Table of contents

The Promise of viem: A TypeScript Library for Interacting with Ethereum

https://www.dynamic.xyz/blog/the-promise-of-viem-a-typescript-library-for-interacting-with-ethereum
The Promise of viem: A TypeScript Library for Interacting with Ethereum
The Promise of viem: A TypeScript Library for Interacting with Ethereum
Download

A wild and sometimes untamed frontier

Ah, the world of blockchain development – a wild and sometimes untamed frontier. It's a place where developers are constantly innovating, exploring new technologies, and, of course, trying to make sense of ethers and web3.js. These two libraries have been the go-to solutions for interacting with Ethereum, but as the saying goes, "three's a party!" Enter viem, a new TypeScript library that promises to make blockchain development a breeze.

In this blog post, we'll dive into the world of viem, a promising library from the creators of wagmi. But before we do, let's take a quick trip down memory lane and explore the origins of ethers and web3.js.

A Tale of Two Libraries

Ethers and web3.js have been the bread and butter of Ethereum developers for quite some time now. With their extensive set of features, they've enabled countless developers to build powerful and secure decentralized applications (dApps).

Ethers.js came to life as a lightweight, modular, and easy-to-use alternative to web3.js (you can read more about it in our recent blog post). It aimed to provide a more consistent and user-friendly API, and quickly gained popularity among developers. Web3.js, on the other hand, has been around for a while, and although it's a bit bulkier and more complex, it's still considered the de facto standard for many Ethereum developers.

But as any ethereum developer will tell you, none of these libraries are perfect. Both ethers and web3.js have their quirks and limitations, which brings us to the birth of viem.

The Birth of viem

Tom and Jake, the developers behind wagmi, a popular React Hooks library for Ethereum, decided to take matters into their own hands and created viem. Their goal was to provide a better developer experience, increased stability, smaller bundle size, and improved performance.

Here is how Tom and Jake defined the problem:
“The current state of low-level Ethereum interface abstractions lack in at least one of the following four areas: developer experience, stability, bundle size and/or performance — a quadrilemma.
As the authors of wagmi, a popular React Hooks library for Ethereum, we struggled to work with the existing low-level TypeScript Ethereum libraries. We wanted to provide the users of wagmi with the best possible developer experience, but we were limited by the underlying technologies wagmi was built on. We knew an always stable, predictable implementation with a tiny bundle size and performant modules was paramount to interacting with the world's largest blockchain ecosystem.
So we created viem: a TypeScript Interface for Ethereum that provides low-level stateless primitives for interacting with Ethereum. An alternative to ethers and web3.js with a focus on reliability, efficiency, and excellent developer experience.“

But what makes viem different from its predecessors? It comes down to four key elements:

1. Developer Experience through verbose writing

viem aims to provide a good developer experience through modular and composable APIs, comprehensive documentation, and automatic type safety and inference. While the APIs may be more verbose, they offer greater flexibility and help developers better understand Ethereum concepts.

2. Stability through test coverage

Stability is a core principle for viem. The team ensures this by running their test suite against a forked Ethereum node, aiming for complete test coverage, and building deterministic and pure APIs.

3. Focus on keeping bundle size low

When it comes to web applications, keeping things lean and efficient is crucial. Viem boasts a minimalist modular architecture and an impressively small bundle size of just 35kB, which helps to reduce the impact on your users' bandwidth. In comparison, ethers.js is an order of magnitude heavier, with web3.js being even larger.

4. Performance via async tasks

Viem only executes heavy asynchronous tasks when required and utilizes optimized encoding/parsing algorithms.

How viem is Different

Ultimately, the choice between ethers, web3js and viem comes down to personal preference and the specific needs of the developer. For those who prioritize simplicity, reliability, and efficiency, viem may be an ideal choice.

Unlike other low-level interfaces that impose opinions on consumers, viem enables consumers to choose their opinions while still maintaining sensible and secure defaults. This allows consumers to create their own opinionated implementations, such as wagmi, without the need for tedious workarounds.

