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:
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: