Gas Optimization In Solidity: Strategies For Cost-Effective Smart Contracts
Gas is the “fuel” that powers smart contract execution. This article offers practical strategies for Solidity gas optimization.
🇺🇦 Hacken stands with Ukraine!Learn more
Mass adoption, user onboarding, and friendly UX have always been the priorities for Web3 builders all over the world.
But if you ever try to talk to a “normie” about the complications in Web3, one of the first problems that arise is wallets, seed phrases, and the “signing up” process, not to mention the nuances of the gas and having ETH on your balance to process any transaction.
To fix these problems, Ethereum introduced Account Abstraction, as highlighted in the Ethereum Foundation’s roadmap. The outcome is access to Ethereum via smart contract wallets, either natively supported as part of the existing protocol or via an add-on transaction network.
So, in this article, we provide a definition of account abstraction, review its role in the blockchain, and show how to implement it in your project. Let’s get started!
Account abstraction is an enhancement to the Ethereum protocol that allows for greater flexibility in user interactions. Instead of relying solely on externally owned accounts (EOAs) to initiate transactions or execute smart contracts, account abstraction permits these tasks to be managed by smart contracts or enables smart contracts to begin transactions.
This shift offers improved security, larger functionality, and better UX through features like batching transactions or letting others cover gas payments.
Ultimately, it simplifies user interactions with Ethereum by embedding desired logic directly within smart contract wallets without the need to always route through traditional EOAs.
You needed to have an EOA.
Externally owned accounts (EOAs) are accounts that are controlled by private keys, typically generated using a seed phrase. Unlike smart contracts, externally owned accounts don’t have any code associated with them. Typically, these accounts are managed with a wallet.
|Feature/Aspect||Smart Contract||EOAs (wallets)|
|Security rules||Define your own flexible security rules.||The main security rule: never compromise the keys.|
|Recovery||Recover your account if you lose the keys.||If you lose the keys, the account is lost.|
|Account sharing||Share your account security across trusted devices or individuals.||Sharing is only via the keys – but remember, never share keys with anyone.|
|Gas options||Pay someone else’s gas or have someone else pay yours.||You pay your own gas with the native network coin (e.g., ETH).|
|Tx batching||Batch transactions together for efficiency (e.g. approve and execute a swap in one go)||Click and wait 2 minutes for each separate transaction.|
Account abstraction allows for more opportunities for dApps and wallet developers to innovate on user experiences. Now, in the account abstraction structure, the public-private key pairs are just the “entry points” to interact with a smart contract wallet.
Consider this: backup keys can be added to a wallet so that if you lose or accidentally expose your main key, it can be replaced with a new, secure one with permission from the backup keys. You might secure each of these keys in a different way or split them across trusted guardians. This makes it much harder for a hacker to gain full control over your funds.
Similarly, you can add rules to the wallet to reduce the impact if your main key gets compromised. You could, for instance, allow low-value transactions to be verified by a single signature, whereas higher-value transactions will require approval from multiple authenticated signers – multisig.
The key management is now diverse with all eyes of developers because smart contracts open new ways of wallet management.
Here is a detailed description of how each dimension works.
Current Limitations: EOAs, using the ECDSA for signatures, ensure funds are safe as long as private keys remain with the user. However, EOAs are vulnerable to multiple security threats, such as phishing and malware attacks. Losing the seed phrase/private key of an EOA means irrecoverable loss of assets.
Signature Abstraction Solution: Removes ECDSA signatures as the standard authorization for non-custodial accounts. Users can establish custom authorization rules for their wallets. Enhances user experience, making web3 wallets as intuitive as web2 banking apps.
Potential Use Cases: Transaction limits, multi-party approvals, key management, trusted sessions, automatic payments.
In essence, signature abstraction empowers users with a more flexible and secure transaction environment, bridging the gap between traditional online banking and the decentralized Web3 experience.
Current Limitations: Every Ethereum transaction necessitates a gas fee, paid in Ethereum’s native token, Ether. This can be a barrier for newcomers who need to acquire ETH to transact.
Fee Abstraction Solution: While account abstraction doesn’t remove the gas fee requirement, it does abstract the methods and timing of gas payments. This brings about the concept of “sponsored transactions”, where another account can cover the gas fee.
Potential Use Cases: Non-ETH gas payments, gasless transactions, social logins.
Summing up, fee abstraction paves the way for a more user-friendly Ethereum ecosystem, reducing the friction associated with gas fees and enhancing the overall user experience.
Current Limitations: Every transaction on Ethereum is associated with a “nonce,” which acts like a counter, ensuring transactions are processed in order. This mechanism, while preventing replay attacks, often leads to “stuck transactions” due to the strict first-in-first-out (FIFO) processing order.
Nonce Abstraction Solution: Rather than adhering strictly to the Ethereum protocol’s enforced transaction ordering, nonce abstraction allows custom replay protection mechanisms. This could enable parallel processing of multiple transactions, addressing the issue of delayed or stuck transactions and enhancing dapp interactions.
Potential Use Cases: Transaction Batching
In summary, nonce abstraction, when combined with transaction batching, can streamline the user experience by allowing multiple actions to be bundled into a single transaction, resulting in reduced gas fees and quicker interactions with dapps.
Developers are currently trying to achieve the account abstraction goals through different standards such as EIP-2771, EIP-4337, EIP-2938, EIP-3074, ERC-6551.
EIP-2771 proposes a secure protocol for native meta transactions. Meta transactions enable users to sign a message instead of a transaction, allowing a third party (a “relayer”) to execute the transaction on behalf of the user. The relayer pays for the transaction fees in Ether, making it easier for users to interact with smart contracts without holding Ether.
The EIP suggests introducing a new field in transaction data to indicate that it is a meta transaction and to include additional information like the recipient contract address and function signature. The recipient contract can then process the meta transaction by verifying the signature and executing the specified function, all without the user needing to hold Ether.
EIP-4337 suggests a way to manage transactions on Ethereum without changing the core rules. Instead of changing the basic transaction process, it introduces a higher-level idea called a UserOperation. People create these UserOperation things and put them in a special holding area. Then, a special group called Bundlers takes these UserOperations and makes them into real transactions by using a special contract called EntryPoint.
In this reference implementation, there are four main parts:
UserOperationsact like special transactions that do things through smart contracts.
UserOperationsand give them to EntryPoint to be checked and done.
EntryPointis a smart contract that makes sure things are okay and then carries out the actions.
Contract Accountsare owned by users and can have features from other smart contracts added to them.
A user starts by making a UserOperation and putting it in a separate area. Bundlers then take this UserOperation and give it to EntryPoint to check and do. EntryPoint looks at the UserOperation to make sure it’s allowed and then does the action using a smart contract. Any extra funds not used for fees go back to the user or can be used for extra tasks.
See code example: ERC-4337 account abstraction via alternative mempool (This one is very complex and cannot be shown in simple code blocks).
Transaction validity within the Ethereum protocol is determined in a structured manner: it involves an ECDSA signature, a straightforward nonce, and the account’s available balance. The concept of account abstraction in EIP-2938 introduces an expansion of the conditions that determine the validity of transactions. This expansion involves the execution of arbitrary Ethereum Virtual Machine (EVM) bytecode, subject to certain limitations on state accessibility. To denote transaction validity, a new EVM opcode named PAYGAS is proposed. This opcode serves a dual purpose: it signifies validity while simultaneously defining the gas price and gas limit that the associated contract is willing to compensate.
The concept of account abstraction is divided into two tiers. The first is single-tenant account abstraction (AA), designed to accommodate use cases involving a limited number of participants such as wallets or similar scenarios. The second is multi-tenant account abstraction, tailored for applications involving a multitude of participants. This tier is intended to support applications like tornado.cash and Uniswap, which involve a large number of users and interactions.
This proposal is in a stagnant state and should not be used in its current form directly.
EIP-3074 introduces two new Ethereum Virtual Machine (EVM) instructions, AUTH and AUTHCALL. AUTH sets a context variable based on an ECDSA signature, while AUTHCALL enables calling a function as the authorized account. This empowers smart contracts to temporarily control an EOA.
Traditionally, enhancing EOAs has been sought, leading to requests for features like batching, gas sponsoring, scripting, and more. These features, however, can increase protocol complexity and security risks. EIP-3074 takes an innovative approach, allowing users to delegate their EOA control to a contract, offering flexibility and novel transaction possibilities.
In this proposal, users sign a message indicating their intention. This message is then included in a transaction calling an invoker. The invoker utilizes the signed message with AUTH and AUTHCALL opcodes to gain account control, enabling actions on the user’s behalf. Importantly, the user’s transaction doesn’t necessarily need to originate from their account, freeing them from relying solely on ETH for transaction fees. Alternative fee methods like ERC-20 tokens could be used.
EIP-3074’s invokers provide an immediate upgrade to EOAs. Users aren’t required to migrate assets to new wallets, as with EIP-4337. The opt-in mechanism of EIP-3074 is akin to adding extensions to EOAs, offering users greater transaction flexibility and control.
This EIP is still under review and may get breaking changes in the future.
See code example: EIP3074Relayer
EIP-6551 introduces a system that associates Ethereum accounts with NFTs, enabling NFTs to own assets and engage with applications without altering current smart contracts or EVM infrastructure.
Motivated by the success of the ERC-721 standard in enabling diverse NFT applications, EIP-6551 addresses limitations preventing NFTs from interacting with other on-chain assets. These limitations hinder the representation of complex real-world non-fungible assets as NFTs. The proposal envisions empowering every NFT with rights comparable to Ethereum users, granting self-custody of assets, execution of operations, management of multiple accounts, and cross-chain utilization.
Achieved through a singular registry, EIP-6551 assigns unique, deterministic smart contract addresses to all current and future NFTs. Each account is forever linked to a specific NFT, with account control granted to the corresponding NFT holder. Notably, this pattern doesn’t necessitate modifications to existing NFT smart contracts and aligns seamlessly with Ethereum account support infrastructure.
EIP-6551 facilitates diverse applications for both existing and future NFTs by conferring full Ethereum account capabilities upon each NFT. This advancement offers a versatile framework without altering the current NFT ecosystem, fostering novel use cases and potential enhancements.
See code example: ExampleERC6551Account
This EIP goes out of the concept of account abstraction a bit. It could be considered as a standalone article.
In the future of Ethereum, we may expect Full Account Abstraction: All accounts are simply smart contracts, and users are free to determine how individual accounts are managed and operated. The details of account types are invisible to the Ethereum protocol.
This evolution of account abstraction promises a more intuitive and secure user experience:
As Ethereum continues to evolve, these forward-looking developments in account abstraction will undeniably play a pivotal role in shaping the landscape of decentralized finance and applications.
Account abstraction enables smart contracts to manage or initiate transactions instead of just relying on EOAs.
Account abstraction improves security by allowing smart contracts to set up any security rules, such as intention-based interaction or fingerprint.
Better UX, more functionality, and higher security.
The security of account abstraction mainly depends on the quality of implementation and underlying smart contracts.