Back to writing

Blog post

Exploring Account Abstraction and ERC-4337: An In-Depth Analysis

Explore Account Abstraction and ERC-4337, how smart wallets improve Ethereum UX through sponsored gas, batch transactions, Web3Auth, and onboarding...

DateNovember 9, 2023
Read7 min read
EthereumERC-4337Account AbstractionSmart ContractsWeb3AuthBlockchainWeb3

Exploring Account Abstraction and ERC-4337: An In-Depth Analysis

#Introduction

In the ever-evolving world of blockchain technology, Ethereum has emerged as a leading platform that facilitates the creation and execution of smart contracts. These self-executing, digitally encrypted contracts enable trusted and transparent transactions without intermediaries. However, as Ethereum adoption grows, so do the challenges associated with usability, accessibility, and efficiency of smart contracts, directly impacting the user experience (UX).

One of the significant developments in this area is Account Abstraction. This concept focuses on providing a layer of flexibility and functionality that was previously limited or absent. Account Abstraction allows developers and users to interact with the Ethereum blockchain more efficiently and effectively, opening up new possibilities in the design and implementation of smart contracts.

Within this abstraction framework, the ERC-4337 or "User Operation" standard has been proposed, which seeks to further simplify user interaction with the blockchain, allowing, for example, gas fees to be paid by third parties and facilitating the execution of batch transactions.

This whitepaper seeks to explore Account Abstraction and the ERC-4337 standard in depth, providing a clear understanding of these concepts, their implementation at the code level, and their implications for the design and operation of smart contracts in Ethereum. In addition, practical examples and comparatives will be presented to illustrate the tangible benefits of applying these concepts in smart contract development. Real projects such as Web3Auth that have implemented these concepts to improve user interaction with smart contracts will also be discussed.

#Historical Background

Prior to the introduction of Account Abstraction, interacting with the Ethereum blockchain presented certain barriers for users and developers, such as the need to own Ether (ETH) to pay gas fees.

To address these challenges, the Ethereum community proposed several EIPs (Ethereum Improvement Proposals) and ERCs (Ethereum Request for Comments). Some of these proposals include EIP-86, which proposed a new transaction structure to enable account abstraction, and EIP-3074, which proposed a sponsored transaction authorization to improve flexibility in transaction management.

Account Abstraction emerged as a key concept to decouple the logic of smart contracts from the intricate mechanics of account management in the blockchain.

The ERC-4337 standard, known as "User Operation," is one of the notable developments in this context. Proposed to further improve user interaction with the blockchain, this standard is a testament to the community's ongoing effort to simplify the user experience and reduce barriers to entry into the Ethereum ecosystem.

These groundbreaking developments have set the stage for a new wave of innovations in the smart contract space, enabling greater accessibility and richer interaction between users, developers, and the Ethereum blockchain.

#Account Abstraction Explained

Account Abstraction in Ethereum represents a significant enhancement that offers greater flexibility in how users and contracts interact with the blockchain. Traditionally, accounts in Ethereum are categorized into two types: externally owned accounts (EOAs) and contracts. EOAs are controlled by private keys and can send transactions to the blockchain, while contracts, on the other hand, rely on EOAs to be activated and execute their code.

In the traditional model, EOAs need to have Ether to pay gas fees for transactions that trigger contracts. This can be a barrier for users who are unfamiliar with the blockchain or who do not wish to acquire Ether.

Account Abstraction seeks to mitigate these barriers by decoupling account management logic from smart contracts. This is achieved by allowing smart contracts to handle their own authentication and gas payment logic. In this way, it is possible to create contracts that can pay their own gas tariffs, or allow third parties to pay tariffs on behalf of users.

This decoupling allows for greater flexibility in smart contract design and can significantly improve the user experience. For example, contracts can be designed to provide a friendlier user interface, or to interact with other contracts more efficiently.

Account Abstraction opens up a range of possibilities in the design and operation of smart contracts on Ethereum, facilitating the creation of more accessible and user-friendly solutions on the blockchain.

#Explanation of the ERC-4337 Standard

