Skip to main content

isGasSponsorshipError

A type guard function that checks if an error is related to gas sponsorship policies. This is useful for handling cases where a transaction was expected to be sponsored but didn’t match any sponsorship policies.

Usage

import {
  createKernelClientForWalletAccount,
  isGasSponsorshipError
} from "@dynamic-labs-sdk/zerodev";
import { isEvmWalletAccount } from "@dynamic-labs-sdk/evm";
import { getPrimaryWalletAccount } from "@dynamic-labs-sdk/client";
import { parseEther } from "viem";

const walletAccount = getPrimaryWalletAccount();

if (walletAccount && isEvmWalletAccount(walletAccount)) {
  const kernelClient = await createKernelClientForWalletAccount({
    smartWalletAccount: walletAccount,
  });

  try {
    await kernelClient.sendTransaction({
      to: recipientAddress,
      value: parseEther("0.01"),
    });
  } catch (error) {
    if (isGasSponsorshipError(error)) {
      console.log("Transaction not sponsored - user needs to pay gas");
      // Handle by retrying without sponsorship or showing user a message
    } else {
      throw error;
    }
  }
}

Parameters

ParameterTypeDescription
errunknownThe error to check

Returns

boolean - Returns true if the error is a gas sponsorship error, false otherwise.

React

Use isGasSponsorshipError inside a button handler’s catch block to show appropriate UI when sponsorship fails:
import { createKernelClientForWalletAccount, isGasSponsorshipError } from '@dynamic-labs-sdk/zerodev';
import { isEvmWalletAccount } from '@dynamic-labs-sdk/evm';
import { useWalletAccounts } from '@dynamic-labs-sdk/react-hooks';
import { useState } from 'react';
import { parseEther } from 'viem';

function SendButton({ recipientAddress }) {
  const walletAccounts = useWalletAccounts();
  const walletAccount = walletAccounts.find(isEvmWalletAccount);
  const [error, setError] = useState('');

  const handleSend = async () => {
    if (!walletAccount) return;
    setError('');
    try {
      const kernelClient = await createKernelClientForWalletAccount({ smartWalletAccount: walletAccount });
      await kernelClient.sendTransaction({ to: recipientAddress, value: parseEther('0.01') });
    } catch (err) {
      if (isGasSponsorshipError(err)) {
        setError('This transaction cannot be sponsored. The user must pay gas.');
      } else {
        throw err;
      }
    }
  };

  return (
    <div>
      <button onClick={handleSend} disabled={!walletAccount}>Send</button>
      {error && <p style={{ color: 'orange' }}>{error}</p>}
    </div>
  );
}