Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Glossary

viem

viem is a low-level, type-safe TypeScript toolkit for interacting with the Ethereum blockchain and its ecosystem, designed for developers building wallets, dApps, and infrastructure.
Chainscore © 2026
definition
ETHEREUM DEVELOPMENT LIBRARY

What is viem?

Viem is a TypeScript interface for interacting with Ethereum and other EVM-compatible blockchains, designed as a modular, lightweight, and type-safe alternative to comprehensive SDKs.

Viem is a low-level TypeScript library that provides a set of modular abstractions for building applications on Ethereum and EVM-compatible chains. Unlike monolithic SDKs, it offers granular, tree-shakable modules for specific tasks like reading chain data (public actions), executing transactions (wallet actions), or interacting with smart contracts. This architecture allows developers to import only the functionality they need, resulting in significantly smaller bundle sizes and improved application performance.

The library is built with type safety and developer experience as core principles. It leverages TypeScript to its fullest, providing autocomplete, compile-time error checking, and precise type inference for contract ABIs, RPC methods, and transaction parameters. Viem abstracts away the complexity of direct RPC calls, handling tasks like ABI encoding/decoding, gas estimation, and EIP-1559 transaction formatting internally, which reduces boilerplate code and potential errors.

A key architectural feature is its separation of clients and actions. Developers instantiate a client (e.g., createPublicClient, createWalletClient) configured for a specific chain and transport (HTTP, WebSocket, IPC). They then use imported action functions (e.g., readContract, sendTransaction) that operate on that client. This clear separation of concerns makes code more testable and composable. Viem also includes first-class support for WalletConnect, ENS, and advanced patterns like account abstraction and multicall.

In practice, viem is often compared to and used alongside Ethers.js, but it is architecturally distinct. While Ethers.js is a more opinionated, all-in-one toolkit, viem adopts a minimalist, functional approach. It is the recommended library for frameworks like Wagmi, which uses viem under the hood for its core blockchain interactions. Its efficiency and precision make it particularly well-suited for both browser-based dApps and backend Node.js services requiring high-performance blockchain connectivity.

etymology
VIEM

Etymology & Origin

The name 'viem' is a modern, minimalist brand identity for a foundational Ethereum development toolkit, chosen for its simplicity and technical resonance.

The term viem (pronounced vye-em) is a coined word, not an acronym, created by the project's founder, Matteo Gaggia. It was selected for its brevity, ease of recall, and the absence of prior associations in the blockchain space, allowing the project to establish its own identity. The name's clean, technical sound aligns with the library's core philosophy of providing a lean, modular, and type-safe interface for Ethereum interaction.

The project originated in 2022 as a direct evolution from and successor to the widely-used ethers.js library. While viem shares a similar high-level goal—enabling developers to interact with the Ethereum blockchain—it was built from the ground up with a fundamentally different architectural philosophy. Its creation was driven by the need for improved TypeScript support, better modularity, and a more focused, composable API that could keep pace with Ethereum's rapidly evolving ecosystem, including Layer 2 rollups.

The development of viem is intrinsically linked to the rise of the Wagmi project, a collection of React Hooks for Ethereum. Wagmi's original core was built on ethers.js, but its creators sought a more type-safe and performant underlying primitive. Viem was developed to be that primitive, leading to a symbiotic relationship where Wagmi provides the frontend framework and viem provides the robust, low-level blockchain communication layer. This origin underscores viem's design as a library for builders of higher-level tools.

Etymologically, viem breaks from the tradition of naming crypto libraries after units of currency (e.g., web3.js, ethers) or playful puns. Its abstract, almost synthetic quality reflects a maturation in developer tooling, prioritizing technical precision and developer experience over thematic naming. This choice signals its role as essential, infrastructural software—the viem through which applications connect to Ethereum, much like a conduit or medium.

key-features
VIEM

Key Features

Viem is a TypeScript interface for Ethereum, providing low-level, modular building blocks for interacting with blockchains. It is designed for reliability, efficiency, and developer experience.

01

TypeScript-First & Type Safe

