Sending ERC20 Tokens in Batch with Axir Smart Account
This guide covers how to send ERC20 tokens to multiple recipients in a single transaction.
Prerequisites
First, import the required dependencies:
import { AxirCore } from "axr-erc4337-sdk";
import { ethers } from "ethers";
import { type Hex } from "viem";
Implementation
1. Initialize AxirCore
First, create an instance of AxirCore:
const axirCore = new AxirCore(
process.env.PRIVATE_KEY as Hex,
process.env.RPC_URL as string,
process.env.BUNDLER_URL as string,
BigInt(0), // nonce
"baseSepolia" // network name
);
2. Send Batch ERC20 Transfers
Follow these steps to send multiple ERC20 token transfers in one transaction:
// Prepare batch ERC20 transfer UserOperation
const batchUserOp = await axirCore.prepareUserOperation(
[
{
contract: tokenAddress,
value: 0n,
abi: [
{
type: "function",
name: "transfer",
inputs: [
{ name: "recipient", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ type: "bool" }],
stateMutability: "nonpayable",
},
],
functionName: "transfer",
args: [receiver1Address, ethers.parseUnits("0.001", tokenDecimals)],
},
{
contract: tokenAddress,
value: 0n,
abi: [
{
type: "function",
name: "transfer",
inputs: [
{ name: "recipient", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ type: "bool" }],
stateMutability: "nonpayable",
},
],
functionName: "transfer",
args: [receiver2Address, ethers.parseUnits("0.002", tokenDecimals)],
},
],
undefined,
usePaymaster,
paymasterType
);
// Estimate gas costs
const gasEstimate = await axirCore.estimateUserOperationGas(
batchUserOp,
usePaymaster,
paymasterType
);
// Log gas estimates
console.log("Gas Estimation for batch ERC20 transfer:");
if (gasEstimate.totalGasFeeInEth) {
console.log(
`Estimated gas fee in ETH: ${ethers.formatEther(
gasEstimate.totalGasFeeInEth
)} ETH`
);
}
if (gasEstimate.totalGasFeeInToken) {
console.log(
`Estimated gas fee in tokens: ${ethers.formatUnits(
gasEstimate.totalGasFeeInToken,
gasEstimate.tokenDecimals
)} ${gasEstimate.tokenSymbol}`
);
}
// Execute the batch transaction
const txHash = await axirCore.executeUserOperation(batchUserOp);
console.log("Batch transaction hash:", txHash);
info
Batch transfers can save gas costs compared to multiple individual transactions.
tip
You can mix different token transfers in the same batch transaction, just make sure to use the correct token address and decimals for each transfer.