The ERC-4337 standard, also known as User Operation, is a proposal that seeks to simplify user interaction with the Ethereum blockchain. This standard focuses on enabling smart contracts to handle transactions on behalf of users, making it easier for others to pay gas fees and allowing for batch transaction execution.

The main innovation of ERC-4337 is the introduction of a new transaction structure, called a "user transaction," which is sent to a relay contract rather than directly to the blockchain. This relay contract is responsible for sending the user transaction to the blockchain, allowing gas tariffs to be paid by the contract or by third parties. This eliminates the need for users to handle Ether to interact with smart contracts, improving accessibility and user experience.

In addition, ERC-4337 enables batch transaction execution, meaning users can submit multiple trades as a single batch, optimizing efficiency and reducing gas costs.

This standard aligns with Account Abstraction by enabling greater flexibility in transaction management and authentication, facilitating the design and operation of more advanced, user-friendly smart contracts.

ERC-4337 represents an important step towards simplifying user interaction with the blockchain, and its implementation can have a significant impact on the adoption and usability of smart contracts on Ethereum.

#Traditional Ethereum Accounts vs Account Abstraction

FeatureTraditional Ethereum AccountsAccount Abstraction / ERC-4337
Account typeExternally Owned Accounts (EOAs) and smart contracts are separateSmart contract accounts can behave more like user accounts
AuthenticationBased mainly on private keysCan support custom validation logic
Gas paymentUsers usually need ETH to pay gasGas can be sponsored or handled through paymasters
Transaction flowUser signs and sends a transaction directlyUser creates a UserOperation handled by bundlers and the EntryPoint
UX complexityUsers need to understand wallets, gas, and private keysApps can abstract wallet complexity and improve onboarding
Batch transactionsUsually require multiple separate transactionsMultiple actions can be bundled into one flow
Recovery optionsLimited if the private key or seed phrase is lostCan support social recovery or custom recovery logic

#Basic ERC-4337 Flow

User
  |
  | Creates a UserOperation
  v
UserOperation Mempool
  |
  | Bundler picks one or more UserOperations
  v
Bundler
  |
  | Sends bundled transaction
  v
EntryPoint Contract
  |
  | Validates and executes the operation
  v
Smart Account / Target Contract

#Use Cases

Account Abstraction and the ERC-4337 standard can be employed in different scenarios where usability, accessibility, and transaction efficiency are key. Some relevant use cases include:

  • Decentralized applications (dApps): Improve onboarding by reducing the need for users to understand gas management, wallet complexity, or blockchain authentication flows.
  • Multi-signature contracts: Support more complex authorization flows while allowing third parties or the contract itself to sponsor gas fees.
  • Decentralized marketplaces: Make transaction management more intuitive, helping platforms reach users who may not be familiar with Web3 tools.
  • Digital identity and access management: Enable more flexible authentication models and secure identity systems on-chain.
  • Web3Auth integrations: Simplify passwordless authentication in dApps and help bridge familiar Web2 login experiences with Web3 interactions.
  • Escrow contracts and financial agreements: Reduce friction by allowing sponsored gas fees and batch execution for multiple related transactions.
  • Blockchain games: Abstract wallet and gas complexity so players can focus on the game experience instead of transaction mechanics.

#Example with a Voting Smart Contract Implementing Web3Auth

#Prerequisites

  • Familiarity with Solidity and the Ethereum development environment.
  • A configured development environment, such as Remix or Truffle.
  • Access to Web3Auth documentation and resources.

#Configuring Web3Auth

Configure Web3Auth in your application according to the instructions provided in the Web3Auth documentation.

import { Web3Auth } from "@web3auth/modal";
 
const web3auth = new Web3Auth({
  clientId: "YOUR_WEB3AUTH_CLIENT_ID",
  chainConfig: {
    chainNamespace: "eip155",
    chainId: "0x5",
    rpcTarget: "https://rpc.ankr.com/eth_goerli",
  },
});
 
await web3auth.initModal();
 
const provider = await web3auth.connect();

#Developing the Voting Contract

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
 
