EIP-7702 Implementation Guide: Build and Test Smart Accounts

Β·

Overview

EIP-7702 introduces a new transaction type, 0x04, in Ethereum's Pectra upgrade that enables externally owned accounts (EOAs) to execute temporary smart contract functionality. This advancement in Account Abstraction bridges the gap between EOAs and smart contracts, enabling key features like batch transactions, sponsored gas payments, and controlled access delegation.

EIP-7702 is now active on Ethereum mainnet and testnets like Sepolia as part of the Pectra upgrade. Developers can test EIP-7702 in local Foundry environmentsβ€”either on a fresh local network or by forking mainnet. This guide will walk you through setting up a fresh local network for testing purposes.

This comprehensive guide will walk you through the technical details of EIP-7702, its use cases, and how to test it using Foundry and Foundry's cheatcodes. By the end, you'll have a clear understanding of how to leverage EIP-7702 in your projects, deploy implementation contracts, and test EIP-7702 features effectively.

What You Will Learn

Prerequisites

Understanding EIP-7702 Transactions

Traditional Ethereum transactions either transfer funds or interact with smart contracts, but the new 0x04 transaction type allows EOAs to execute code directly. This breakthrough unlocks new possibilities for externally owned accounts, enabling them to function more like smart contracts while maintaining their fundamental characteristics.

With this new standard, EOAs can execute smart contract logic directly from their own address, enabling several advanced functionalities:

Ethereum Account Types Explained

The user (EOA) signs an authorization message that includes the chain ID, nonce, delegation address, and signature components (y_parity, r, s). This generates a signed authorization, ensuring that only the approved implementation contract can execute transactions while protecting against replay attacks.

For each authorized delegation address, the user stores a delegation designator, a pointer to the implementation contract that the EOA will delegate to. When the user (or a sponsor) executes an EIP-7702 transaction, it loads and runs the code from the address indicated by that pointer.

Transaction Construction Mechanics

In standard Ethereum transactions, calling a function on a smart contract requires setting the to field to that contract's address and including the appropriate data to call its function. With EIP-7702, you set the to field to the EOA's address and include the data to call the implementation contract's function with the signed authorization message.

EIP-7702 Transaction Anatomy

The process involves generating an authorization signature for a specific contract, then constructing a transaction where the to field is set to the smart account's own address. The data field is created by encoding a call to the execute function with an array of call objects. The transaction includes the signed authorization in an authorizationList, enabling the smart account to delegate execution to the implementation contract.

If another wallet (a sponsor) wants to execute this transaction (a sponsored transaction), it can use the same authorization signature to delegate execution to the implementation contract.

πŸ‘‰ Explore advanced transaction building techniques

Sending EIP-7702 Transactions with Viem

import { createWalletClient, http, parseEther } from 'viem'
import { anvil } from 'viem/chains'
import { privateKeyToAccount } from 'viem/accounts'
import { eip7702Actions } from 'viem/experimental'
import { abi, contractAddress } from './contract'

const account = privateKeyToAccount('0x...')

const walletClient = createWalletClient({
  account,
  chain: anvil,
  transport: http(),
}).extend(eip7702Actions())

const authorization = await walletClient.signAuthorization({
  contractAddress,
})

const hash = await walletClient.sendTransaction({
  authorizationList: [authorization],
  data: encodeFunctionData({
    abi,
    functionName: 'execute',
    args: [
      [
        {
          data: '0x',
          to: '0xcb98643b8786950F0461f3B0edf99D88F274574D',
          value: parseEther('0.001'),
        },
        {
          data: '0x',
          to: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
          value: parseEther('0.002'),
        },
      ],
    ]
  }),
  to: walletClient.account.address,
})

EIP-7702 Transaction Flow

The transaction flow begins with the EOA signing an authorization message, which is then included in the transaction's authorization list. The network processes this transaction by temporarily elevating the EOA's capabilities through the specified implementation contract, executing the desired operations, and then reverting the EOA back to its normal state after transaction completion.

Testing EIP-7702 Features with Foundry

This section provides practical guidance on implementing EIP-7702 features using Foundry, a powerful smart contract development toolkit. Foundry provides a set of cheatcodesβ€”special commands that modify the behavior of the Ethereum Virtual Machine (EVM) to simplify testing. We'll utilize the signDelegation, attachDelegation, and signAndAttachDelegation cheatcodes to test EIP-7702 features comprehensively.

Project Overview

In this project, we deploy an implementation contract called BatchCallAndSponsor that enables:

The project includes the following files:

Environment Setup

Step 1: Install Foundry

Install Foundry using the following command:

curl -L https://foundry.paradigm.xyz | bash

Restart your terminal and run:

foundryup

Step 2: Initialize Foundry Project

Initialize a new Foundry project:

forge init eip-7702-project
cd eip-7702-project

Alternatively, clone the sample project:

git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/ethereum/eip-7702

Step 3: Install Dependencies

Install required libraries:

forge install foundry-rs/forge-std
forge install OpenZeppelin/openzeppelin-contracts

Step 4: Configure Remappings

Create remappings to simplify import paths:

forge remappings > remappings.txt

Step 5: Update Foundry Configuration

Modify foundry.toml to ensure compatibility with EIP-7702 by setting the Prague hardfork:

evm_version = "prague"

Step 6: Implement Smart Contract

