Ensure the security of your smart contracts

Account Abstraction. Auditor’s View

Author: Dmitri Zakharov
СTO at MixBytes
Introduction
EIP-4337 proposes an innovative approach to Account Abstraction in Ethereum that doesn't require changes to the consensus layer. The architecture of EIP-4337 replicates the functionality of a transaction mempool in a high-level system, allowing for a more flexible and dynamic processing model. The main participants in this system are users and Bundlers, who operate through a specialized peer-to-peer network of clients with an implemented UserOperationPool.

In this setup, users submit UserOperation objects to the UserOperationPool. Bundlers, acting as transaction builders, monitor the mempool and combine UserOperation objects into a single bundle transaction, which is then sent to the EntryPoint smart contract. This EntryPoint contract acts as a central processing hub, executing the UserOperation objects and deploying custom Account smart contracts implementing a specified interface.

The deployed Account smart contracts go beyond asset storage; they handle nonces and signature validation, offering opportunities for custom logic in the operations process and asset utilization. To enhance the versatility of EIP-4337 further, the protocol introduces Paymaster actors, which handle gas payments during the execution of inner transactions. This addition allows for customizable gas payment methods based on various conditions, such as accepting ERC-20 tokens as payment to the Paymaster.

The detailed architecture and logic of EIP-4337 can be found in the proposal authored by Vitalik Buterin et al.
Understanding the Mechanics of Account Abstraction
  • Users should create a UserOperation pseudo-transaction object and sign it. UserOperation is described as follows:

struct UserOperation {
    address sender,
    uint256 nonce,
    bytes initCode,
    bytes callData,
    uint256 callGasLimit,
    uint256 verificationGasLimit,
    uint256 preVerificationGas,
    uint256 maxFeePerGas,
    uint256 maxPriorityFeePerGas,
    bytes paymasterAndData,
    bytes signature
    }
The UserOperation structure consists of several fields that define the parameters and instructions for executing a transaction. Let's explore each field and its significance:
sender
This field indicates the address of the smart contract wallet initiating the transaction;

nonce
The nonce acts as a security measure against replay attacks. It serves as a salt during the creation of a user account to ensure uniqueness;

initCode
In case of a first-time transaction, the initCode is used to deploy the smart contract wallet. A Factory contract, introduced by smart contract developers, utilizes this code;

callData
The callData field contains the data to be executed by the smart contract wallet;

callGasLimit
This field sets the gas limit for the execution process within the smart contract wallet;

verificationGasLimit
The verificationGasLimit specifies the gas limit for the UserOperation verification process, performed by an EntryPoint contract;

preVerificationGas
This fee compensates the bundler for their services;

maxFeePerGas and maxPriorityFeePerGas
These values follow the EIP-1559 standard and define the maximum gas price for the transaction;

paymasterAndData
This field contains the Paymaster contract address and specific data required for verification and validation on the Paymaster side;

signature

Together with the nonce, the signature ensures the legitimacy of the UserOperation. It verifies that it was created by an authorized user.
  • UserOpeartion is sent to a specific mempool which is used only for the such type of objects (using a eth_sendUserOp call). Bundlers watch that mempool, verify UserOperations objects using public functions of EntryPoint contract, then pack UserOperations into a transaction (it is a call to the EntryPoint contract with a UserOperation[] array) to be included in a block (which can be proposed by a bundler if they act as a block builder).
  • If initCode is set in a UserOperation object, then EntryPoint contract calls a Factory contract with that initCode and the created Account contract wallet address is returned. Factory uses CREATE2 opcode to create a user wallet. nonce is used as a salt (which is equal to 0 in most cases as it is a first tx with a UserOperation). CREATE2 is used to produce the same address for wallets on different networks as the EntryPoint is persistent across other networks.
  • Then, UserOperation is checked within an Account contract, which confirms that the call originates from EntryPoint, checks nonce provided in UserOperation, validates the provided signature and calls a Paymaster to prefund a tx (if requested). eth-infinitism implementation uses OpenZeppelin ECDSA recover function to get signer address out of UserOperation structure hash

bytes32 hash = userOpHash.toEthSignedMessageHash();
if (owner != hash.recover(userOp.signature))
    return SIG_VALIDATION_FAILED;
where owner is the users’ address.