Viem is built with TypeScript from the ground up, providing full end-to-end type safety. It infers types from ABIs and EIP-712 domains, catching errors at compile time and enabling superior IDE autocompletion. This eliminates a major class of runtime errors common in blockchain development.

02

Modular & Tree-Shakeable

The library is split into small, focused modules (clients, actions, utilities). This allows developers to import only the specific functions they need, such as readContract or sendTransaction, resulting in significantly smaller bundle sizes through tree-shaking. It avoids the bloat of monolithic SDKs.

03

Low-Level Abstraction

Viem operates close to the JSON-RPC layer, giving developers precise control over requests and responses. It provides Wallet Clients, Public Clients, and Test Clients as core primitives, rather than a high-level, opinionated object model. This makes it predictable and excellent for building custom abstractions.

04

Multi-Chain & Multi-Transport

Viem supports Ethereum, Polygon, Arbitrum, Base, and other EVM-compatible chains out of the box. It works with various transport layers including HTTP, WebSocket, and IPC. The Public Client is configured per chain, ensuring correct RPC URLs, chain IDs, and native currency details.

05

Wallet & Signer Integration

It provides a Wallet Client for managing private keys, JSON-RPC Accounts (e.g., MetaMask), and local Private Key Accounts. Viem handles transaction signing, message signing, and typed data signing (EIP-712) uniformly across these account types, abstracting wallet-specific complexities.

06

Utility-First Design

Core operations are exposed as simple, composable functions. For example:

  • encodeFunctionData for calldata
  • parseUnits for unit conversion
  • getAddress for address checksums
  • verifyMessage for signature verification This utility-first approach makes code explicit and easy to reason about.
how-it-works
VIEM

How It Works: Architecture & Flow

An explanation of viem's modular architecture and how its core components interact to provide a robust TypeScript interface for Ethereum.

Viem is a modular, type-safe, and low-level TypeScript library for interacting with the Ethereum blockchain and its ecosystem. Its architecture is built around a clear separation of concerns, organized into distinct clients, transports, and actions. The foundational Client object, configured with a specific Transport (like HTTP or WebSocket), serves as the primary interface. This client then exposes public actions—modular functions for specific operations like reading chain data or sending transactions—which internally call the transport to communicate with a node. This design enables powerful type inference, excellent tree-shaking, and flexible composition for developers.

The data flow in viem begins with a developer importing and creating a client. For example, createPublicClient is used for read operations, requiring a transport such as http() to connect to a JSON-RPC provider. When an action like getBlockNumber is called on this client, the request is serialized, passed through the configured transport layer to the node, and the response is deserialized and strongly typed before being returned. For writing to the chain, a Wallet Client (createWalletClient) is used, which manages private keys or connectors (e.g., for browser wallets) to sign transactions before they are broadcast via the public client's transport.

Key architectural concepts include its modular actions, which are imported on-demand to keep bundle sizes minimal, and its extensive support for Account Abstraction via the viem/accounts submodule, which provides utilities for managing different private key types and signing methods. The library also features a comprehensive ABI-driven type system; when you provide a contract's ABI to a readContract or writeContract action, viem infers the exact function names, argument types, and return types, providing full autocompletion and compile-time safety. This makes interacting with smart contracts far less error-prone.

Beyond core Ethereum, viem's architecture extends to L2s and other chains through its chains module. Developers can import chain definitions (e.g., arbitrum, polygon) and pass them during client creation. The client automatically uses the correct RPC URLs, chain IDs, and native currency information. Furthermore, viem includes specialized utilities for ens, multicall batching, and error handling with custom error classes, making it a comprehensive toolkit that abstracts away the complexities of direct RPC communication while remaining flexible and performant.

code-example
VIEM

Code Example: Reading a Contract

A practical demonstration of how to use the viem TypeScript library to read data from a smart contract on the Ethereum blockchain.

This example demonstrates the fundamental pattern for querying a smart contract's state using viem's readContract function, which executes a view or pure function without sending a transaction or paying gas. The core steps involve: - Importing the necessary clients and functions from viem. - Configuring a public client for the desired blockchain network (e.g., mainnet). - Defining the target contract's address, Application Binary Interface (ABI), and the specific function to call. - Executing the read call and handling the returned data. This pattern is essential for fetching on-chain data like token balances, governance proposals, or protocol parameters.

