Skip to main content

The Ghost in the Bundler: Exploiting ERC-4337 Smart Wallets

Updated 10 min readMarkdown

Cryptography and smart contract architecture are supposed to make our data and money very secure using math.. Sometimes systems designed to make Web3 easier can actually introduce new and scary ways for people to attack us.

Imagine you are trying Metamask (a standard crypto wallet). You sign up with your email id or you use seed phrases/recovery phrases. Now the most important point if you lose these phrase, it’s not like forgetting your Netflix password—there is no "Forgot Password" button, and no customer support can save you. If it's gone, your crypto is permanently trapped in a digital void. To fix this, a new upgrade called ERC-4337 (Account Abstraction) turns your wallet into a smart, programmable app making it free from seed phrases and gas complexities. But there's a catch behind all this smooth abstraction lies a fragile reality: a complex, off-chain network of intermediaries. When a smart wallet blindly trust the data coming from the middlemen without double-checking the gas math, it isn't building the future of money. It is just handing hackers an open cash register.

The security of Account Abstraction lives and dies in the delicate gap between off-chain simulation and on-chain execution. When validation fails, exploitation thrives. This guide breaks down "The Fee Trap" attack where a simple validation flaw lets an attacker trick a smart wallet into paying massive, fake fees and build a local sandbox to watch the exploit happen in real time.

What’s an EOA?

It stands for “Externally Owned Account”. It is a standard crypto wallet managed by us. If you use MetaMask, Trust Wallet, or a hardware wallet like a Ledger, you are using an EOA. It consists of a public address (your account number) and a private key (your secret password).

REMEMBER : Whoever has the private key has total control over the wallet

What are ERC’s?

It stands for Ethereum Request for Comment. An ERC is just an official rulebook or blueprint for building things on the Ethereum blockchain.

ERC 4337 :

Crypto was too stressful and unforgiving for regular people, where a single mistake meant losing everything. Imagine you own a standard crypto wallet, lost your 12-word seed phrase, and your life savings vanished forever. No backup, no "forgot password" button, nothing. All your funds gone. But with the help of ERC 4337 you can turn your standard wallets into Smart Wallets which runs on code.

fig.1.1.ERC 4337 transaction flow

Deconstructing the Account Abstraction Pipeline

In a traditional setup configuration, we use an Externally Owned Account (EOA) like MetaMask. we sign a transaction , broadcast it to the public mempool, and your wallet pays the gas fee directly to the validators.

With Account Abstraction, your wallet isn't just a private key anymore. It’s a deployed smart contract. Since contracts can't just start transactions out of nowhere on Ethereum, the system uses a totally new pipeline to get your actions onto the blockchain.

1. The UserOperation (UserOp) :

Instead of a standard transaction, your wallet client builds a pseudo-transaction called a UserOperation. It packages what you actually want to do (like a token transfer) along with gas limits, fee settings, and your signature proving it's from you.

2. The Bundler :

You don't send this to the normal Ethereum mempool. Instead, it goes to a special alt-mempool where nodes called Bundlers listen. The Bundler grabs your UserOp, groups it with other users' requests into one big standard transaction, and pays the network gas out of pocket to get it mined.

3. The EntryPoint Contract :

The Bundler drops the package into a master contract on-chain called the EntryPoint. This handles everything: it pings your smart wallet to check your signature, runs the trade, tracks the gas, and grabs tokens from your wallet vault to pay back the Bundler.

Think of the Bundler like a delivery guy who pays your postage upfront. Once the package drops at your door, your smart lock automatically opens your safe and pays him back the exact delivery cost.

The security hole opens up when a hacker figures out how to mess with that receipt.

fig.1.2.How Data Moves in ERC-4337

Where the Leak Begins: The Broken Code

