Relay SDK with Viem

Getting Started with Relay SDK and Viem

This section is designed to assist developers in implementing the Relay SDK with Viem as an alternative to Ethers.

Installation

To start using the Relay SDK with Viem, you need to install the necessary packages:

npm install @gelatonetwork/relay-sdk-viem 

Configuration

Basic Configuration

Set up your project to use Viem by configuring the Relay SDK as follows:

import { GelatoRelay } from "@gelatonetwork/relay-sdk-viem";
import { createPublicClient, http } from "viem";
import { sepolia } from "viem/chains";

const client = createPublicClient({
  chain: sepolia,
  transport: http(),
});

const relay = new GelatoRelay(client);

Example Usage: Sponsored Call with ERC-2771

This example demonstrates how to use the sponsoredCallERC2771 method from the Relay SDK, which allows transactions to be sponsored using EIP-2771. Learn more about it at sponsoredCallERC2771

Prerequisites

Ensure your environment variables are set up by configuring your .env file:

PRIVATE_KEY=your_private_key_here
ALCHEMY_KEY=your_alchemy_key_here
GELATO_RELAY_API_KEY=your_gelato_relay_api_key_here
import {
  CallWithERC2771Request,
  GelatoRelay,
} from "@gelatonetwork/relay-sdk-viem";
import { createWalletClient, http, encodeFunctionData, Hex } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { sepolia } from "viem/chains";
import * as dotenv from "dotenv";
import { Contract, BytesLike } from "ethers";
dotenv.config({ path: ".env" });
import { counterAbi } from "../utils/counterAbi";
const privateKey = process.env.PRIVATE_KEY;

const testSponsoredCallERC2771 = async () => {
  const relay = new GelatoRelay();

  const account = privateKeyToAccount(privateKey as Hex);
  const client = createWalletClient({
    account,
    transport: http(
      `https://eth-sepolia.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`
    ),
  });
  console.log(account.address);
  const GELATO_RELAY_API_KEY = process.env.GELATO_RELAY_API_KEY as string;
  const counterAddress = "0x00172f67db60E5fA346e599cdE675f0ca213b47b";
  const chainId = await client.getChainId();

  //encode function data
  const data = encodeFunctionData({
    abi: counterAbi,
    functionName: "increment",
  });

  const relayRequest = {
    user: account.address,
    chainId: BigInt(chainId),
    target: counterAddress,
    data: data as BytesLike,
  } as CallWithERC2771Request;

  const response = await relay.sponsoredCallERC2771(
    relayRequest,
    client as any,
    GELATO_RELAY_API_KEY
  );
  console.log(`https://relay.gelato.digital/tasks/status/${response.taskId}`);
};

testSponsoredCallERC2771();

This guide outlines the initial setup and demonstrates how to utilize the Relay SDK with Viem for sponsoring transactions. To explore more SDK methods and capabilities, please visit:

Last updated