In cases where BLS account signatures are implemented, the user's smart contract wallet must include a getBlsPublicKey() function. UserOperation structure is converted into a verifiable message. Then retrieved public key, message and signature are passed to the signature verification function.
  • Paymaster allows users to “outsource” gas payment by providing an ERC-20 token allowance instead of paying with the native network currency. The Paymaster calculates the transaction price in the provided tokens, determines if a refund is necessary, and checks if the given allowance is sufficient. Notably, eth-infinitism updates the token price towards the end of UserOperation execution. If token price decreased since the previous fetch, a negative refund is applied.The OracleHelper contract in the eth-infinitism implementation includes a priceUpdateThreshold to determine when a price update is needed.
  • After passing all checks, including logic checks and gas expenditure verification, the callData provided is executed through a call from the EntryPoint to the user's Account contract wallet. The Account contract then performs another call to the desired destination with the specified calldata.
Possible Ways of Integration
Integration of paymasters
In ERC-4337, the integrated paymaster is a crucial component for DeFi projects as it handles the gas costs involved. It offers different methods to cover these costs, such as using ERC-20 tokens or sponsoring the gas prices directly, which enhances the attractiveness of the protocol.

When integrating a paymaster, it is important for all protocols to consider the risk of Denial-of-Service (DOS) attacks. If someone discovers a way to sponsor their transactions without providing fair compensation, they can deplete the paymaster's stake. To illustrate, let's consider a scenario where a new ERC-20 token compensates for the gas cost of any transfer. An attacker could exploit this by repeatedly transferring tokens back and forth, quickly draining the paymaster's funds.

Paymasters have utility in decentralized exchanges (DEXes) like Uniswap, enabling the exchange of ERC-20 tokens without requiring native tokens. For example, when exchanging token A for token B, the amount of token A allocated for the trade can be reduced to account for the equivalent gas cost. Additionally, ERC-20 tokens can be exchanged for wrapped native tokens, which are then immediately unwrapped and sent to the user's account.

In this use case, it is crucial to consider slippage. The calculation of the minimum amount of token B should take into account gas price compensation. Incorrect adjustments to the slippage mechanism can result in constant transaction failures or potential exploitation by MEV-bots seeking to steal a user's funds.

Furthermore, NFT markets like OpenSea can leverage paymasters to enable artists to mint NFTs without requiring native tokens. Artists or institutions can make payments through traditional means, such as bank cards on the marketplace. Subsequently, the protocol whitelists these users in the paymaster, allowing them to deploy their collections without needing in-depth knowledge of cryptocurrency, simply by utilizing a user-friendly interface. Moreover, markets can even sponsor gas payments to support cultural institutions or attract renowned artists, further enhancing the ecosystem.
Regular operations
ERC-4337 introduces additional functionalities like recurrent operations and subscriptions, which can bring new features to DeFi projects. However, implementing these capabilities requires support from an abstract account realization where wallet contracts can validate such UserOperations.

One application of recurrent operations is in lending platforms like Aave and Compound. Users can set up regular transfers of funds to the protocol, allowing their tokens to be continuously lent out. This generates profits and improves the health factor of users' debt. Additionally, users can auto-approve a specific amount of funds if the health factor falls below a certain threshold.

Another use case is the ability to set orders on decentralized exchanges (DEXes) or other trading platforms without initially transferring funds from the user's balance. Users can establish conditions for approval of an ERC-20 token. The trading protocol will execute the order only if these conditions are met and the user has sufficient balance.