A typical implementation begins by setting up a public client using createPublicClient and a transport like http(). The contract's ABI is a critical component, as it provides the type definitions that viem uses to encode the function call and decode the response. For example, to read the totalSupply of an ERC-20 token, you would import or define the ERC-20 ABI snippet containing the totalSupply function. The readContract function is then called with an object containing the client, the contract's address, the abi, the functionName, and any required args (arguments) for the function.

Error handling and type safety are paramount. Viem, being a TypeScript-first library, leverages the provided ABI to infer the return type of the function call, ensuring the result is correctly typed. Network-specific considerations, such as multicall batching for efficiency or handling RPC rate limits, can be addressed using viem's extended client capabilities. This code pattern forms the basis for more advanced interactions, such as simulating transactions with simulateContract or writing to contracts with writeContract, establishing viem as a comprehensive toolkit for Ethereum development.

ecosystem-usage
VIEM

Ecosystem Usage

Viem is a TypeScript interface for Ethereum, providing low-level stateless primitives for interacting with blockchains. It is the foundational library for modern Ethereum development, powering wallets, dApps, and developer tools.

05

Performance & Bundle Size

Viem is engineered for performance and minimal bundle size, making it ideal for production applications.

  • Tree-shaking: Its modular architecture allows bundlers to include only the used code paths, drastically reducing final bundle size.
  • No Dependencies: Viem has zero runtime dependencies, improving security and reliability.
  • Benchmarks: Compared to predecessors like ethers.js, Viem offers faster ABI encoding/decoding and more efficient BigInt handling. These characteristics make it the preferred choice for performance-critical applications and browser extensions.
06

Advanced Use Cases & Utilities

Beyond basic RPC calls, Viem provides utilities for complex blockchain interactions and data analysis.

  • Multicall: Batch multiple contract view calls into a single RPC request for efficiency.
  • Event Watching: Subscribe to and decode contract events with real-time streams.
  • Bytecode Utilities: Analyze and decompose contract bytecode and deployedBytecode.
  • Gas Estimation: Advanced fee estimation with support for EIP-1559 and priority fee calculations.
  • Unit Conversion: Reliable utilities for converting between wei, gwei, and ether.
LIBRARY COMPARISON

Comparison: viem vs. ethers.js vs. web3.js

A technical comparison of key features, architecture, and performance characteristics of three prominent Ethereum JavaScript libraries.

Feature / Metricviemethers.jsweb3.js

Primary Architecture

TypeScript-first, modular

Monolithic, object-oriented

Monolithic, callback/promise-based

Bundle Size (core)

~150 KB

~400 KB

~1 MB

Tree-shakable

Type Safety

Strict, generated from ABIs

Good, manual definitions

Basic, limited

Account Abstraction (ERC-4337)

Native support

Plugin required

Limited support

Multichain Support

Native, type-safe

Via providers/network objects

Via provider configuration

Provider Agnosticism

Performance (tx/s benchmark)

~12,500

~8,200

~4,100

security-considerations
VIEM

Security Considerations & Best Practices

While viem is a robust library, its security depends heavily on correct implementation. These cards outline critical security patterns and common pitfalls to avoid when using viem in production.

01

Private Key & Mnemonic Management

Never embed private keys or mnemonics in client-side code or commit them to version control. Use environment variables or secure secret management services. For browser environments, leverage wallet connection flows (e.g., WalletConnect, MetaMask) instead of direct key usage. viem's createWalletClient with local transport should only be used in secure, server-side contexts with keys injected via environment variables.

  • Insecure: const privateKey = '0x...' in source code.
  • Secure: const privateKey = process.env.PRIVATE_KEY from a secure environment.
02

Transaction Simulation & Gas Estimation

Always simulate transactions before broadcasting using simulateContract or estimateGas. This validates that the transaction will execute without reverting and provides an accurate gas estimate, preventing failed transactions and lost gas fees. For complex interactions, consider using Tenderly or OpenZeppelin Defender for advanced simulation and gas profiling.

  • Key Function: publicClient.simulateContract({ ... })
  • Best Practice: Use the returned request object from simulation to send the transaction, ensuring consistency.