Let’s look at a sketchy but common way people write these validation functions. When the EntryPoint handles a batch of operations, it loops through each one and calls the target wallet to verify it.

  • EntryPoint: The main supervisor on the blockchain. It double-checks every request, enforces the rules, and handles the fee refunds.

  • UserOperation (UserOp): A digital request package. It contains your signature, your transaction limits, and what you want to do.

  • op.callData: The specific action instructions. It tells the network exactly what you want, like sending coins or buying an item.

  • preVerificationGas: It is a set amount inside your request that pays the Bundler back for their extra work done behind the scenes.

  • keccak256: A standard cryptography function. It takes a piece of data (like the callData) and scrambles it into a unique hash( 32-byte string ).

pragma solidity ^0.8.20;
import "./interfaces/UserOperation.sol";

contract LeakySmartWallet {
    address public owner;
    address public immutable entryPoint;

    // Security check: Only the global EntryPoint contract can call this wallet
    modifier onlyEntryPoint() {
        require(msg.sender == entryPoint, "Unauthorized caller");
        _;
    }

    constructor(address _owner, address _entryPoint) {
        owner = _owner;
        entryPoint = _entryPoint;
    }

    // The EntryPoint calls this function to ask: "Did the user actually sign this?"
    function validateUserOp(
        UserOperation calldata op, 
        bytes32 userOpHash, 
        uint256 missingWalletFunds
    ) external onlyEntryPoint returns (uint256 validationData) {
        
        // VULNERABILITY 
        // We are ONLY hashing the 'callData' (the action). 
        // We are completely ignoring the gas parameters sent in the UserOp!
        bytes32 hash = keccak256(abi.encodePacked(op.callData));
        
        // Check if the user's signature matches the hashed action
        if (!_isValidSignature(hash, op.signature)) {
            return 1; // Fails validation
        }

        // If the EntryPoint needs gas money up front, the wallet pays it here
        if (missingWalletFunds > 0) {
            payable(msg.sender).call{value: missingWalletFunds}("");
        }
        
        return 0; // Success! Transaction is allowed to run.
    }

    function _isValidSignature(bytes32 hash, bytes memory sig) internal view returns (bool) {
        // Imaginary ECDSA logic that checks the signature against the 'owner' address
        return true; 
    }
}

At a glance, it looks fine. The wallet acts like a gatekeeper; it takes what you want to do (op.callData), hashes it, and checks if your signature matches the owner's address. If everything is good, it sends the needed gas money to the EntryPoint and returns 0 for success.

The Exploit: How Your Gas Gets Stolen

To see where this breaks, look at what the contract actually hashes:

bytes32 hash = keccak256(abi.encodePacked(op.callData));

fig.1.3.Exploit contract

The wallet only checks op.callData. It completely ignores the rest of the data inside the UserOperation struct.

A standard UserOperation has fields for network execution, like preVerificationGas. This tells the EntryPoint how much extra gas to pay the Bundler for off-chain work. The final payout uses this formula:

Gas Refund = {Actual Execution Gas + preVerificationGas} x maxFeePerGas

Because our LeakySmartWallet doesn't include preVerificationGas in the signature hash, a rogue Bundler can easily pull off a man-in-the-middle attack.

They grab your signed UserOp from the mempool and leave your callData and signature completely alone. But since the signature doesn't actually lock down the gas settings, the Bundler just cranks up the preVerificationGas from a normal 45,000 units to a massive 5,000,000 units.

Once the tampered bundle hits the chain, the EntryPoint calls your wallet to validate it. The wallet hashes the callData, sees your signature matches, and approves it.

Your transaction goes through perfectly, but during the refund step, the EntryPoint reads that inflated gas metric. It drains a huge chunk of crypto from your wallet and sends it straight to the bad Bundler. Your funds are gone, even though your private keys never left your laptop.

Setting Up a Local Sandbox

To test this exploit without spending real money, you can spin up a quick sandbox.

Step 1: Setting Up the Trap

We can write a local test suite that mimics a bad node sniffing the mempool and modifying those unhashed gas parameters.

const crypto = require('crypto');