viem also provides consumers with strongly typed APIs, allowing consumers to get the best possible experience through autocomplete, type inference, as well as static validation. It uses a documentation and test-driven development approach to building modules, which leads to predictable and stable APIs.

As an example, here is one difference between the libraries, as illustrated by the co-creator of viem:

viem providers are called clients, with a total of three:

  • Public Client - like the ethers providers - should be used to access block-chain info (transactions, block numbers, balance, etc…)
  • Wallet Client - like Ethers signers, should be used for signing transactions, messages
  • Test Client - to test the different actions on local test node.

To illustrate additional key differences, let's explore a few examples that show how different common actions differ between viem and ethers:

JsonRPC Provider:

ethers.js:
import { providers } from 'ethers'

const provider = new providers.JsonRpcProvider('https://cloudflare-eth.com')
viem:
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'

const client = createPublicClient({
  chain: mainnet,
  transport: http('https://cloudflare-eth.com')
})

Note: Instead of having a a different provider for each RPC Provider (Alchemy/Infura/etc..) you only need to change the transport url.


Wallet Client:

ethers.js:
import { providers } from 'ethers'

const provider = new providers.Web3Provider(window.ethereum)
const signer = provider.getSigner(address)

signer.sendTransaction({ ... })
viem:
import { createWalletClient, custom } from 'viem'
import { mainnet } from 'viem/chains'
const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' })

const client = createWalletClient({
	account,
  chain: mainnet,
  transport: custom(window.ethereum)
})

client.sendTransaction({ ... })

Notes:

 - Account is an optional arg that is only needed for actions that require signing.

- The custom transport is a wrapper to injected wallets and EIP-1193 wallet-providers

As seen in these examples, each library has its way of handling providers and wallet clients. Viem aims for a more modular and composable approach, resulting in leaner and more efficient code.

Growth and challenges

While viem shows great promise, it's still the new kid on the block(chain), and is still untested in the wild. Facing real-world applications will be the ultimate trial, pitting it against established competitors like ethers and web3.js. There are some learnings that only appear when developers use a product in unexpected ways, leading to growth and innovation, but at times growing pains.

One specific challenge viem might face is its minimalist modular architecture, which may require developers to import more modules than expected. While not necessarily a downside, this could still require some "brain rewiring", especially among seasoned developers who are accustomed to more comprehensive libraries. (an analogy, in this case, can be the differences between Angular and React, the latter of which is more verbose).

Overall, the potential of viem is exciting, and its emergence indicates that the blockchain space is still growing and evolving. With more tools and libraries like viem, developers can continue to push the boundaries of what is possible on the blockchain, and bring the power of this revolutionary technology to a wider audience. Its strong focus on developer experience, stability, and performance might just be the winning combination that leads to widespread adoption. After all, who doesn't love a good underdog story?

Going beyond viem and ethers

Ethers, viem and others opens the door to interacting with EVM networks, but do not on their own assist in interacting with the myriad of wallets available - whether they are injected, mobile, embedded or others. 

Dynamic is a flexible web3 auth platform

Dynamic, a powerful web3 auth developer platform, sets to tackle exactly that. We abstract away wallet-based auth from developers using ethers with a flexible developer SDK. If you’re building in web3, we recommend exploring Dynamic - you can get started here.

References

If you're interested in learning more about viem, ethers, or web3.js, here are some resources to check out:

Share this article

https://www.dynamic.xyz/blog/the-promise-of-viem-a-typescript-library-for-interacting-with-ethereum
Itai Turbahn

Itai is the co-founder and CEO of Dynamic. Before Dynamic, Itai spent 7 years in product management leadership positions, and was previously a consultant at the Boston Consulting Group. Itai holds an MBA from Harvard Business School and B.Sc degrees in EECS and Economics from MIT.

Related articles

Dynamic takes minutes to set up

(Oh, and we also offer a free multi-chain wallet adaptor)

Get started