This guide will walk you through the process of setting up Capsule with Viem, a modern Ethereum library. We’ll cover both v1 and v2 of Viem, as Capsule provides integration packages for both versions.

Installation

First, you’ll need to install the necessary packages. Choose the appropriate package based on your Viem version:

Setting Up Capsule with Viem v2

Here’s how to set up Capsule with Viem v2:

import { createCapsuleViemClient, createCapsuleAccount } from '@usecapsule/viem-v2-integration';
import { http } from 'viem';
import { sepolia } from 'viem/chains';
import Capsule from '@usecapsule/web-sdk';

// Initialize Capsule
const capsule = new Capsule(Environment.BETA, YOUR_API_KEY);

// Create the Capsule Viem Client
const viemClient = createCapsuleViemClient(capsule, {
  chain: sepolia,
  transport: http(YOUR_RPC_URL),
});

// Create a Capsule Account
const account = createCapsuleAccount(capsule);

Setting Up Capsule with Viem v1

For Viem v1, the setup is similar:

import { createCapsuleViemClient, createCapsuleAccount } from '@usecapsule/viem-v1-integration';
import { http } from 'viem';
import { sepolia } from 'viem/chains';
import Capsule from '@usecapsule/web-sdk';

// Initialize Capsule
const capsule = new Capsule(Environment.BETA, YOUR_API_KEY);

// Create the Capsule Viem Client
const viemClient = createCapsuleViemClient(capsule, {
  chain: sepolia,
  transport: http(YOUR_RPC_URL),
});

// Create a Capsule Account
const account = createCapsuleAccount(capsule);

Usage

Once you’ve set up the Capsule Viem Client and Account, you can use them to interact with the Ethereum network. Here’s a basic example:

// Get the account address
const address = account.address;
console.log('Account address:', address);

// Get the balance
const balance = await viemClient.getBalance({ address });
console.log('Balance:', balance);

Server-Side Usage

If you need to use Capsule with Viem on the server-side, please check our Server-Side Signing Guide for specific instructions.

Remember to always handle errors appropriately and ensure your user is authenticated with Capsule before attempting to use the client or account.

For more advanced usage and a complete API reference, please refer to the Viem documentation.