// --- Fake On-Chain State Management ---
let smartWalletBalance = 10.0; // The Victim's money
let bundlerBalance = 0.0;      // The Hacker's money

// Helper function to simulate Solidity's hashing
function keccak256(data) {
    return "0x" + crypto.createHash('sha256').update(data).digest('hex');
}

// =================================================================
// STEP 1: The user signs their transaction
// =================================================================
const actionIntent = "transfer(0xVictim, 100)"; 
const callDataHash = keccak256(actionIntent); 

// The user ONLY signs the action hash, because that's all the smart contract checks.
const validSignature = "0x" + keccak256(callDataHash + "private_key_seed");

// =================================================================
// STEP 2: The Hacker (Bundler) intercepts and alters the data
// =================================================================
const hijackedUserOp = {
    sender: "0xSmartWalletAddress",
    callData: actionIntent, // The hacker leaves the action alone
    
    // THE ATTACK 
    // The hacker changes the gas tip from normal (50,000) to massive (5,000,000).
    // Because the user didn't sign this specific field, the hacker can change it freely!
    preVerificationGas: 5000000, 
    
    signature: validSignature // The signature is still perfectly valid!
};

// =================================================================
// STEP 3: The EntryPoint executes the flawed math
// =================================================================
function executeEntryPoint(userOp) {
    // 1. Signature check passes because callData wasn't changed
    const reconstructedHash = keccak256(userOp.callData);
    if (reconstructedHash !== callDataHash) return;

    // 2. The EntryPoint calculates the Bundler's refund using the hacked gas number
    const conversionRate = 0.000001; // Gwei to ETH
    const extractedFee = userOp.preVerificationGas * conversionRate;

    // 3. The wallet is drained, and the hacker gets paid!
    smartWalletBalance -= extractedFee;
    bundlerBalance += extractedFee;
}

executeEntryPoint(hijackedUserOp);

Capturing the Exploit

1. Finding Differences in the Code :

fig.1.4.The difference

The Exploit: Signature checks the action data (left) but completely ignores the editable metadata (right).

2. Execution Trace :

fig.1.5.The execution

The check passes anyway: The bad node successfully drains funds using tampered gas parameters.

How to protect?

To patch this, you need to lock down every single field in the transaction payload so outside nodes can't change anything in transit.

Instead of writing your own custom hashing logic inside the smart wallet, your validation code should just use the official userOpHash calculated by the EntryPoint contract. This master hash securely binds every single gas limit, metadata field, and transaction detail into an unchangeable signature:

function validateUserOp(
    UserOperation calldata op, 
    bytes32 userOpHash, 
    uint256 missingWalletFunds
) external onlyEntryPoint returns (uint256 validationData) {
    
    // Comprehensive Cryptographic Binding: Validate the master hash directly
    if (!_isValidSignature(userOpHash, op.signature)) {
        return 1; // SIG_VALIDATION_FAILED
    }

    // Process gas requirements securely
    if (missingWalletFunds > 0) {
        payable(msg.sender).call{value: missingWalletFunds}("");
    }
    
    return 0; // Success
}

fig.1.6. Safe contract

fig.1.7. Code Diff: Replacing the vulnerable hash with the secure one

Once you switch to validating the entire userOpHash, everything is locked down. If a bad Bundler changes even a single gas setting, the signature math breaks on-chain. The EntryPoint will instantly reject the transaction, keeping your funds perfectly safe.

Conclusion: What We Actually Learned

Breaking down this vulnerability leaves us with three major takeaways for Web3 developers:

  • Your signature has to lock down every single parameter, especially gas limits. Leaving any data unsigned is literally handing a blank check to a middleman.

  • Account Abstraction makes crypto easy for users by hiding all the messy stuff. But that complexity just moves to the background, meaning devs have to work twice as hard to secure the invisible plumbing.

  • Normal unit tests won't catch this. The test will say "Passed!" because the transfer technically went through. To spot a middleman attack, you have to actually read the step-by-step execution logs.

11 views

No comments yet. Be the first to comment.