Integrating Base Paymaster for Gasless Transactions in a Wagmi Project

·

This guide provides a step-by-step walkthrough for integrating Base Paymaster support into an existing Wagmi project to enable gasless transactions. It covers configuration adjustments, environment setup, and the implementation of experimental Wagmi hooks to facilitate seamless onchain interactions without users needing to pay gas fees.

Initial Setup: Configure Your Account

To begin, you need access to the necessary developer tools. Create a new account or sign into your existing one through the developer platform. This account will grant you access to the paymaster and bundler services required for gasless transactions.

Obtain Paymaster and Bundler Endpoint

Once logged into your dashboard, navigate to the Onchain Tools section and select Paymaster. Within the Configuration tab, choose your desired chain—either Base or Base Sepolia—for sponsoring transactions. Copy the RPC URL provided in the Paymaster & Bundler endpoint section.

Store this URL securely in your project's .env file under a variable like NEXT_PUBLIC_CDP_PAYMASTER. For production applications, consider implementing a proxy service to enhance security and reliability.

Whitelist Contracts

In the Contract allowlist section, specify the smart contract addresses you intend to interact with using the Base Paymaster. For each contract, provide a descriptive name and include the exact functions you plan to use. Click "Add" to confirm each entry, ensuring only authorized contracts can utilize gasless transactions.

Add Base to Wagmi Configuration

Next, update your Wagmi configuration to support the Base network and essential connectors. Open your wagmi.ts file and implement the following setup:

import { http, cookieStorage, createConfig, createStorage } from 'wagmi';
import { base } from 'wagmi/chains';
import { coinbaseWallet, injected, walletConnect } from 'wagmi/connectors';

export function getConfig() {
  return createConfig({
    chains: [base],
    connectors: [
      injected(),
      coinbaseWallet(),
      walletConnect({ projectId: process.env.NEXT_PUBLIC_WC_PROJECT_ID }),
    ],
    storage: createStorage({
      storage: cookieStorage,
    }),
    ssr: true,
    transports: {
      [base.id]: http(),
    },
  });
}

declare module 'wagmi' {
  interface Register {
    config: ReturnType<typeof getConfig>;
  }
}

This configuration enables connectivity to the Base network and integrates popular wallets like Coinbase Wallet and WalletConnect.

Implement Wagmi Hooks for Onchain Actions

For handling onchain actions such as minting NFTs, leverage Wagmi's experimental hooks to manage wallet connections, check paymaster capabilities, and execute transactions.

Below is an example implementation for a minting page:

'use client';
import { useAccount, useConnect, useDisconnect } from 'wagmi';
import { useState, useMemo } from 'react';
import { coinbaseWallet } from 'wagmi/connectors';
import { abi, contractAddress } from '../utils';
import { useCapabilities, useWriteContracts } from 'wagmi/experimental';

export default function MintPage() {
  const { address, isConnected } = useAccount();
  const { connect } = useConnect();
  const { disconnect } = useDisconnect();
  const [isMinting, setIsMinting] = useState(false);

  const { writeContracts } = useWriteContracts({
    mutation: { onSuccess: () => console.log('Mint successful') },
  });

  const handleMint = async () => {
    setIsMinting(true);
    try {
      writeContracts({
        contracts: [
          {
            address: contractAddress,
            abi,
            functionName: 'mintTo',
            args: [address],
          },
        ],
        capabilities,
      });
    } catch (error) {
      console.error('Minting failed:', error);
    } finally {
      setIsMinting(false);
    }
  };

  const { data: availableCapabilities } = useCapabilities({
    account: address,
  });

  const capabilities = useMemo(() => {
    if (!availableCapabilities || !address) return {};
    const capabilitiesForChain = availableCapabilities[address.chainId];
    if (
      capabilitiesForChain['paymasterService'] &&
      capabilitiesForChain['paymasterService'].supported
    ) {
      return {
        paymasterService: {
          url: `https://api.developer.coinbase.com/rpc/v1/base/`, // Use proxy in production
        },
      };
    }
    return {};
  }, [availableCapabilities, address]);

  return (
    <div>
      <p>{isConnected ? `Connected wallet: ${address}` : 'No wallet connected'}</p>
      <button
        onClick={() => connect({ connector: coinbaseWallet() })}
      >
        {isMinting ? 'Minting...' : isConnected ? 'Mint NFT' : 'Connect Wallet'}
      </button>
      {isConnected && <button onClick={() => disconnect()}>Disconnect</button>}
    </div>
  );
}

By following these steps, you integrate Base Paymaster into your Wagmi project, enabling gasless onchain interactions for improved user experience.

👉 Get detailed setup instructions

Frequently Asked Questions

What is a paymaster in blockchain transactions?
A paymaster is a service that sponsors gas fees for users, allowing them to perform onchain actions without needing to hold the native cryptocurrency for transaction costs. This enhances usability and adoption for decentralized applications.

Why whitelist contracts with Base Paymaster?
Whitelisting ensures only approved smart contracts can use the gasless transaction feature. It adds a layer of security and control, preventing unauthorized contracts from exploiting the paymaster service.

Can I use Base Paymaster on testnets?
Yes, Base Paymaster supports both Base mainnet and Base Sepolia testnet. This allows developers to test gasless transactions in a safe environment before deploying to production.

What wallets are compatible with this setup?
The configuration supports popular wallets like Coinbase Wallet, WalletConnect, and injected providers (e.g., MetaMask). Ensure your wallet supports the necessary capabilities for paymaster services.

How do I handle errors during integration?
Common issues include incorrect RPC URLs, misconfigured capabilities, or unwhitelisted contracts. Double-check your environment variables and contract settings, and refer to troubleshooting resources for guidance.

Is a proxy service necessary for production?
While not mandatory, using a proxy service for your paymaster endpoint is recommended in production. It adds security by masking sensitive URLs and improves reliability through load balancing and caching.

Troubleshooting

If you encounter errors during integration, verify your configuration steps and ensure all environment variables are correctly set. For persistent issues, consult the official troubleshooting documentation for additional insights and solutions.