Sending ERC20 Tokens with Axir Smart Account
This guide explains how to send ERC20 tokens using your Axir smart account.
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 ERC20 Transaction
Follow these steps to send an ERC20 token transfer:
// Prepare ERC20 transfer UserOperation
const erc20UserOp = 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: [receiverAddress, ethers.parseUnits(amount, tokenDecimals)],
},
undefined,
usePaymaster,
paymasterType
);
// Estimate gas costs
const gasEstimate = await axirCore.estimateUserOperationGas(
erc20UserOp,
usePaymaster,
paymasterType
);
// Log gas estimates
console.log("Gas Estimation for 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 transaction
const txHash = await axirCore.executeUserOperation(erc20UserOp);
console.log("Transaction hash:", txHash);
info
Make sure you have sufficient token balance and that the smart account has approved the token spending if required.
tip
For token transfers, you might need to approve the paymaster contract if using ERC20 tokens for gas fees.