Create BatchCallAndSponsor.sol in the src folder and add the contract logic from the sample project. This implementation contract supports batch transactions and sponsored gas features.

Step 7: Write Test Cases

Create BatchCallAndSponsor.t.sol in the test folder and add test cases from the sample project. These tests cover direct execution, sponsored execution, replay protection, and error handling scenarios.

Step 8: Create Deployment Script

Create BatchCallAndSponsor.s.sol in the script folder and add the deployment script from the sample project. This script handles contract deployment, token minting, and transaction execution.

The complete project structure should look like this:

β”œβ”€β”€ README.md
β”œβ”€β”€ foundry.toml
β”œβ”€β”€ lib
β”‚   β”œβ”€β”€ forge-std
β”‚   └── openzeppelin-contracts
β”œβ”€β”€ remappings.txt
β”œβ”€β”€ script
β”‚   └── BatchCallAndSponsor.s.sol
β”œβ”€β”€ src
β”‚   └── BatchCallAndSponsor.sol
└── test
    └── BatchCallAndSponsor.t.sol

Implementation Contract Details

The BatchCallAndSponsor contract is a straightforward implementation that supports batch transactions and sponsored gas functionality. The contract includes several key components:

Batch Execution Logic

The execute function takes an array of Call structs, each representing a different call with target address, value, and calldata specifications. The function processes these calls sequentially, ensuring atomic execution where either all calls succeed or none execute.

Signature Verification

The contract verifies signatures using OpenZeppelin's ECDSA library and MessageHashUtils, ensuring transactions were signed by the appropriate EOA and preventing unauthorized execution.

Execution Modes

The contract supports both direct execution (where the caller executes calls themselves) and sponsored execution (where a sponsor executes calls on behalf of the caller after verifying their signature).

Replay Protection

A nonce system prevents replay attacks by incrementing after each successful execution, ensuring that signed authorizations cannot be reused maliciously.

Test Cases Overview

The test suite comprehensively validates the contract's functionality through multiple scenarios:

Direct Execution Test

Validates that users can execute batch transactions directly, combining multiple operations like ETH transfers and token transfers into a single atomic transaction.

Sponsored Execution Test

Verifies that third parties can execute transactions on behalf of users, with proper signature verification and authorization mechanisms.

Signature Validation Tests

Ensure the contract correctly rejects invalid signatures and prevents unauthorized access to account functionality.

Replay Protection Test

Confirms that the nonce system effectively prevents transaction replay attacks by rejecting previously used signatures.

Deployment Script Functionality

The deployment script handles contract deployment, token minting, and execution of both direct and sponsored transactions. It provides a practical demonstration of EIP-7702 functionality in action, showing how these features work together in a real-world scenario.

Running and Testing the EIP-7702 Project

Step 1: Start Local Network

Run a local network with the Prague hardfork:

anvil --hardfork prague

Step 2: Install Dependencies

Install project dependencies:

forge install

Step 3: Build Contracts

Compile the smart contracts:

forge build

Step 4: Run Tests

Execute the test suite:

forge test -vvv

Step 5: Execute Deployment Script

Run the deployment script to see EIP-7702 in action:

forge script ./script/BatchCallAndSponsor.s.sol --tc BatchCallAndSponsorScript --broadcast --rpc-url 127.0.0.1:8545

When prompted about transactions to addresses without code (EOAs), type y to continue, as this is expected behavior before EIP-7702 application.

Frequently Asked Questions

What is the main benefit of EIP-7702?

EIP-7702 enables externally owned accounts to temporarily function as smart contracts, allowing batch transactions, gas sponsorship, and delegated execution without requiring users to migrate to smart contract wallets. This significantly improves user experience while maintaining backward compatibility.

How does EIP-7702 improve transaction efficiency?

By enabling batch transactions, EIP-7702 allows multiple operations to be executed atomically in a single transaction, reducing gas costs and blockchain congestion while improving the user experience for complex operations.

Is EIP-7702 compatible with existing Ethereum wallets?

Yes, EIP-7702 maintains full backward compatibility with existing wallets and smart contracts. The new transaction type is optional, and traditional transactions continue to work exactly as before.

How does EIP-7702 handle security concerns?

The implementation includes signature verification, nonce-based replay protection, and strict authorization checks to ensure only approved implementation contracts can execute transactions on behalf of EOAs.

Can EIP-7702 transactions be sponsored by third parties?

Yes, one of the key features enables gas sponsorship, where third parties can pay transaction fees on behalf of users, opening up new business models and improving user onboarding experiences.

What are the limitations of EIP-7702?

The functionality is temporary and transaction-specific. EOAs only gain smart contract capabilities during the execution of an EIP-7702 transaction and revert to normal functionality afterward, which maintains security while enabling advanced features.

Conclusion

EIP-7702 represents a significant advancement in Ethereum's account abstraction capabilities, opening the door to innovative use cases like batch transactions, delegated execution, and sponsored transactions. This novel feature has the potential to transform how users interact with smart contracts and decentralized applications.

This guide has covered the fundamentals of EIP-7702, its practical applications, and implementation techniques using Foundry. Through hands-on testing with implementation contracts on a local network, you've gained practical experience with this emerging standard. The knowledge gained provides a solid foundation for exploring more advanced EIP-7702 applications and contributing to the evolving ecosystem of account abstraction solutions on Ethereum.

πŸ‘‰ Discover more smart account strategies