One of the key features of the Smart Wallet SDK is its ability to estimate gas costs before sending a transaction on-chain—across different gas payment methods.

Gas estimation is crucial for ensuring transactions are processed smoothly and efficiently. It helps developers and users avoid failed transactions due to underpayment and provides better transparency into the expected cost of execution, improving both reliability and user experience.

Getting Started

1

Setup Smart Wallet Client

Quickly set up the Smart Wallet client as outlined in the How-To Guides.

import { createGelatoSmartWalletClient, sponsored } from "@gelatonetwork/smartwallet";
import { createWalletClient, createPublicClient, http } from "viem";
import { gelato } from "@gelatonetwork/smartwallet/accounts";
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";

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

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

const account = await gelato({
  owner: signer,
  client: publicClient,
});

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

const smartWalletClient = createGelatoSmartWalletClient(client);
2

Estimate Gas

Use estimate instead of execute when estimating gas for transactions with different gas payment methods.

Note: When estimating gas for ERC-20 tokens, the results will be based on the token’s decimals. Ensure you format the results accordingly. Learn how to use different gas payment methods here.

const results = await smartWalletClient.estimate({
  payment: sponsored(sponsorApiKey),
  calls: [
    {
      to: "0xa8851f5f279eD47a292f09CA2b6D40736a51788E",
      data: "0xd09de08a",
      value: 0n
    }
  ]
});

console.log(`Estimated fee: ${formatEther(results.fee.amount)} ETH`);
console.log(`Estimated gas: ${results.fee.gas} GAS`);
3

Estimate Gas for Multiple Transactions

You can also estimate gas for multiple transactions by adding them to the calls array:

const results = await smartWalletClient.estimate({
  payment: sponsored(sponsorApiKey),
  calls: [
    {
      to: "0xa8851f5f279eD47a292f09CA2b6D40736a51788E",
      data: "0xd09de08a",
      value: 0n
    },
    {
      to: "0xa8851f5f279eD47a292f09CA2b6D40736a51788E",
      data: "0xd09de08a",
      value: 0n
    }
  ]
});

console.log(`Estimated fee: ${formatEther(results.fee.amount)} ETH`);
console.log(`Estimated gas: ${results.fee.gas} GAS`);

Additional Resources

  • Check out the full example code for estimating gas for sponsored transactions here.