Skip to main content
Batching transactions combines multiple operations into a single transaction. Instead of staking tokens and claiming rewards separately, users can perform both in one transaction.

Getting Started

1

Import Dependencies

import {
  createGelatoSmartAccountClient,
  toGelatoSmartAccount,
  sponsored,
  StatusCode,
} from "@gelatocloud/gasless";
import { createPublicClient, http, type Hex, encodeFunctionData } from "viem";
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";
2

Setup Smart Account

const owner = privateKeyToAccount(
  (process.env.PRIVATE_KEY ?? generatePrivateKey()) as Hex
);

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

const account = toGelatoSmartAccount({
  client,
  owner,
});
3

Create Relayer Client

To create an API Key, visit the Gelato App and navigate to Paymaster & Bundler > API Keys.
const relayer = await createGelatoSmartAccountClient({
  account,
  apiKey: process.env.GELATO_API_KEY,
});
4

Batch Multiple Transactions

Add multiple operations to the calls array:
const result = await relayer.sendTransactionSync({
  payment: sponsored(),
  calls: [
    {
      to: "<token-address>",
      data: encodeFunctionData({
        abi: tokenAbi,
        functionName: "approve",
        args: [targetContractAddress, amount],
      }),
    },
    {
      to: "<target-contract-address>",
      data: encodeFunctionData({
        abi: targetContractAbi,
        functionName: "stake",
        args: [amount],
      }),
    },
    {
      to: "<target-contract-address>",
      data: encodeFunctionData({
        abi: targetContractAbi,
        functionName: "claimRewards",
        args: [],
      }),
    },
  ],
});

if (result.status === StatusCode.Included) {
  console.log(`Transaction hash: ${result.receipt.transactionHash}`);
} else {
  console.log(`Failed: ${result.message}`);
}