contract Voting {
    mapping(address => bool) public hasVoted;
    mapping(string => uint256) public votes;
 
    string[] public candidates;
 
    constructor(string[] memory _candidates) {
        candidates = _candidates;
    }
 
    function vote(string memory _candidate) public {
        require(!hasVoted[msg.sender], "You have already voted");
 
        bool validCandidate = false;
 
        for (uint256 i = 0; i < candidates.length; i++) {
            if (
                keccak256(abi.encodePacked(candidates[i])) ==
                keccak256(abi.encodePacked(_candidate))
            ) {
                validCandidate = true;
                break;
            }
        }
 
        require(validCandidate, "Invalid candidate");
 
        votes[_candidate] += 1;
        hasVoted[msg.sender] = true;
    }
 
    function getVotes(string memory _candidate) public view returns (uint256) {
        return votes[_candidate];
    }
 
    function getCandidates() public view returns (string[] memory) {
        return candidates;
    }
}

#Interaction Between Web3Auth and the Voting Contract

Once a user has authenticated through Web3Auth, your application must allow the user to interact with the voting contract.

import { ethers } from "ethers";
import VotingArtifact from "./artifacts/contracts/Voting.sol/Voting.json";
 
const contractAddress = "YOUR_DEPLOYED_CONTRACT_ADDRESS";
 
async function vote(candidate) {
  const ethersProvider = new ethers.providers.Web3Provider(provider);
  const signer = ethersProvider.getSigner();
 
  const votingContract = new ethers.Contract(
    contractAddress,
    VotingArtifact.abi,
    signer
  );
 
  const tx = await votingContract.vote(candidate);
  await tx.wait();
 
  console.log(`Vote submitted for ${candidate}`);
}
 
async function getVotes(candidate) {
  const ethersProvider = new ethers.providers.Web3Provider(provider);
 
  const votingContract = new ethers.Contract(
    contractAddress,
    VotingArtifact.abi,
    ethersProvider
  );
 
  const votes = await votingContract.getVotes(candidate);
  return votes.toString();
}

#Deployment

Deploy your voting contract to the Ethereum network of your choice.

Make sure your application is configured to interact correctly with Web3Auth and your voting contract.

const hre = require("hardhat");
 
async function main() {
  const candidates = ["Alice", "Bob", "Charlie"];
 
  const Voting = await hre.ethers.getContractFactory("Voting");
  const voting = await Voting.deploy(candidates);
 
  await voting.deployed();
 
  console.log(`Voting contract deployed to: ${voting.address}`);
}
 
main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

#Testing and Verification

Perform extensive testing to ensure that authentication through Web3Auth and interaction with the voting contract work as expected.

const { expect } = require("chai");
 
describe("Voting", function () {
  it("allows a user to vote once", async function () {
    const Voting = await ethers.getContractFactory("Voting");
    const voting = await Voting.deploy(["Alice", "Bob"]);
 
    await voting.vote("Alice");
 
    expect(await voting.getVotes("Alice")).to.equal(1);
  });
 
  it("prevents double voting", async function () {
    const Voting = await ethers.getContractFactory("Voting");
    const voting = await Voting.deploy(["Alice", "Bob"]);
 
    await voting.vote("Alice");
 
    await expect(voting.vote("Bob")).to.be.revertedWith(
      "You have already voted"
    );
  });
});

#Optimization and Security

Review and optimize your code to ensure that it is secure and free of bugs or vulnerabilities.

In this flow, Web3Auth handles user authentication, while the smart contract handles the voting process. The application you are developing acts as an intermediary, facilitating the interaction between Web3Auth and the smart contract.

#Closing

In conclusion, Account Abstraction and the ERC-4337 standard represent significant advances in the evolution of smart contracts on Ethereum. They offer substantial improvement in user experience and operational efficiency. Tools such as Web3Auth not only facilitate secure password-less authentication, but also act as essential bridges to draw users from the traditional web (Web2) to the decentralized web (Web3). By simplifying interaction with decentralized services, these innovations play a crucial role in promoting wider adoption of blockchain technology, bringing the promises of Web3 one step closer to reality.

© Lucas Malizia

Made with love

Built while drinking mate and overthinking