03

Handling User Input & Contract Calls

Sanitize and validate all user inputs before passing them to contract functions to prevent malformed calldata or unexpected state changes. Use TypeScript interfaces and viem's type generation (viem abi) to enforce correct argument types. Be cautious with writeContract functions that accept dynamic arrays or strings, as these can be vectors for unexpected behavior.

  • Use: viem's ABI TypeScript generation for strict type safety.
  • Validate: Addresses with isAddress, numeric ranges, and string lengths.
04

Error Handling & Resilience

Implement comprehensive error handling for all JSON-RPC calls. Network requests can fail, nodes can return errors, and contracts can revert. Use try/catch blocks and handle specific viem errors (e.g., ContractFunctionRevertedError, TransactionExecutionError). Implement retry logic with exponential backoff for transient network failures and set appropriate timeout configurations on clients.

  • Critical Errors: ContractFunctionRevertedError contains the revert reason.
  • Client Config: Set batch and retryCount options for reliability.
05

Wallet Client & Signer Isolation

Isolate wallet clients (signers) from public clients (readers). A Wallet Client holds signing authority and should have minimal, audited exposure, typically only used for sendTransaction or signMessage. A Public Client is used for all read operations (readContract, getLogs). This separation follows the principle of least privilege and reduces the attack surface if a public client connection is compromised.

  • Pattern: Instantiate separate createPublicClient and createWalletClient objects.
  • Benefit: Prevents accidental signing from read-only code paths.
06

Dependency & Version Pinning

Pin your viem dependency to a specific, stable version in your package.json to prevent unexpected breaking changes or the introduction of vulnerabilities from automatic updates. Regularly audit dependencies and update deliberately after testing. Subscribe to security advisories for viem and its underlying dependencies (e.g., via GitHub or Snyk).

  • Use: Exact versions ("viem": "2.0.0") or lockfiles (package-lock.json).
  • Audit: Run npm audit or use Dependabot for vulnerability alerts.
VIEM

Common Misconceptions

Clarifying frequent misunderstandings about viem, a popular TypeScript interface for Ethereum, to help developers use it more effectively.

No, viem is not a wrapper for ethers.js; it is a distinct, from-scratch TypeScript library built with a fundamentally different architecture. While both libraries enable interaction with the Ethereum blockchain, viem employs a modular, type-safe design that separates concerns like account abstraction, client management, and RPC communication into discrete packages. This design prioritizes tree-shaking, smaller bundle sizes, and stricter compile-time type safety. Unlike ethers.js's more monolithic class-based structure, viem uses a functional composition pattern, leading to different API patterns and performance characteristics.

VIEM

Technical Deep Dive

Viem is a TypeScript interface for Ethereum, providing low-level stateless primitives for building wallets, applications, and tools. This section answers common developer questions about its architecture, usage, and advantages.

Viem is a TypeScript library that provides low-level, modular, and stateless primitives for interacting with Ethereum and other EVM-compatible blockchains. It works by separating concerns into distinct clients (Public, Wallet, Test) and transports (HTTP, WebSocket, IPC), allowing developers to compose precisely the functionality they need without unnecessary abstraction. Unlike monolithic SDKs, viem's stateless design means it doesn't manage user state internally, making it more predictable, easier to test, and highly performant for both Node.js and browser environments.

VIEM

Frequently Asked Questions (FAQ)

Essential questions and answers about viem, a TypeScript interface for interacting with Ethereum and other EVM-compatible blockchains.

Viem is a modular, type-safe, and low-level TypeScript library for interacting with the Ethereum Virtual Machine (EVM). It works by providing a collection of clients (Public, Wallet, Test) that handle specific functionalities like reading chain data, managing accounts, and deploying contracts, all while offering superior type inference and bundle size optimization compared to alternatives. Its architecture separates concerns, allowing developers to compose only the tools they need, such as using a Public Client with an HTTP RPC URL to query blockchain state and a Wallet Client with a private key to sign and send transactions.

ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team
What is viem? | Ethereum TypeScript Interface | ChainScore Glossary