Skip to main content

Batch Transactions

Demo

Introduction

One great advantage of smart contract wallets is the ability to execute transactions in batches. That is, you can execute multiple transactions as if it's a single transaction, so you get to save on confirmation time and gas costs. It's also safer because these transactions either all execute or all revert, no in-between, which is a property known as "atomicity."

API

SDK

const txn = await ecdsaProvider.sendUserOperation([
{
target: "targetAddress1",
data: "callData1",
value: value1,
},
{
target: "targetAddress2",
data: "callData2",
value: value2,
},
])

Each object in the array can have three properties:

  • target: the contract you are interacting with
  • data: the calldata
  • value: the ETH value of the transaction (can be undefined)

To encode the calldata, you can use Viem's encodeFunctionData, like this:

import { encodeFunctionData, parseAbi } from 'viem'

const contractABI = parseAbi([
'function mint(address _to) public',
])

const userOp = {
target: contractAddress,
data: encodeFunctionData({
abi: contractABI,
functionName: 'mint',
args: [address],
}),
}

// Batch two mints in one transaction
const { hash } = await ecdsaProvider.sendUserOperation([
userOp,
userOp,
])

Wagmi

import { usePrepareContractBatchWrite, useContractBatchWrite  } from "@zerodev/wagmi";
Full Code (Editable)
Result
Loading...