When implementing recurrent or triggered approvals, it is crucial to pay close attention to various details such as the approved amount, authorized transferrs, and the periodicity of auto-approvals. Both the protocol owner and the user share the responsibility of ensuring these settings are carefully defined and managed.
Limitations
Despite its revolutionary approach to Ethereum account management, EIP-4337 still encounters several inherent limitations. These constraints stem from various factors such as potential griefing and DoS attacks, the necessity for an isolated validation process of UserOperations and the decentralized nature of the overall system:
  • Gas Constraints in the Validation Process: The design of EIP-4337 imposes limitations on the validation process. To safeguard against excessive gas consumption and potential griefing, high-cost validation algorithms cannot be implemented into Account smart contracts. Bundlers are allowed to exclude UserOperation objects from a bundle if the gas limit parameter for the validation process is set too high.
  • Independence of the Validation Process: The validation process for Accounts and Paymasters grouped into a single bundle must remain independent, implying that they cannot call Accounts associated with other UserOperations or access the same storage slots. This restriction ensures that the consistency of validation does not depend on the order of UserOperation objects within the bundle transaction. Consequently, the usage of BeaconProxy is limited, and Accounts linked to the same Beacon cannot be included in one bundle.
  • Restrictions on Storage Access: Accounts and Paymasters can only read the storage slots associated with their address. To reduce the possibility of DoS and griefing attacks, a staking mechanism has been introduced. If the Paymaster validation process accesses storage associated with other addresses, it must stake a specified amount of assets. This stake can be unstaked at any time after a fixed delay.
  • Whitelisting of the Paymasters: The client implements a Throttle and Ban mechanism to determine Paymasters whose validation processes fail after being included into the bundle. In simpler terms, this targets Paymasters with inconsistent validation functions. If a Paymaster repeatedly fails after being included in the bundle (more frequently than a predefined parameter of client or Bundler), the Bundler may decrease priority of operation or even ban operations that employ this Paymaster for a period of time.
  • Delay between UserOperationPool and Chain Mempool: The UserOperation object is included into UserOperationPool before it’s added within the bundle transaction to the chain mempool. It means that between sending the operation to the mempool and including the related bundle transaction in the block the significant amount of time can pass. To mitigate late operation processing, Account validation function returns a validUntil parameter, enabling Bundlers to avoid using outdated UserOperation objects.
  • Opcode Restrictions: EIP-4337 requires the validation processes to be independent of block and transaction states to maintain consistency between validation simulation and execution of the bundle transaction. This restriction mandates Bundlers to ensure that validateUserOp method of Accounts and validatePaymasterUserOp of Paymasters don’t use specific opcodes (GASPRICE, GASLIMIT, DIFFICULTY, TIMESTAMP, BASEFEE, BLOCKHASH, NUMBER, SELFBALANCE, BALANCE, ORIGIN, GAS, CREATE, CREATE2, COINBASE, SELFDESTRUCT). Exceptions are made for GAS if followed by one of the call opcodes.
  • Deployment Costs: Every Account smart contract must be deployed before utilization. If extrapolated to millions of Accounts, the deployment costs could be significant. However, these costs can be mitigated through EIP-1167 (minimal proxy contract), which facilitates cheaper contract creation costs.
  • Replication Attack Defense: To defend from replication attacks, EIP-4337 requires that UserOperation validation depend on chainId, nonce, and msg.sender (which is the EntryPoint smart contract).
Security Risks
The implementation of EIP-4337 brings several risks to the forefront. These risks relate to the potential vulnerabilities in custom signature verification methods in Account smart contracts, the potential of griefing, constraints on integration with certain projects, and the crucial need for comprehensive auditing:
  • Custom Signature Verification Risks: The ability for Account smart contracts under EIP-4337 to employ custom signature verification can potentially introduce security vulnerabilities. These custom verification methods may be less secure than the standard ECDSA algorithm on the secp256k1 curve used for transaction signatures in Ethereum, leading to increased vulnerability risks.
  • Griefing: Despite precautions, the potential griefing persists in EIP-4337. For instance, a malicious actor could front-run the bundle transaction, changing the state of multiple Accounts and causing the validation process to fail after consuming a significant amount of gas.
  • Project Integration Constraints: The structure of EIP-4337, where each Account is a smart contract, imposes integration constraints with projects using the isContract() modifier. This restriction essentially prohibits anything other than EOA message senders from using these projects.
  • Necessity for Auditing: Given potential security vulnerabilities in the Account and the Paymaster it’s imperative that they are rigorously audited to ensure the overall system’s security.
  • Bundler’s Extracted Value: Bundlers can replay the operations of users included in the UserOperationPool, potentially front-running arbitrage opportunities. This risk can be mitigated by implementing the client as a trusted third party, much like the FlashBots project does, thereby guaranteeing the security of operations for both users and Bundlers or direct block producers.
Conclusion
ERC-4337 presents an innovative solution for managing transactions on the Ethereum network, allowing for more flexibility in handling assets and gas payments. This protocol has the potential to enhance existing DeFi protocols, making them more convenient and adaptable. However, it is crucial to approach its implementation with careful consideration of the associated limitations and risks. Striking a thoughtful balance between leveraging the advantages of ERC-4337 and implementing robust security measures will be key in establishing it as a significant milestone within the Ethereum ecosystem.
Who is MixBytes?
MixBytes is a team of expert blockchain auditors and security researchers specializing in providing comprehensive smart contract audits and technical advisory services for EVM-compatible and Substrate-based projects. Join us on Twitter to stay up-to-date with the latest industry trends and insights.
Disclaimer
The information contained in this Website is for educational and informational purposes only and shall not be understood or construed as financial or investment advice.
Other posts