Viem is a TypeScript interface for Ethereum, providing low-level primitives for interacting with Ethereum. This guide
will show you how to integrate Capsule’s wallet and signing capabilities with both Viem v2 (recommended) and v1.
Prerequisites
Before integrating Capsule with Viem, ensure you have:
- Set up authentication with Capsule. See our
Getting Started guides for details.
- Configured the Capsule client in your application
If you haven’t set up Capsule authentication yet, complete one of our authentication tutorials first and return to
this guide when you’re ready to implement Viem integration.
Viem v2
Installation
Choose your preferred package manager to install the required dependencies:
Usage
First, set up the Capsule account and Viem client:
import { createCapsuleViemClient, createCapsuleAccount } from "@usecapsule/viem-v2-integration";
import { http, parseEther, parseGwei } from "viem";
import { sepolia } from "viem/chains";
import { capsuleClient } from "./capsuleClient";
const viemCapsuleAccount = await createCapsuleAccount(capsuleClient);
const capsuleViemSigner = createCapsuleViemClient(capsuleClient, {
account: viemCapsuleAccount,
chain: sepolia,
transport: http("https://ethereum-sepolia-rpc.publicnode.com"),
});
Example of signing a transaction:
const transaction = {
account: viemCapsuleAccount,
chain: sepolia,
to: "0x..." as `0x${string}`,
value: parseEther("0.1"),
gas: parseGwei("21000"),
gasPrice: parseEther("0.000000001"),
};
try {
const signedTx = await capsuleViemSigner.signTransaction(transaction);
console.log("Signed transaction:", signedTx);
} catch (error) {
console.error("Error signing transaction:", error);
}
Viem v1 (Legacy)
Installation
Install the v1-specific integration package:
Usage
The setup process for v1 is similar to v2:
import { createCapsuleViemClient, createCapsuleAccount } from "@usecapsule/viem-v1-integration";
import { http } from "viem";
import { sepolia } from "viem/chains";
import { capsuleClient } from "./capsuleClient";
const viemCapsuleAccount = await createCapsuleAccount(capsuleClient);
const capsuleViemSigner = createCapsuleViemClient(capsuleClient, {
account: viemCapsuleAccount,
chain: sepolia,
transport: http("https://ethereum-sepolia-rpc.publicnode.com"),
});
Example transaction signing with v1:
const transaction = {
to: "0x...",
value: "0.1",
gasLimit: "21000",
gasPrice: "1000000000",
};
try {
const signedTx = await capsuleViemSigner.signTransaction(transaction);
console.log("Signed transaction:", signedTx);
} catch (error) {
console.error("Error signing transaction:", error);
}
Server-Side Usage
While Viem can be used in both client and server environments, some considerations apply when using it server-side with
Capsule. For server-side signing operations, please refer to our Server-Side Signing Guide for specific instructions.
When using Viem server-side, ensure you’re following proper security practices and handling authentication
appropriately.
Additional Resources