Next Article in Journal
A 87 dB SNR and THD+N 0.03% HiFi Grade Audio Preamplifier
Next Article in Special Issue
Blockchain Innovations, Applications, and Future Prospects
Previous Article in Journal
Automated Hyperparameter Tuning in Reinforcement Learning for Quadrupedal Robot Locomotion
Previous Article in Special Issue
Blockchain-Based E-Voting Systems: A Technology Review
 
 
Font Type:
Arial Georgia Verdana
Font Size:
Aa Aa Aa
Line Spacing:
Column Width:
Background:
Article

Exemplary Ethereum Development Strategies Regarding Security and Gas-Saving

Department for Smart and Interconnected Living, University of Applied Sciences Upper Austria, Softwarepark 11, 4232 Hagenberg, Austria
*
Author to whom correspondence should be addressed.
Electronics 2024, 13(1), 117; https://doi.org/10.3390/electronics13010117
Submission received: 29 November 2023 / Revised: 18 December 2023 / Accepted: 25 December 2023 / Published: 27 December 2023
(This article belongs to the Special Issue Advancement in Blockchain Technology and Applications)

Abstract

:
Ethereum is a rapidly evolving blockchain with new features as well as new vulnerabilities being introduced regularly. Interaction with the network is costly compared to other blockchains or traditional software systems. When starting to develop on Ethereum, a supported smart contract programming language needs to be learned, most notably Solidity. Having various pitfalls raises the question of what the best practices for the safe and efficient usage of Ethereum are. This study primarily aims to combine knowledge from existing research resources, while also introducing new approaches learned from practical smart contract development analysis and inquiry, which are subsequently compiled into lists of best practices. The most important findings are that code quality and security should be prioritized. Moreover, some simple gas-saving strategies can help to decrease interaction costs with little effort.

1. Introduction

The problem with Ethereum’s smart contract security issues stems from multiple sources. As summarized by Luu et al. [1], smart contracts operate in a permissionless network where anyone can join and they can hold large monetary value. On top of this, the code is publicly available and fixing errors is difficult due to the immutability of the network. Secondly, Ethereum is the largest Turing-complete blockchain by market capitalization. Interacting with the network is costly because of a maximum throughput limit and the high price of Ether. Ethereum commonly gets congested and experiences high gas prices [2]. The importance of best practices is also heightened, due to multiple reasons. The execution environment is more unfamiliar to developers. The code is run by a global network of anonymous nodes. The Ethereum stack is under constant, fast-paced development. New security issues are therefore found regularly [3,4,5]. Lastly, the saying “move fast and break things” that is sometimes used in software development is not applicable due to the immutability of Ethereum and its limited patching functionality [6].
From ten blockchain-specific vulnerabilities that were found by Chen et al. [7], nine can be avoided by applying best practices. They also note a mismatch between high attack efforts and trailing defence efforts. In interviews conducted by Zou et al. [8], 70% of interviewees answered that guaranteeing the security of smart contracts is hard. One reason that was mentioned is the lack of missing best practices. This study seeks to combine best practice knowledge by leveraging previous research, the knowledge of the Ethereum community and own findings. The aim is to create a best practice list that is easy to follow and that contains the most important information.

1.1. Research Questions

To improve the current situation, a set of research questions was formulated. These tackle parts of Ethereum development where an improvement could have a positive impact. The following are the research questions that this study tries to answer, which are answered in Section 6.
  • RQ1: What are general best practices that should be followed for developing on Ethereum?
  • RQ2: What best practices help to defend against major attack vectors used to hack smart contracts?
  • RQ3: Which coding techniques help save gas? Are there negative side effects when using those techniques?

1.2. Summary

The results of this study are a best practice list for the sections of general philosophy, security and gas saving. Each section contains the most important parts, and the entries for each topic range from four to ten recommendations. An important finding was the priority of security over other best practices. Without a security focus, a smart contract is vulnerable to many attacks inexperienced developers are not aware of. The gas savings were separated into two lists, as not all are always preferable and depend on the context. If the list can improve the knowledge of other Ethereum developers and how they interact with the network will be seen in the future. A limitation is that it is hard to define the list as complete, as new features are continuously introduced and new security issues are discovered. The best practices could be further extended to contain best practices for other programming languages of Ethereum and focus on other parts of the blockchain, like decentralized finance (DeFi) or gaming. Another extension could be to include other blockchains and compare the best practices to the ones explained here.

1.3. Paper Outline

Section 2 gives some information on the background of Ethereum. In Section 3 the related work is introduced. Publications from different areas of best practices are shown and their differences and contributions to this study are explained. Section 4 focuses on the methodology used for finding further best practices through hands-on experience. Afterwards, the best practices from the research and the methodology have been combined into the best practice list. This list is depicted in Section 5 and its points are elaborated on. Lastly, the research questions are revisited in Section 6 and implications, limitations and future work are presented in Section 7.

2. Background

The background section is a collection of some important Ethereum information related to the findings of the paper.

2.1. Gas Fee

Since the Ethereum Virtual Machine is Turing-complete, code can be executed that includes nondeterministic code. Infinite loops could be utilized by malicious users or unintentionally occur due to a programming error. The whole network could collapse, as the computation would not come to a stop. The problem is known as the halting problem [9], which says it is not possible to predict if a given piece of code will terminate or not. To tackle this problem, a fee for using the network is introduced [10].
The following list contains the most important fee-related terms [11]:
  • Gas: this fee is a unit of measurement for computational resource consumption and is referred to as gas.
  • Gas limit: the user sets a maximum amount of steps that the code is allowed to run with the gas limit. If the code does not terminate before all gas is used, the transaction is reverted, but the fee still has to be paid.
  • Gas price: this is the price per unit of gas used during a transaction. Most commonly, Gwei is used to price gas.
  • Base fee and priority fee: the fee that is required to be paid to be able to be included in a block. The current base fee is calculated by the previous block and it can only grow a maximum of 12.5% per block. The base fee set for the block is getting burned and only the priority fee is being paid to the validators. The higher the tip, the more likely a transaction is included before other transactions.
Per block, there is a maximum throughput that the network can handle. If many participants want to interact at the same time, the network gets congested and the base fee is increased. The users outbid each other to get included in the network [11].

2.2. Solidity Optimizer

There are different types of optimizer programs that reduce the size of the code and make it more efficient. Optimizer tools are trying to find optimizations on Solidity code, bytecode or an intermediate language like Yul [12,13,14,15,16]. The tools then try to optimize the respective code representations and create a smaller code for deployment. Solidity has its own optimizer included in the Solidity compiler. There are two optimizer modules titled “old” optimizer and “new” optimizer. The “old” optimizer is opcode-based and has simplification rules to change opcodes. Moreover, dead code is removed, and equal code sets are merged. The “new” optimizer is Yul-based which allows it to optimize across functions, according to the Solidity documentation. The optimizations improve the cost of calling a function and deploying the contract to the blockchain [16].

2.3. Blockchain Security

Security on Ethereum is crucial for the safe usage of the network. Security is required in multiple parts of interacting with the network. It requires users and developers to be security aware. Problematic are the two attributes permissionless and immutability, according to Chen et al. [7]. Those features allow malicious users to attack at will, and no one can normally change the immutability of the blockchain. The DAO hack [17] was an extraordinary circumstance where the Ethereum Foundation overrode a smart contract, which led to a fork in Ethereum [18]. More on overcoming immutability can be seen in Section 2.4 and the trade-offs involved are reviewed in Section 5.2.2.
Alchemy has created a simulator API that can simulate the changes that would happen when authorizing a transaction. This makes it easier for users to see changes without having to look at the code. Not only users have to be careful, but also developers—they need to secure their code against attacks [19] and bugs. A more thorough survey regarding smart contract vulnerabilities, exploits and countermeasures has been proposed by Kjiam et al. [20]. The steps recommended for developers to improve the safety of Ethereum are covered Section 5.

2.4. Immutability and Proxy Contracts

Smart contract code that has been deployed on Ethereum is immutable. This makes bug fixes on deployed code impossible. This is a negative for security because fixing bugs is seen as a standard development practice. However, one can get around the immutability by deploying multiple smart contracts containing the code and having a proxy contract that links to the implementations of the contracts. The addresses linking to the other contracts are stored in the modifiable storage of the proxy contract [10,11].
Amri et al. [21] say that the number of proxies increased in the last couple of years and the transparent proxy increased significantly. They are unsure whether overcoming immutability has a positive or negative impact. Salehi et al. [18] report a growth in proxy upgradability contracts on Ethereum as well. Salehi et al. further identified changes with the terms retail changes and wholesale changes. Retail changes are made as small changes to components inside a smart contract. Those contracts need to be set up beforehand to be able to handle changes. The simplest retail change is a parameter that can be updated with a setter method. The second retail change is when a contract has a function that calls another contract with the logic for that function. Here, the contract can store the address in a changeable variable and therefore the logic of the function can be changed or bugs can be fixed. On the other hand, wholesale changes enable the modification of entire contracts. The simplest wholesale change is a so-called “social upgrade” or contract migration, where a new contract is deployed and everyone is informed about that change. Another way to upgrade a whole contract is via CREATE2-based Metamorphosis. This allows for deleting a contract and redeploying a new one at the same address. However, the required opcode SELFDESTRUCT is expected to be deprecated in a future version [22]. Lastly, the DELEGATECALL-based or CALL-based data separation is another pattern found by them. Those two patterns both consist of a proxy contract, a storage contract and a logic contract. Here, the logic contract is changed to handle updates.

2.5. Ethereum 1.0 vs. 2.0

Most publications related to gas-saving or smart contracts in general refer to Ethereum 1.0. It is, however, important to note that the core virtual machine which eventually runs compiled smart contract code, the Ethereum Virtual Machine (EVM), is used by numerous other blockchains e.g., Binance Smart Chain, Polygon (formerly Matic) and Avalanche. As a general rule, all open permissionless blockchains allowing the execution of smart contracts always rely on some kind of metric for making execution steps costly in order to prevent overtaxing or exploiting the network [23]. For EVM-based blockchains, gas is almost exclusively used for such a metric.
Ethereum itself is currently undergoing a far-reaching and architecturally challenging change, which is commonly referred to as Ethereum 2.0. This change includes significant modifications to the overall network design, most notably switching from the energy-intensive proof-of-work consensus to the much more economic proof-of-stake scheme. This also includes introducing a new blockchain solely for coordination, the Beacon chain, as well as sharding concepts for scalability. The transformation towards Ethereum 2.0 is happening in multiple phases. It is still in progress as of the end of 2023 and is expected to continue for another 5–10 years [24].
The Ethereum organization claims that around 99.95% less energy is consumed by the network now. This is in line with Kapengut and Mizrach [25], as they state that the consumed energy by the Ethereum network was reduced by 99.98% with the switch. Some misconceptions were that the network would be faster afterwards and that the gas fee would become lower. However, the change was only for how to reach consensus and not for improving the performance or capacity of Ethereum [11]. Generally, the amount of gas required for any particular smart contract to run will remain similar, even though the variability of effective costs for such transactions still remains a significant factor and is subject to change.

2.6. Oracles

While smart contracts are self-executing, deterministic entities, they do not have direct access to data outside the blockchain ecosystem they are running in. Oracles are third-party services that can provide smart contracts with such information as, e.g., stock data or game results [26]. Even though Oracles may drastically widen the potential areas of application regarding smart contracts, they are typically represented by a central authority, disrupting the claim of trustlessness of many blockchains and introducing a single point of failure or manipulation [27]. From a security point of view, an attack known as Oracle manipulation aims at manipulating Oracle answers in order to invoke unintended execution flows in smart contracts. Kjiam et al. [20] discuss countermeasures against this attack, which primarily revolve around using time-weighted average values when processing Oracle data, and instantiate an M-of-N Oracle approach rather than only relying on a single Oracle provider. Oracles can directly (service fees) or indirectly (transaction fees) increase the amount of gas required, but they are not inherently relevant to the topic of gas savings and hence disregarded for this study.

3. Related Work

This section presents an overview of the related literature. Each work is briefly described and its differences compared to this paper are highlighted. They are sorted into the different categories of the best practices list. First, the publications for general best practices are presented and we continue with security recommendations and gas-saving patterns. Next, related works for tools assisting with security and gas optimization are introduced. The last part is about token standards, especially NFT standards.

3.1. General Best Practices

The related works in this section are two-sided, with software engineering recommendations and suggestions specifically tailored to blockchain development and Solidity.
Jones [28] examined over 600 companies as well as government organizations and created best practices for software engineering, ranked by an average score. The biggest expenditures were located and put into a list, with the four most expensive ones being bug fixes, cancelled projects, documentation and security flaws. In 6th place is coding and in 14th place is avoiding security flaws. Comparing it to smart contract development, the security aspects could be even ranked higher, as they have the highest emphasis, according to Zou et al. [8]. Jones, moreover, argues about two important points. Firstly, that software varies greatly in size and therefore the best practices vary as well. Smaller projects might gain more from some practices than larger projects and vice versa. Secondly, software engineering often does not have a universal way of proceeding with different types of software. For instance, open-source applications, military applications and games all have different requirements. This is equally true for Solidity, where the range of functionality can vary greatly. The ConsenSys best practice list [29] uses a similar philosophy and gives examples of when to use different patterns over others. Comparing the resulting best practice list of Jones [28] with the results of the best practices for Solidity from other works [8,29,30] indicates some relations. Reusability is ranked at the first position in the list and it is also an important part of smart contracts. ConsenSys [29] states that maximizing the reuse of code wherever reasonable is desirable and the safest way is to reuse own code.
Martin [31] argues in his book Clean Code about how to write better code. He starts with general clean code and continues with discussing naming conventions, functions, classes, comments and other topics of his best practices. He further urges testing the code heavily, which is highly recommended for Ethereum as well [29,32]. James O. Coplien says in Clean Code [31]:
“Code is never perfect.”
This quote should alert Ethereum developers of the implications for blockchain development. ConsenSys [29] predicts something similar and says that there will be bugs in any non-trivial contract. ConsenSys recommends having the option to pause a contract, manage rate limits and have upgrade paths for enhancements and fixing bugs. In general, Clean Code is a helpful general advisor for the best practice list.
ConsenSys [29] documentation for Ethereum smart contract best practices explains how to write good and safe Solidity code according to their standard. The documentation is set up as a git repository and currently has more than 6600 stars, making it their most starred repository, followed by their developer tool list for Ethereum with around 4600 stars. Their recommendations are security-related and they target intermediate Solidity programmers [29]. The collection begins with general security mindset, development recommendations and code patterns. Furthermore, known attacks, how to avoid them and security tools helping to detect vulnerabilities are explained. Their work is a great resource for developers looking for best practices, as can be seen by the popularity of their GitHub repository. ConsenSys’s work still differs from this paper, as they do not go into detail on gas savings and do not contain all recommendations given in this paper.
Antonopoulos and Wood [32] present a great starting resource for Ethereum development. They start with an introduction to Ethereum for beginners and afterwards explain more technical topics suited for developers. The more advanced topics contain Ethereum clients, wallets, transactions, the Ethereum Virtual Machine and consensus algorithms. They also explain smart contracts with Solidity and security-related best practices. Their work is a great resource for Ethereum developers, but it is partly more focused on giving a broad overview of blockchain technology while neglecting more specific topics like gas savings and the Solidity optimizer. Furthermore, the development of Ethereum is fast-paced and some vulnerabilities and facts are not up-to-date anymore. For instance, the consensus mechanism of Ethereum changed. However, they remark that the consensus mechanism could be changing. Therefore, this paper will be an extension of points made in their work.

3.2. Security

The importance of security is emphasized by Zou et al. [8]. In their work, they interviewed 20 people with Solidity experience and did a validation survey with 232 respondents to see challenges and opportunities in the field. A total of 75% of the respondents agreed that the code security required for smart contracts is a lot higher than for traditional software. The three major reasons are the sensitive information being handled, the irreversibility of transactions on the blockchain and that the code is not modifiable after deployment. In addition, around 70% of the developers answering the survey said that it is hard to guarantee security. They mention the ConsenSys [29] documentation but argue that following this guide still is not enough for the requirements of developing smart contracts. This is where this publication tries to improve the situation by creating and collecting best practices for developing with Solidity on Ethereum.
Kushwaha et al. [33] conducted a review of Ethereum vulnerabilities. In their review, they present different attacks, their underlying causes and state which tools were able to find them. They did not state which tool is best to use, but are more concerned with improving the tools, especially when new features are introduced. In their work, they do not focus on any of the other best practices categories like gas saving or ERC standards. Furthermore, they do not discuss the security implications of proof-of-stake, as their publication was before the transition to proof-of-stake. Therefore, this study is a great guide for the security part of our proposal, with additional information being added.
Chen et al. [7] provide a survey for the system security of Ethereum. The thorough survey shows vulnerabilities, their possible attacks and lastly the recommended defences. They classified 40 vulnerabilities at different layers of Ethereum. They found some insights which are valuable and can be compared to the work of others. They argue about the importance of domain-specific best practices, because 10 out of 14 types of vulnerabilities are non-existent in traditional software. Of those 10 types, 9 can be prevented by following best practices. They further state that due to Ethereum being permissionless and immutable, writing safe code is harder compared to traditional software and it is even a security barrier. The attackers can hence attack at will and the often-used mechanism of vulnerability-patching in conventional software is by default not possible. These findings are backed by the earlier presented findings of Zou et al. [8] when interviewing Ethereum developers on why it is hard to write safe code and guarantee security. Code reuse potentially inflicts a greater risk, compared to traditional development systems. Marchesi et al. [34] write that one should use libraries but also remark on potential security issues. ConsenSys [29] states that OpenZeppelin’s library for Solidity tries to provide secure code and that reusing one’s own code is the safest option. The work of Chen et al. [7] helps improve the security best practices of this proposal.
Wohrer and Zdun [30] elaborate on six smart contract security patterns to mitigate typical attack scenarios. Their patterns try to improve the execution control after a smart contract is added to the blockchain. The patterns focus on allowing the owner to stop smart contract execution or by adding different types of so-called speed bumps to slow down the execution time. Their patterns are a great start to writing more secure code but are not exhaustive. They also observe the fact that a substantial part of the knowledge and the research are scattered and that it can be found in the grey literature and blog articles.
Wang et al. [35] provide a blockchain-based smart contract overview. They show the operating mechanisms, use cases, challenges and basic framework. The two most discussed blockchains in their paper are Ethereum and Hyperledger Fabric. They categorize the problems and challenges, similar to Praitheeshan et al. [36], with contract vulnerabilities and blockchain limitations, but also add legal and privacy concerns. They remark that it is difficult to keep data private and critical methods safe. This study tries to extend the written challenges from Wang et al. [35] and elaborate on security issues.
Destefanis et al. [37] provide a case study on the Parity [38] library for smart contracts. In their investigation, they highlight that the vulnerability was already revealed and discussed in earlier literature. They, therefore, call for following best practices and standards in blockchain development, which this work is trying to improve by creating a detailed summary of best practices.
The work of Atzei et al. [39] is, according to them, the first systematic structured composition of Solidity and Ethereum vulnerabilities. Their work aims to help smart contract developers and researchers improve their verification and analysis methods. They created a taxonomy of vulnerabilities with common programming pitfalls and further showed corresponding actual attacks that had been carried out on contracts deployed on the Ethereum Mainnet. Their taxonomy is one of the most established ones, say Dika and Nowostawski [40], who also used it for their vulnerability list. Their work further warns of the security vulnerability leading to the Parity attack before it happened, said Destefanis [37]. Lastly, other scientific works have extended their work, for example Kushwaha et al. [33].
Marchesi et al. [41] provide a security checklist for developers containing 32 best practices and 16 abstract security patterns. The best practices are split into the design phase, the coding phase and the testing phase. This publication further tries to improve their security lists with further best practices from other parts of Ethereum and Solidity development.
Chen et al. [42] collected smart contract defects from more than 17,000 StackExchange posts and defined 20 vulnerabilities for five different aspects. The aspects are availability, maintainability, performance, reusability problems and security. Furthermore, they defined five impact levels ranging from IP1 to IP5, with IP1 being the most critical and IP5 the lowest, where IP4 and IP5 are similar to code smells from Fowler [43] or Martin [31]. These code smells do not cause critical behaviour on their own, but over time can decrease development speed and enhance the risk of bugs being added later on. Their categorization of the impact of defects highlights that vulnerabilities and tips have varying impacts and not all are equally important.
Zhang et al. [44] investigated 516 unique smart contracts deployed to the Mainnet. They created a bug model for the simplification of finding future bugs. They have earned USD 102,660 with their findings in bug bounties. Some of their findings are that around 80% of bugs are not auditable by a machine and that most exploitable bugs are difficult to find. This shows that only using tools is not a feasible option if one is aiming for high security. This serves as a reminder in the best practice list to not trust tools blindly.

3.3. Gas Savings and Design Patterns

This section contains general gas-saving related publications and scientific research that tried to find design patterns that are good for gas savings and antipatterns that can be gas costly.
Marchesi et al. [34] showed in another paper a collection of design patterns for saving gas. In total, 24 patterns were presented in the following five different categories: external transactions, storage, saving space, operations and miscellaneous. Although they also elaborate on many areas for gas savings, they do not explain and emphasize the consequences of some of their presented patterns. For instance, the introduced proxy pattern does well in saving money if one or multiple contracts had needed to be redeployed. However, they do not address the required additional complexity and potential security issues arising from proxy patterns [29].
Research on the mutability and upgradeability of smart contracts on Ethereum was conducted by Salehi et al. [18]. They classified six upgradeability patterns into two types, which they named wholesale changes and retail changes. Different patterns for upgrading are explained in Section 2.4. Furthermore, they developed a framework to detect the number of smart contracts on Ethereum that use a certain type of upgrade pattern. Around 1.4 million contracts with proxy patterns were found by their framework. Interestingly, with 8225 contracts, the number of unique proxy contracts is only a fraction of that. Their work helped identify different proxy contract possibilities.
Kong et al. [45] showed an approach for the detection and optimization of six inefficient patterns on the source code level. The focus therefore is on development issues caused by programmers. A total of 160,000 smart contracts from the Ethereum blockchain were analyzed and their findings were applied. They found that 52.75% of the contracts showed a minimum of one gas inefficiency. They state, without providing a concrete number, that a lot of money could have been saved if gas optimizations had been applied to all 16 million smart contracts that were available at that time. Their work highlights that small improvements can have huge effects on a large scale. Their work is only focused on gas savings and not on other best practices.

4. Methodology

This section contains the project that was set up to test the different aspects of smart contract programming and to gain knowledge about the domain by hands-on practice. First, the conception phase is explained and it is followed by the implementation. Eventually, the results of the project are presented.

4.1. Project Concept

Figure 1 visualizes a comprehensive overview of the methodology process. Each step is discussed in more detail in the section below. The first step was to find the related work, which was explained in Section 3. This provides a solid understanding of Ethereum’s fundamentals and highlighted the parts that were less researched. Less researched parts were a comparison of the different NFT standards including their gas efficiency and a best practice collection containing as much about Ethereum as possible, including security, gas savings, development tips and other insights. Following the research, the outcome of this project was set to investigate NFT standards and combine best practices from all domains of Ethereum. The findings were presented on a token-gated website that allows for minting different NFTs. After owning one of the tokens, the findings are accessible.

4.1.1. Learning Tools and Resources

After researching scientific publications, further research was done by visiting Ethereum learning platforms to find further Solidity and Ethereum-related best practices. The following resources are a valuable addition to the Ethereum space. The Ethernaut [46] by OpenZeppelin currently contains 30 Solidity levels that are intended to be hacked. Cryptozombies is another interactive learning platform to study different blockchains with. At the time of writing, there are six free courses available. Solidity by Example is another website to introduce Solidity to new developers. All concepts and ideas are presented with a smart contract example.

4.1.2. Collection of NFT Standards

The most prominent token standards are the ERC-721 and ERC-1155. They have often been mentioned in scientific publications [47,48,49,50,51,52,53,54]. Therefore, the preferred tokens for analysis were selected by popularity, as these tokens are the ones being used and detailed research of their costs was deemed helpful. The standards ERC-721, ERC-721A, ERC-721R, TinyERC-721, ERC-998 and ERC-1155 [11] were chosen for a more thorough investigation, containing use cases, deployment costs, mint costs and transfer costs. Some contracts were again dropped from the list due to time constraints, missing popularity or bugs in their implementation. Lastly, the final selection consisted of the following four standards ERC-721, ERC-721A, item ERC-1155, ERC-721 from Zora. Zora’s ERC-721 is not a standard on its own, but they have a website that allows users to create and deploy an NFT collection with little knowledge. Additionally, the contract the user creates is not a standard ERC-721 contract, but a proxy contract containing the user’s modified settings and pointing to another contract with the required logic. The main logic of minting, transferring and other parts are deployed on another contract that the proxy contracts call. Hence, minting and transfer costs are interesting, as the underlying mechanism works a bit differently.

4.2. Implementation

In this section, the implementation details concerning the smart contracts, the test cases and the audits are explained. The contracts were created to be as similar as possible, with a very limited set of functionalities. Each contract contains at least a mint function that enables minting and a constructor.
The tests of the NFT standards are a continuation of the work of the Azuki team [55] and Hu [56]. The standards were tested with HardHat on gas efficiency and functionality in different domains. These tests contained minting and transferring. The deployment costs were checked on Remix, as it is easily possible to deploy to a testnet from there. The deployment was done twice, first with the default settings, where the Solidity optimizer is turned off, and a second time with the optimizer turned on. The optimizer was used with the default settings of 200 runs.

Applying Best Practices to Deployed Contracts

The collected best practices were not only applied to the standard ERC implementations but also to a few contracts deployed on the Mainnet. The contracts were reviewed manually and then locally redeployed. Each test was adapted towards the contract and the parts that were optimized. All contracts were tested on deployment costs.

4.3. Project Results

4.3.1. Deployment Costs

The deployment costs for the NFT standards are depicted in Table 1. A significant reduction in gas costs can be achieved with the optimizer turned on.
The amount of effort required, in comparison to the gain in these cases, is minimal. In Remix, the optimizer can be turned on with the check of a button. In a setup with Visual Studio Code and HardHat, one can turn on the optimizer by setting a variable to true in the hardhat.config.js file. Lastly, the expected runs of the code can be adapted to easily modify the optimizer. More background explanation can be seen in Section 2.2 and more advanced information on optimizer settings in Section 5.3.1. The ERC-721 contract created by Zora was not adaptable, as one cannot change optimizer settings on their website, albeit, they have the optimizer turned on and the created contract is optimized for 5000 runs. Its small deployment size can be explained by the minimal proxy that was deployed, while the ERC-721 requests are forwarded to their main smart contract containing that logic. This information results in Box 1:
Box 1. Optimizer savings
Insight 1: The optimizer decreases the gas required for the deployment of a basic ERC-721 or ERC-1155 contract between 43.01% and 46.81%.

4.3.2. Deployment Time

There is a significant change in gas prices when the network is congested, state Cong et al. [57]. The fluctuation can also be seen clearly on Etherscan [2], where the average daily gas price in Gwei is shifting heavily over the whole time. Gas prices also fluctuate daily. On the 6th of July 2023, the gas price fluctuated between 19 and 138 Gwei [2]. Interaction with the blockchain, for instance, a transaction, could cost around 725% of the lowest fee. The computation for the maximum price fluctuation can be seen in calculation (1). Notably, this scenario is about the greatest gap during the day, but significantly lower differences in the gas price still have a great impact.
138 Gwei ÷ 19 Gwei × 100 = 726.32 %
Formula (2), shows how to calculate the gas fee for a transaction. It takes the units of gas used by the desired interaction and multiplies it by the current base fee plus an optional priority fee. By setting a priority fee, the validators are incentivized to include the transaction earlier into the blockchain, as they get to keep the tip [11]. The interaction can be a simple Ether transaction, which requires 21,000 units of gas [58]. There are also more costly contract deployments, for instance, the Bored Ape Yacht Club, the biggest Ethereum NFT project in total trading volume on OpenSea [59], costs 3,893,600 units of gas.
Units of Gas Used × ( Base Fee + Priority Fee ) = Total Fee
It is possible to set the optional parameter maxFeePerGas. The adapted formula can be seen in Formula (3). Participants then never pay more for the transaction than declared and a surplus is returned to the user [11].
Max Fee ( Base Fee + Priority Fee ) = Returned Fee
Akiyoshï [60] explains a technique for how to save gas with this parameter. If the network is currently congested and the current base fee is high, the max fee should be set lower to a more normal network status. How low and what a normal network status is can be inferred from Etherscan’s Gas Tracker [2]. These gas fees vary at all times. Therefore, stating a value that is best for all times is infeasible. The transaction will stay with the pending status and will be conducted once the network is less busy. It is important to note that the maxFeePerGas ought not to be set too low, as this could end in the transaction never being executed. Furthermore, if the transaction is time-critical and should be added to the blockchain as soon as possible, the strategy should be inverted, meaning a high max fee should be set so that that transaction is preferred by validators over others. This leads to the next finding (Box 2):
Box 2. Network state implications
Insight 2: The cost of deployment and interaction on Ethereum is heavily influenced by the congestion state of the network. Non-urgent interactions with the Ethereum blockchain should be set with a low max fee.

4.3.3. Applied Best Practices

The audits on ERC-721 contracts showed that other gas saving tips [34,45,61] lead to significantly smaller savings. This is consistent with previous work from Kong et al. [45], where 52.75% of researched contracts could be improved by USD 0.30. However, they argue that applying it to all contracts can save a lot of money. The fact that small savings can compound to larger savings is true, yet this paper argues that easily attainable savings should be prioritized first. This is still not done by some, as can be seen on Blockscout [62], where at the time of writing some still did not use the optimizer on deployed contracts.
Moreover, compared to insight 1 and insight 2, other gas savings tips can have a bad impact on readability. In particular, more advanced gas-saving tips can reduce readability. It is not the case that any gas saving automatically decreases the security or adds bugs. However, Martin [31] cautions that obscured domain logic reduces quality, as it allows bugs to hide more easily. These findings are similar to those of related work. Zou et al. [8] write about there being a trade-off between code readability and gas optimizations. The code smells, found by Di Sorbo et al. [61], were generally agreed upon by developers of smart contracts, but the developers raised awareness that some optimizations could harm readability. Small gas savings should not be the reason why a bug or an attack is possible. This leads to the next insight (Box 3):
Box 3. Security vs. gas-saving
Insight 3: Security should be prioritized over other aspects that can harm it, such as gas-saving techniques.
If a contract is, however, used by many users, gas savings should be utilized as much as possible. Similar to ConsenSys [29], this study wants to emphasize that different projects and smart contracts need to be coded differently. A one-time mint ERC-721 NFT contract has different requirements than an OpenZeppelin library. Small gas savings can make a big impact if they are saved in a library that is often used. This shows the next observation (Box 4):
Box 4. Size vs. functionality
Insight 4: Not all smart contracts should be treated the same when it comes to best practices. Smart contracts benefit differently from the best practices, depending on their size and functionality.

4.3.4. Project Limitations

A manual analysis of smart contracts by only one reviewer leaves space for error or missed potential. However, the results are strengthened by their similarity and consistency to other publications mentioned. The application of the best practices on more contracts could have been beneficial, but again were similar to other related work and were aborted due to time constraints.

5. Best Practice Analysis

This section presents the best practices found through research on related work from Section 3 and practical tests discussed in Section 4. The various points are grouped into different categories and together form the whole recommendations list. Each section explains the individual parts and demonstrates the similarities and contrasts to other works. The category structure of the best practices was partly taken from other related works [7,29,41].

5.1. General Blockchain Development Philosophy

The composed best practice list for general development on Ethereum is analysed here. The list is depicted in Table 2 and contains the most important general findings.

5.1.1. Simplicity

The first recommendation is to prefer simple contracts over complex ones. This should be done with clean code and small contracts. Antonopoulos and Wood assert [32]:
“Complexity is the enemy of security.”
This quote explains why one should strive for simplicity. Simplicity helps to make code more secure, by making it easier to understand the program flow, the intention behind the code and making it harder for bugs to hide [31]. Security is a primary concern for programming on Ethereum, claim Tikhomirov et al. [6]. Alchemy [63] adds to this rule by reminding that it does not imply to avoid creating smart contracts with many features. Its core message is to start from a simple standpoint and build more complex functionality with high code quality from there.

5.1.2. Expectation of Failures

The next principle is to prepare the code for failure. Wang et al. [64] say that it is impossible to claim that code has no bugs. They further state that even highly experienced teams that write contracts and audit them are not exempt from that rule. In conventional software, it is normally easier to stop, pause or remove your service when it is malfunctioning. On Ethereum, that is by default not possible, which is yet another reason why preparing for failure is important. To get some functionality to assist with this problem, one of the following mechanisms could be used:
  • An upgrade mechanism for smart contract;
  • A pause functionality of critical functionality;
  • Some limitation rate to reduce maximum usage or withdrawal.
Upgrade mechanisms help improve security and can help save gas. Therefore, this tip is further analyzed in the security Section 5.2 and the gas-saving Section 5.3. A pause functionality can be helpful to pause withdrawals or other important parts of a smart contract in the event of an unexpected behaviour occurring on the smart contract. Lastly, limiting the usage is another solution to have more time to respond to undesired interactions.

5.1.3. Strategy Adaptation

The recommendation to adapt the strategy is true for general software development and for Ethereum development. There is often no one-size-fits-all technology, technique or “silver-bullet”, as stated by various sources [7,28,29,43,65]. The strategy should be first adapted from conventional software engineering to blockchain development. Secondly, adaptations between different smart contracts should be undertaken as well. Some unconventional programming patterns should be used on Ethereum, which is due to its blockchain characteristics [30]. The quote from Maslow explains what happens if one does not have different strategies to choose from [66]:
“I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.”
Different requirements require different solutions. Adapting the strategy also means implementing different functionalities at different times.

5.2. Security

The problem with security on Ethereum and other public blockchains is a combination of circumstances. Generally, security [8] and bug-free code [64] are hard to guarantee. Furthermore, attackers can attack whenever they want, since Ethereum is permissionless [36]. Moreover, contracts can hold high monetary value, making it attractive for adversaries to attack [1]. The situation is improved in permissioned blockchains, but according to Staples et al. [67], not even private blockchains are potentially private enough. They argue that private blockchains share information between their nodes and if competitors are in the same network, they have the potential to attain sensitive information about their competitors. Developers need to therefore prioritize security and make Ethereum safer. Table 3 contains guidelines to improve safety. Although it is not feasible to get rid of all security issues, since new attack vectors can arise at any time, it is at least possible to protect oneself against known attacks.

5.2.1. Code Reuse

Reusing code is a common practice and recommended by many in the Ethereum domain [11,29,41,68]. Antonopoulos and Wood [32] emphasize that reusing trusted code is possibly the most fundamental principle for security. They further warn that reinventing the wheel with new code is likely going to be less secure than extensively tested and used libraries. There is a saying in cryptography for that: “Don’t roll your own crypto”. However, it is noteworthy that Chen et al. [7] remark that the reuse of code on Ethereum possibly carries a higher risk than in traditional systems and therefore reused contracts should be security audited. In summary, it can be said that well-tested and widely used libraries can and should be used. OpenZeppelin [69] is a prominent example that offers a variety of such smart contracts that should be reused.
Table 3. The security best practices list.
Table 3. The security best practices list.
Security Best Practices
NameDescriptionReference
Reuse Code and LibrariesWell-tested and widely used libraries are good for reuse and most often outweigh the benefits of creating everything from scratch. The more complex the code is, the better it is to rely on audited libraries.[11,29,32,41]
Contract UpgradesFor more complex and long-lived smart contracts, a proxy pattern or another upgradeable pattern is advisable to fix critical flaws that could render a contract useless or insecure. This reduces gas costs, as otherwise, multiple contracts would need to be redeployed. The security implications are two-sided. It enables bug fixing but also introduces new security vulnerabilities.[18,41,69]
Check-Effect-InteractIt is difficult to check if code could be used differently than anticipated. As a defensive safety mechanism, the general order of the Solidity code should be, to check the condition first. Afterwards, update the checked state and only, as a last step, should an external call happen. Otherwise, reentrancy attacks are possible.[7,16,32]
Pull Over PushThere are two possible ways to send ETH. A smart contract can be sent to other accounts or have the ability for other accounts to actively pull the resource. For external calls, it is advisable to implement a pull mechanism. They should be separated into their own function that the user calls. Otherwise, a denial of service with an unexpected revert could happen.[7,29,40,70]
ReadabilityClear and simple code is easier to check for bugs and better for audits. Contracts should be built with open-source methodologies and collaborations. Documenting code and following the styling and naming conventions further help.[16,29,32]
TokenizationUsing token standards is highly recommended and each has different benefits and side effects. Prominent tokens are explained in Section 5.2.5.[32,41,51,71]
TestingHigh test coverage is recommended as smart contracts are executed in a public environment and anyone can interact with them. Make use of the test networks and test over multiple stages during the development.[6,11,29,32,37,41]
Stay Up-To-DateAlways use the current stable versions of Solidity. All tools and the libraries used for development should be up-to-date. When new security techniques are introduced and vulnerabilities are discovered, check if they concern your smart contracts.[29,37]
Interact With Ethereum SecurelySafe general interaction with Ethereum is key to avoid pitfalls. These include key management and being mindful of scams. Due to Ethereum’s decentralized nature, it is not possible for a centralized authority to help in the case of key loss.[11]

5.2.2. Upgradeability Trade-Off

Generally, blockchain-based software benefits from the immutability aspects, but some degree of modification is necessary for feature improvements and fixing problems, says OpenZeppelin [69]. If a vulnerability is found on production smart contracts, the desired action is to fix the problem. However, circumventing immutability and adding upgradeability bring about their own risks [29]. OpenZeppelin [69] report that upgradable proxies are difficult to use securely and correctly. They discuss the problem that both the proxy contract and the contract containing the logic access the same state variables and the same risk of overwrites. Furthermore, a programming overhead and increased complexity is added when including proxy logic.
The recommendation is for bigger projects and contracts that are used over a longer period should make use of upgradable patterns. There is a variety of possible solutions. For instance, Meisami and Bodell III [72] found 11 different patterns for upgradable proxies. Small and short-lived projects might work better without the added overhead.

5.2.3. Reentrancy and Check-Effect-Interaction Method

Reentrancy means that during the execution of the code, the executed smart contract is called multiple times by an attacker contract during one transaction. The first reentrancy attack was used during the DAO hack [29]. One possible scenario of reentrancy is to drain the balance of a smart contract. Reentrancy is the vulnerability that has been investigated most extensively, with 17 defence mechanisms developed, says Chen et al. [45]. Many defence mechanisms aid with this problem. A simple one is the recommendation “Check-Effect-Interact” of Table 3.

5.2.4. Pull over Push

There are two options to make an external call for a ETH transaction. A smart contract can try to push the ETH or have a pull mechanism that is activated by the other account that should receive the ETH. If a transaction is required to go through, an implementation that uses a push mechanism is at risk. Either maliciously or unintentionally, users can bring the smart contract to a halt. If the receiving account is a contract, it could, as an example, revert when receiving ETH. A real-world example is the Akutar auction contract [73]. It had a push mechanism to refund ETH back to bidders who did not win the auction. A hacker used it and locked it to prove the point of audits and security. Since the hacker had no ill intentions, they reopened it again. This could have been avoided by implementing a pull mechanism.

5.2.5. Token Standards

Each token standard has its benefits and disadvantages and should be used for the right use case. The ERC-20 is often used for simple interchangeable tokens. ERC-721 and its modified versions allow for differentiating between the tokens. If multiple different tokens are planned or multiple tokens are expected to change owner, the ERC-1155 is recommended to use.

5.2.6. Readability

The importance of readability of code is often mentioned [8,31,32,61]. Readability is a lot about clear and simple code, as it helps developers and auditors to quickly understand the purpose of a function or a smart contract. One additional thing to consider with Ethereum, is the trade-off with some gas savings, as they can hurt readability. Therefore, if there is no strong reason for a specific gas saving, especially for a small saving, one should deter from adding it. This tip was a finding from Section 4 and has been similarly mentioned by others [8,61].

5.2.7. Testing and Staying Up-to-Date

Over time, new token standards have been introduced to Ethereum. It is important to keep up to date, as they help with the development and make it safer to interact with them. Testing should be done often and early and can be seen as a minimum security requirement. There are different tools to test smart contracts. One can have automated testing with unit tests, integration tests, property-based tests and static and dynamic analysis tools. Furthermore, smart contracts can and should be tested manually. This includes testing on a local blockchain, testing on a currently active testnet, having bug bounties and audits. The recommended approach is to use a mix of all possible tools and to adjust the effort relative to the project size and functionality [11,32].
Dannen [74] also concludes that it can be challenging to acclimate to the fast pace of blockchain development. The best practice of staying up-to-date leads to the next finding (Box 5):
Box 5. Occurrence of breaking changes
Insight 5: The development of Ethereum and its accompanying tools is fast-paced. Breaking changes happen continually.

5.2.8. Secure Ethereum Usage

With Ethereum, there is no centralized authority that can intervene due to the underlying technology. The user has to keep their private key safe or use a strong password for their wallet. It is possible to lose access to one’s wallet if the user forgets their private key. On top of the required key management, the users need to be aware of scams. A sceptical mindset is recommended. Common scams include asking for the private key or telling someone to send ETH to an address with the promise of huge returns. Moreover, scams also occur when interacting with smart contracts [11].
Vitalik et al. [75] have proposed the ERC-4337, which allows users to have smart contract accounts instead of externally owned accounts. It would allow for more user-friendly keys and key recovery according to Alchemy [76]. Alchemy acknowledges that it also possibly introduces new security risks and that interaction with using account abstraction would lead to more expensive interactions due to the overhead.

5.3. Gas Savings

The gas-saving parts of the best practices are separated into a general and an advanced part. The reason for that is that the general section is mostly a selection of low-cost, high-impact tips that provide great benefits with little effort. On the other hand, the more advanced savings require more in-depth knowledge about Solidity and yield smaller rewards. While smaller changes combined can also make a huge difference, the effort is higher. These tips can also change with newer versions of Solidity.

5.3.1. Solidity Optimizer

As found in Section 4, the Solidity optimizer improved simple ERC-721 and ERC-1155 contracts by more than 40%. The findings on the optimizer were interesting because a reduction of more than 40% for projects should be emphasized more than it is and it should also be turned on by default. It is, however, noteworthy that using an optimizer does not come without some concerns or past bugs. There are multiple occasions where issues with the Solidity optimizer were found [77]. Moreover, the Solidity documentation [16] warns against using some experimental features. Lastly, the improvements found for simple ERC-721, ERC-721A and ERC-1155 token contracts cannot automatically be assumed for other contracts. Checking the Solidity optimizer against other types of contracts is a future work task. According to a blog post by the Solidity team [78], they admit that earlier versions of the optimizer were complicated and contained bugs, but since late 2020, they recommend to always use the optimizer. They state that only if someone does not care about gas costs at all can they then disregard the optimizer.
An important setting is the runs setting. It gives the optimizer a criterion on what to optimize for. If the value is set low, one tells the optimizer that the code will not be executed often and therefore a small deployment size is important. On the other hand, a high value means that the contract will often be executed, which sets the focus on cheaper execution costs. The standard value is 200 [16]. Finding the optimal value is not trivial and needs to be tested individually. One can do some manual tests or run some test cases and see what works best.

5.3.2. Deployment Time and Network Congestion

The time when one wants to deploy has a huge impact on the cost required to do so. Furthermore, the urgency with which the interaction has to happen can also impact the cost. In Section 2.1, the mechanism of the network that is dealing with congestion is explained.
To begin with, a clear trend can be seen for when the network is normally congested and when it is more idle, according to Marchioro [79]. The best time for interacting is at night, using Coordinated Universal Time. Interestingly, the hour of the day has a stronger dependency on the network state than the day of the week. Marchioro expects the trend to flatten out over time, as more bots for interacting with Ethereum might be used in the future. Additionally, it can be very beneficial for the cost required to interact with the network if the interactions are time-flexible. As mentioned in the methodology in Section 4.3.2, by setting the maxFeePerGas to a lower level than the current base fee, one can decrease the required cost sharply. Yet, two matters have to be taken into account. If a transaction is time-critical, one cannot utilize this. Secondly, the fee should not be set too low, otherwise the transaction might never go through. The effect of this technique is conditional on the network state. It enables the usage of the network at the lower end of the fee range. The exact execution time is not predictable.

5.3.3. Storage

All Ethereum full nodes need to store all data of the network. It would be hard for network participants to run a full node if the blockchain were to be multiple TBs large. The chain is continuously growing. Currently, it is a bit over 1.2 TB, with the Ethereum client Go-Ethereum (GETH) [80]. They state that around 14 GB are added to the database per week. The GETH client [80] has a pruning feature to keep the disk size lower. This is one of the reasons why storage on Ethereum is relatively expensive and developers have to adapt their strategy accordingly. External storage options like IPFS [81], are a solution to extract bigger data from the blockchain.

5.3.4. Solidity Gas Improvements by Versions

Newer versions of Solidity improve safety but can also help reduce gas costs. With the included check of overflow and underflow in Solidity 0.8.0, the SafeMath library has become obsolete [69]. This saves gas because the library does not have to be added. It is possible to use unchecked blocks to tell the compiler to not check those parts for overflows or underflows. This saves a bit of gas as well. However, it is not advisable to use it in circumstances where the value can overflow or underflow. Another improvement came with Solidity 0.8.4 [16], where custom errors were introduced. They can be used to improve the explanation of why a smart contract reverted. Furthermore, custom errors decrease runtime and deployment gas costs.

5.3.5. Solidity Idiosyncrasies

This recommendation should be considered more, with growing experience. It may be less feasible for a beginner who is learning Solidity to study small gas-saving details. However, over time and if the project requires it, more time should be invested in learning and utilizing more advanced tricks for saving gas.

5.4. Advanced Solidity Gas Cost Improvements

This section discusses the best practices from Table 4. As mentioned in Table 2, adapting the strategy of programming is favourable. These tips can be used to save gas, but their effectiveness depends on the various factors of a contract and its surroundings. These are the size, the expected lifetime of the contract, the expected frequency of it being used, the experience of the developer team and whether it is a library or a standard contract.

5.4.1. Gas Saving Trade-Offs

Not all developers recommend advanced gas-saving methods, since they sometimes come with reduced readability or can create misunderstandings [8,31,61]. Further, not all improvements are valid at all times nor come without side effects. Fravoll [82] provides three patterns for saving gas packing variables, memory array building and string equality comparison. These are tips to lower cost, but they also bring about problems. Packing variables increases gas cost if implemented wrong. Next, the complexity can increase when using memory array building. Lastly, string equality comparison has not been used in a production environment according to Fravoll.
According to Valverde [83], the lesser sign (<) and greater sign (>) should be favoured over the less than or equal sign (≤) and the greater than or equal sign (≥). This tip is for a slightly more gas-efficient code. However, this could lead to confusion, when the contract for example contains a check if the maximum number of NFTs per transaction is exceeded. The code for both smart contracts is presented in Figure 2. If one only checks the contract quickly, they could think that the maximum amount to mint is 11. If the user then tries to mint 11 pieces in one transaction, it would revert due to the maximum only being 10.
Table 4. Advanced Solidity improvements, recommended for libraries and other frequently used smart contracts.
Table 4. Advanced Solidity improvements, recommended for libraries and other frequently used smart contracts.
Advanced Solidity Improvements
NameDescriptionReference
Minimal Proxy ContractUsing a minimal proxy contract allows cheap contract functionality cloning. The contract only implements some parts and delegates to another contract holding the logic. Therefore, the deployment cost can be reduced.[84]
Cache Storage ValuesBefore reading storage values multiple times from storage, it is better to copy them to memory once and then read from memory.[85]
Use BitmapBitmaps are useful to save data in a compact and gas-efficient way. Each entry only takes one bit instead of 8. The cost of writing to storage depends on the value stored before overwriting it.[86]
Variable PackingThe state variables are stored in 32-byte slots. If smaller state variables are declared next to each other in a smart contract, the Solidity compiler packages them together and therefore saves storage and gas.[11,34]
Use UINT256If variables are not packaged, it is better to use uint256. Otherwise, the variable has to be converted to a uint256 variable every time.[34]

5.4.2. Minimal Proxy Contract

If one has to issue smart contracts with similar functionality, using a minimal proxy contract could be beneficial. Manifold states that deployment costs are low due to using a delegate proxy implementation [87]. This tip is only utilizable under certain requirements. One requirement is that similar code needs to be required by multiple contracts. However, due to its gas savings, it should be kept in mind. The minimal proxy contract standard ERC-1167 by Murray et al. [84] has nothing to do with upgradeable contract patterns, neither is it a replacement for it.

5.4.3. Storage vs. Memory

There is a gas discrepancy between interactions with memory and storage on the EVM. The loading and writing to memory is cheaper compared to doing the same thing on storage variables [85,88]. It is recommendable for variables that are used multiple times to load them first to memory, interact with them and lastly store them back into the storage. This means that a temporary variable is introduced that keeps the variable in memory. This tip should be used with caution, as it increases complexity slightly and can seem confusing for developers who do not know the gas implications for memory and storage interactions.

5.4.4. Bitmaps

OpenZeppelin [69] provides a bitmap library that maps uint256 to boolean, meaning that each bit of the 256 bits is an entry. The gas savings come from writing a variable that is already non-zero. Writing from non-zero to non-zero costs 5000 units of gas, while zero to non-zero is 22,100 units of gas [89].

5.4.5. Variable Packing

The EVM operates on 256-bit elements. This can be used to save on storage space by putting multiple smaller data types into one uint256 variable. This is done automatically by the compiler if the smaller variables are placed next to each other in the code. However, if, for instance, a uint16 variable on its own has to be converted to a uint256 every time it is used, It will be more expensive than when the variable is a uint256. Furthermore, if the variables are not used together, the cost of writing is also increased, because the new value is not just replacing the old, but has to be combined with the data in the same slot [11].

5.5. Tools for Auditing and Developing

When using additional tools, two things should be kept in mind. Firstly, using a security tool does not guarantee security. Zhang et al. [44] claim that 80% of security-related bugs cannot be audited by a tool. Secondly, using a gas optimizer can also bring about unexpected issues or can even introduce vulnerabilities. Therefore, one has to consider the possible side effects and decide for themselves, if they want to accept them or not. This study recommends staying with well-tested and maintained tools.
The agreement on defects between tools is low, therefore the tools should be used complementary to each other, say Di Angelo et al. [90]. Similarly, Ivanov et al. [91] found that the coverage of vulnerabilities in security tools is very different and many defects from the SWC registry [92] are not covered by any tool. Durieux et al. [93] suggest using Mythril and Slither in combination for the best results. Both tools are well maintained, which improves their appeal further.

6. Results

This section summarizes the findings of this study and recalls the research questions and checks how they have been answered.
RQ1: Multiple best practices have been found and put together into a list. Table 2 shows what general best practices should be followed. Its main points are to favour simplicity and security over other things. Program failure and bugs are a natural part of the process and should be taken into consideration from the beginning. Code quality is always preferable, but with blockchain development, high code quality is indispensable, since code faults can lead to irretrievable damage. Smart contracts can have different sizes, functionality, use cases and lifespans. Adapting the strategy on how to implement them is preferable. Last but not least, it is beneficial to do one’s own research. Up-to-date information changes regularly and some recommendations might not be applicable for every scenario. Insight 4 from Section 4 influenced the answer to this research question.
RQ2: To secure smart contracts, a lot of publications were found. Some pointed out that hacks still occur even long after defense mechanisms are developed and best practices are published. Simple best practice principles to defend against security issues are presented in Table 3. Developers should build upon well-tested libraries and code. Since protection against failure cannot be easily guaranteed, proxy patterns for updating should be applied, especially for larger and more complex projects. The two coding flows “Check-Effect-Interact” and “Pull Over Push” can boost security. Readability is important for keeping it easy to read and understand the code. Using token standards helps build upon the experience of the open-source community. Lastly, staying up-to-date is highly recommended on Ethereum. New features are introduced and vulnerabilities are discovered. The answer to this research question has been influenced by insight 3 from Section 4 and insight 5 from Section 5.
RQ3: Gas savings can have a negative influence on readability and complexity. Through the methodology in Section 4, it was visible that some techniques have fewer or no side effects and can improve gas savings heavily. These techniques can be seen in Table 5. Not all found practices are in any way new, but too little advertised for their effectiveness, for example, using the Solidity optimizer and utilizing the network when it is less busy. Furthermore, storage costs should be kept in mind when developing on Ethereum. On the other hand, there are more advanced gas savings that either are less effective or increase complexity and could harm readability. These savings are not unhelpful but should be used in the right environment. The advanced gas savings are visible in Table 4. The answer to this research question has been influenced by insights 1 and 2 in Section 4.
The research, the collection of knowledge and the answering of the research questions happened to the best of the author’s knowledge and belief. Still, it cannot be ruled out that the best practices are incomplete, faulty or will lose relevance.

7. Discussion

This is the section where the results are critically discussed and their implications for others are evaluated. Limitations of this work are disclosed, the project creation is presented and an outlook for future works is given.

7.1. Practical Implications

The found best practices should be seen as a guide for beginner blockchain developers and can function as a good lookup resource for more experienced developers. With four different lists, the best practices introduce each category and highlight the most important aspects. The lists also help get a feeling for which principles are more relevant and should be prioritized. The most important recommendations are to prioritize code quality, security and testing. A security breach should be avoided. This includes being aware of possible attack vectors and their corresponding defense mechanisms. Moreover, software projects have disparate challenges and needs. This is the same for projects on Ethereum and means that the strategy should be adapted to the smart contract’s functionality and size. Gas savings should be utilized where useful, but should not be traded for simplicity and security. Lastly, the quick progress of Solidity and Ethereum should be considered.

7.1.1. Relevance for Other Blockchains

Since multiple other blockchains make use of the EVM, some findings should be relevant to alternative blockchains as well. Some alternatives are Polygon PoS, BNB Smart Chain or Avalanche. These blockchains likely benefit the most from general best practices. However, gas savings should be less important since the fees required to be paid are much lower than on Ethereum. For example, high transaction speed and low gas fees are desired properties for Polygon [97]. In 2023, Aschauer et al. proposed a blockchain-based implementation for an Uber-like ride-sharing platform which compared execution costs of the required contracts on Ethereum, Polygon and HarmonyOne. Since all those blockchains are directly or indirectly EVM-based, the resulting gas values are similar even though the actual costs differ significantly due to vastly different transaction fees [98].

7.2. Limitation

It is hard to make the best practice list exhaustive as new vulnerabilities are discovered and other features are introduced. Hence, this study cautions the readers against blindly trusting the results. To reduce the problem of missing best practices, a wide range of popular lists, tips and helpful resources were checked to get as many diverse insights as possible. The best practices are generally not holistically applicable to other blockchains without adaptations, since many use different programming languages and architectures. Nevertheless, Section 7.1.1 summarizes the expected gains for similar blockchains. The fast-paced development of blockchains and Solidity results in some best practices becoming less relevant over time if not adapted.

7.3. Credibility of Sources

Although Ethereum was initially published in 2015 and a lot of research has been made on blockchains and Ethereum, a vast amount of knowledge and current news are first found on different blog entries, the Ethereum documentation [11] or the platform X. This point is backed by multiple papers in this domain. Oliveira et al. [99] claim that the literature on tokens is based strongly on blog posts, news articles and social media channels. Wohrer and Zdun [30] also state that best practices are found across Ethereum blogs and the Ethereum community. Ultimately, the gas-saving patterns by Marchesi et al. [34] are based partly on discussion lists and Ethereum blogs.

7.4. Future Work

Future work is imaginable in multiple directions. It is possible to add best practices for other languages on Ethereum or research other blockchains. The most apparent next language to check would be Vyper. It is the second most popular programming language on Ethereum. A security comparison between Vyper and Solidity has already been made by Kaleem et al. [70]. Such a comparison could be supplemented with further investigations into differences in tools, gas-saving techniques and standards. Another possible next step would be to research best practices for other blockchains. Checking how much these guidelines help similar technologies would be worth researching. Moreover, different blockchains, such as Solana [100] could be compared. It would be interesting to see which best practices overlap and which are completely different. There should be differences between the different architectures. Other differences like low transaction fees probably make gas savings less important.

Author Contributions

Conceptualization, M.B.; methodology, M.B.; software, M.B.; writing—original draft preparation, M.B.; writing—review and editing, E.S.; supervision, E.S.; funding acquisition, M.K. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Data Availability Statement

The entire source code associated with this publication is available at https://github.com/GitHub-Fred/Ethereum-Strategies-For-Security-and-Gas-Saving (accessed on 18 December 2023).

Conflicts of Interest

The authors declare no conflicts of interest.

References

  1. Luu, L.; Chu, D.H.; Olickel, H.; Saxena, P.; Hobor, A. Making smart contracts smarter. In Proceedings of the 2016 ACM SIGSAC Conference on Computer and Communications Security, Vienna, Austria, 24–28 October 2016; pp. 254–269. [Google Scholar]
  2. Ethereum Gas Tracker|Etherscan. Available online: http://etherscan.io/gastracker (accessed on 2 August 2023).
  3. Schwarz-Schilling, C.; Neu, J.; Monnot, B.; Asgaonkar, A.; Tas, E.N.; Tse, D. Three attacks on proof-of-stake ethereum. In Proceedings of the International Conference on Financial Cryptography and Data Security, Grenada, Grenada, 2–6 May 2022; Springer: Berlin/Heidelberg, Germany, 2022; pp. 560–576. [Google Scholar]
  4. Neu, J.; Tas, E.N.; Tse, D. Two attacks on proof-of-stake GHOST/Ethereum. arXiv 2022, arXiv:2203.01315. [Google Scholar]
  5. Neu, J.; Tas, E.N.; Tse, D. Two more attacks on proof-of-stake GHOST/Ethereum. In Proceedings of the 2022 ACM Workshop on Developments in Consensus, Los Angeles, CA, USA, 7 November 2022; pp. 43–52. [Google Scholar]
  6. Tikhomirov, S.; Voskresenskaya, E.; Ivanitskiy, I.; Takhaviev, R.; Marchenko, E.; Alexandrov, Y. Smartcheck: Static analysis of ethereum smart contracts. In Proceedings of the 1st International Workshop on Emerging Trends in Software Engineering for Blockchain, Gothenburg, Sweden, 27 May 2018; pp. 9–16. [Google Scholar]
  7. Chen, H.; Pendleton, M.; Njilla, L.; Xu, S. A survey on ethereum systems security: Vulnerabilities, attacks, and defenses. ACM Comput. Surv. (CSUR) 2020, 53, 1–43. [Google Scholar] [CrossRef]
  8. Zou, W.; Lo, D.; Kochhar, P.S.; Le, X.B.D.; Xia, X.; Feng, Y.; Chen, Z.; Xu, B. Smart contract development: Challenges and opportunities. IEEE Trans. Softw. Eng. 2019, 47, 2084–2106. [Google Scholar] [CrossRef]
  9. Turing, A.M. On computable numbers, with an application to the Entscheidungsproblem. J. Math 1936, 58, 5. [Google Scholar]
  10. Buterin, V. A Next-Generation Smart Contract and Decentralized Application Platform. 2014. Available online: https://finpedia.vn/wp-content/uploads/2022/02/Ethereum_white_paper-a_next_generation_smart_contract_and_decentralized_application_platform-vitalik-buterin.pdf (accessed on 18 December 2023).
  11. Ethereum Documentation. Available online: https://ethereum.org/en/developers/docs/ (accessed on 1 August 2023).
  12. Tsankov, P.; Dan, A.; Drachsler-Cohen, D.; Gervais, A.; Buenzli, F.; Vechev, M. Securify: Practical security analysis of smart contracts. In Proceedings of the 2018 ACM SIGSAC Conference on Computer and Communications Security, Toronto, ON, Canada, 15–19 October 2018; pp. 67–82. [Google Scholar]
  13. Canfora, G.; Sorbo, A.D.; Laudanna, S.; Vacca, A.; Visaggio, C.A. GasMet: Profiling Gas Leaks in the Deployment of Solidity Smart Contracts. arXiv 2020, arXiv:2008.05449. Available online: http://xxx.lanl.gov/abs/2008.05449 (accessed on 18 December 2023).
  14. Albert, E.; Gordillo, P.; Hernández-Cerezo, A.; Rubio, A. A Max-SMT superoptimizer for EVM handling memory and storage. In Proceedings of the International Conference on Tools and Algorithms for the Construction and Analysis of Systems, Munich, Germany, 2–7 April 2022; Springer: Berlin/Heidelberg, Germany, 2022; pp. 201–219. [Google Scholar]
  15. Albert, E.; Correas, J.; Gordillo, P.; Román-Díez, G.; Rubio, A. Gasol: Gas analysis and optimization for ethereum smart contracts. In Proceedings of the International Conference on Tools and Algorithms for the Construction and Analysis of Systems, Dublin, Ireland, 25–30 April 2020; Springer: Berlin/Heidelberg, Germany, 2020; pp. 118–125. [Google Scholar]
  16. Śliwak, K.E.A. Solidity Documentation. Available online: https://docs.soliditylang.org/en/v0.8.20/index.html (accessed on 14 July 2022).
  17. Dhillon, V.; Metcalf, D.; Hooper, M.; Dhillon, V.; Metcalf, D.; Hooper, M. The DAO Hacked. In Blockchain Enabled Applications: Understand the Blockchain Ecosystem and How to Make it Work for You; Apress: New York, NY, USA, 2021; pp. 113–128. [Google Scholar]
  18. Salehi, M.; Clark, J.; Mannan, M. Not so immutable: Upgradeability of smart contracts on ethereum. arXiv 2022, arXiv:2206.00716. [Google Scholar]
  19. Charoenwong, B.; Bernardi, M. A Decade of Cryptocurrency ‘Hacks’: 2011–2021. SSRN 2021. [Google Scholar] [CrossRef]
  20. Tjiam, K.; Wang, R.; Chen, H.; Liang, K. Your smart contracts are not secure: Investigating arbitrageurs and oracle manipulators in Ethereum. In Proceedings of the 3rd Workshop on Cyber-Security Arms Race, Virtual, 19 November 2021; pp. 25–35. [Google Scholar]
  21. Amri, S.A.; Aniello, L.; Sassone, V. A Review of Upgradeable Smart Contract Patterns based on OpenZeppelin Technique. J. Br. Blockchain Assoc. 2023, 6, 1–8. [Google Scholar] [CrossRef]
  22. Ballet, G.; Vitalik Buterin, D.F. EIP-4758: Deactivate SELFDESTRUCT. Available online: https://eips.ethereum.org/EIPS/eip-4758 (accessed on 21 July 2023).
  23. Jangid, H.; Meel, P. Blockchain Protocols: Transforming the Web We Know. In Proceedings of the International Conference on Information and Communication Technology for Intelligent Systems, Ho Chi Minh, Vietnam, 7–8 December 2023; Springer: Berlin/Heidelberg, Germany, 2023; pp. 545–557. [Google Scholar]
  24. Foundation, E. The Ethereum Roadmap. Available online: https://ethereum.org/en/roadmap/ (accessed on 12 December 2023).
  25. Kapengut, E.; Mizrach, B. An event study of the ethereum transition to proof-of-stake. Commodities 2023, 2, 96–110. [Google Scholar] [CrossRef]
  26. Al-Breiki, H.; Rehman, M.H.U.; Salah, K.; Svetinovic, D. Trustworthy blockchain oracles: Review, comparison, and open research challenges. IEEE Access 2020, 8, 85675–85685. [Google Scholar] [CrossRef]
  27. Beniiche, A. A study of blockchain oracles. arXiv 2020, arXiv:2004.07140. [Google Scholar]
  28. Jones, C. Software Engineering Best Practices: Lessons from Successful Projects in the Top Companies; McGraw-Hill Education: New York, NY, USA, 2010. [Google Scholar]
  29. Ethereum Smart Contract Security Best Practices. Available online: https://consensys.github.io/smart-contract-best-practices/ (accessed on 1 August 2023).
  30. Wohrer, M.; Zdun, U. Smart contracts: Security patterns in the ethereum ecosystem and solidity. In Proceedings of the 2018 International Workshop on Blockchain Oriented Software Engineering (IWBOSE), Campobasso, Italy, 20 March 2018; IEEE: Piscataway, NJ, USA, 2018; pp. 2–8. [Google Scholar]
  31. Martin, R.C. Clean Code: A Handbook of Agile Software Craftsmanship; Pearson Education: London, UK, 2009. [Google Scholar]
  32. Antonopoulos, A.M.; Wood, G. GitHub—Ethereumbook/Ethereumbook: Mastering Ethereum, by Andreas M. Antonopoulos, Gavin Wood; O’Reilly Media: Sebastopol, CA, USA, 2021. [Google Scholar]
  33. Kushwaha, S.S.; Joshi, S.; Singh, D.; Kaur, M.; Lee, H.N. Systematic review of security vulnerabilities in ethereum blockchain smart contract. IEEE Access 2022, 10, 6605–6621. [Google Scholar] [CrossRef]
  34. Marchesi, L.; Marchesi, M.; Destefanis, G.; Barabino, G.; Tigano, D. Design Patterns for Gas Optimization in Ethereum. In Proceedings of the 2020 IEEE International Workshop on Blockchain Oriented Software Engineering (IWBOSE), London, ON, Canada, 18 February 2020; pp. 9–15. [Google Scholar] [CrossRef]
  35. Wang, S.; Ouyang, L.; Yuan, Y.; Ni, X.; Han, X.; Wang, F.Y. Blockchain-enabled smart contracts: Architecture, applications, and future trends. IEEE Trans. Syst. Man Cybern. Syst. 2019, 49, 2266–2277. [Google Scholar] [CrossRef]
  36. Praitheeshan, P.; Pan, L.; Yu, J.; Liu, J.; Doss, R. Security analysis methods on ethereum smart contract vulnerabilities: A survey. arXiv 2019, arXiv:1908.08605. [Google Scholar]
  37. Destefanis, G.; Marchesi, M.; Ortu, M.; Tonelli, R.; Bracciali, A.; Hierons, R. Smart contracts vulnerabilities: A call for blockchain software engineering? In Proceedings of the 2018 International Workshop on Blockchain Oriented Software Engineering (IWBOSE), Campobasso, Italy, 20 March 2018; IEEE: Piscataway, NJ, USA, 2018; pp. 19–25. [Google Scholar]
  38. Parity. Available online: https://www.parity.io/ (accessed on 12 June 2023).
  39. Atzei, N.; Bartoletti, M.; Cimoli, T. A survey of attacks on ethereum smart contracts (sok). In Proceedings of the Principles of Security and Trust: 6th International Conference, POST 2017, Held as Part of the European Joint Conferences on Theory and Practice of Software, ETAPS 2017, Uppsala, Sweden, 22–29 April 2017; Springer: Berlin/Heidelberg, Germany, 2017; pp. 164–186. [Google Scholar]
  40. Dika, A.; Nowostawski, M. Security vulnerabilities in ethereum smart contracts. In Proceedings of the 2018 IEEE International Conference on Internet of Things (iThings) and IEEE Green Computing and Communications (GreenCom) and IEEE Cyber, Physical and Social Computing (CPSCom) and IEEE Smart Data (SmartData), Halifax, NS, Canada, 30 July–3 August 2018; IEEE: Piscataway, NJ, USA, 2018; pp. 955–962. [Google Scholar]
  41. Marchesi, L.; Marchesi, M.; Pompianu, L.; Tonelli, R. Security checklists for Ethereum smart contract development: Patterns and best practices. arXiv 2020, arXiv:2008.04761. Available online: http://xxx.lanl.gov/abs/2008.04761 (accessed on 18 December 2023).
  42. Chen, J.; Xia, X.; Lo, D.; Grundy, J.; Luo, X.; Chen, T. Defining Smart Contract Defects on Ethereum. IEEE Trans. Softw. Eng. 2022, 48, 327–345. [Google Scholar] [CrossRef]
  43. Fowler, M. Refactoring; Addison-Wesley Professional: Boston, MA, USA, 2018. [Google Scholar]
  44. Zhang, Z.; Zhang, B.; Xu, W.; Lin, Z. Demystifying Exploitable Bugs in Smart Contracts. In Proceedings of the Demystifying Exploitable Bugs in Smart Contracts. ICSE, Melbourne, Australia, 14–20 May 2023. [Google Scholar]
  45. Kong, Q.P.; Wang, Z.Y.; Huang, Y.; Chen, X.P.; Zhou, X.C.; Zheng, Z.B.; Huang, G. Characterizing and Detecting Gas-Inefficient Patterns in Smart Contracts. J. Comput. Sci. Technol. 2022, 37, 67–82. [Google Scholar] [CrossRef]
  46. OpenZeppelin. Ethernaut. Available online: https://ethernaut.openzeppelin.com/ (accessed on 26 July 2023).
  47. Agarwal, U.; Singh, K.; Verma, R. An Overview of Non-Fungible Tokens (NFT). Int. J. Adv. Res. Sci. Commun. Technol. (IJARSCT) 2022, 2. [Google Scholar] [CrossRef]
  48. Guidi, B.; Michienzi, A. Sleepminting, the brand new frontier of Non Fungible Tokens fraud. In Proceedings of the 2022 ACM Conference on Information Technology for Social Good, Limassol, Cyprus, 7–9 September 2022; pp. 75–81. [Google Scholar]
  49. Guidi, B.; Michienzi, A. From NFT 1.0 to NFT 2.0: A Review of the Evolution of Non-Fungible Tokens. Future Internet 2023, 15, 189. [Google Scholar] [CrossRef]
  50. Malashetti, A.P. Impact of Non-Fungible Token (NFT) on World. Int. J. Res. Eng. Sci. Manag. 2022, 5, 219–221. [Google Scholar]
  51. Olsson, O. A Taxonomy of Non-Fungible Tokens: Overview, Evaluation and Explanation. Master’s Thesis, Department of Informatics and Media, University of Uppsala, 2022. Available online: https://www.diva-portal.org/smash/get/diva2:1672740/FULLTEXT01.pdf (accessed on 18 December 2023).
  52. Tan, Y.; Wu, Z.; Liu, J.; Wu, J.; Zheng, Z.; Chen, T. Bubble or Not: Measurements, Analyses, and Findings on the Ethereum ERC721 and ERC1155 Non-fungible Token Ecosystem. arXiv 2023, arXiv:2301.01991. [Google Scholar]
  53. von Wachter, V.; Jensen, J.R.; Regner, F.; Ross, O. NFT wash trading: Quantifying suspicious behaviour in NFT markets. arXiv 2022, arXiv:2202.03866. [Google Scholar]
  54. Wang, Q.; Li, R.; Wang, Q.; Chen, S. Non-fungible token (NFT): Overview, evaluation, opportunities and challenges. arXiv 2021, arXiv:2105.07447. [Google Scholar]
  55. Azuki. ERC721A. Available online: https://www.azuki.com/erc721a (accessed on 30 July 2023).
  56. Hu, A. ERC721 vs. ERC721A: Batch Minting NFTs. Available online: https://www.alchemy.com/blog/erc721-vs-erc721a-batch-minting-nfts (accessed on 7 July 2023).
  57. Cong, L.W.; Tang, K.; Wang, Y.; Zhao, X. Inclusion and Democratization through Web3 and Defi? Initial Evidence from the Ethereum Ecosystem; National Bureau of Economic Research: Cambridge, MA, USA, 2023. [Google Scholar] [CrossRef]
  58. Wood, G. Ethereum: A secure decentralised generalised transaction ledger. Ethereum Proj. Yellow Pap. 2014, 151, 1–32. [Google Scholar]
  59. Opensea. Available online: https://opensea.io/ (accessed on 8 July 2023).
  60. Akiyoshï, M. Gas Tutorial: How to Set Your Own Gas Prices. Available online: https://medium.com/@maimai816/advanced-metamask-gas-tutorial-how-to-set-your-own-gas-prices-236d59f563b7 (accessed on 6 July 2023).
  61. Di Sorbo, A.; Laudanna, S.; Vacca, A.; Visaggio, C.A.; Canfora, G. Profiling gas consumption in solidity smart contracts. J. Syst. Softw. 2022, 186, 111193. [Google Scholar] [CrossRef]
  62. Blockscount Verified Contracts. Available online: https://eth.blockscout.com/verified-contracts (accessed on 8 July 2023).
  63. Team, A. A Developer’s Guide to Securing Ethereum Smart Contracts. Available online: https://alchemy.com/blog/a-developers-guide-to-securing-ethereum-smart-contracts (accessed on 15 August 2023).
  64. Wang, Z.; Jin, H.; Dai, W.; Choo, K.K.R.; Zou, D. Ethereum smart contract security research: Survey and future research opportunities. Front. Comput. Sci. 2021, 15, 152802. [Google Scholar] [CrossRef]
  65. Brooks, F.; Kugler, H. No Silver Bullet; Addison-Wesley: Reading, MA, USA, 1987. [Google Scholar]
  66. Maslow, A.H. The Psychology of Science: A Reconnaissance; HarperCollins: New York, NY, USA, 1966. [Google Scholar]
  67. Staples, M.; Chen, S.; Falamaki, S.; Ponomarev, A.; Rimba, P.; Tran, A.; Weber, I.; Xu, X.; Zhu, J. Risks and Opportunities for Systems Using Blockchain and Smart Contracts. Data61; CSIRO: Sydney, Australia, 2017. [Google Scholar]
  68. Fröwis, M.; Böhme, R. In code we trust? Measuring the control flow immutability of all smart contracts deployed on Ethereum. In Proceedings of the Data Privacy Management, Cryptocurrencies and Blockchain Technology: ESORICS 2017 International Workshops, DPM 2017 and CBT 2017, Oslo, Norway, 14–15 September 2017; Springer: Berlin/Heidelberg, Germany, 2017; pp. 357–372. [Google Scholar]
  69. OpenZeppelin Documentation. Available online: https://docs.openzeppelin.com/ (accessed on 1 August 2023).
  70. Kaleem, M.; Mavridou, A.; Laszka, A. Vyper: A security comparison with solidity based on common vulnerabilities. In Proceedings of the 2020 2nd Conference on Blockchain Research & Applications for Innovative Networks and Services (BRAINS), Paris, France, 28–30 September 2020; IEEE: Piscataway, NJ, USA, 2020; pp. 107–111. [Google Scholar]
  71. Xu, X.; Pautasso, C.; Zhu, L.; Lu, Q.; Weber, I. A Pattern Collection for Blockchain-Based Applications. In Proceedings of the 23rd European Conference on Pattern Languages of Programs, New York, NY, USA, 4–8 July 2018. [Google Scholar] [CrossRef]
  72. Meisami, S.; Bodell III, W.E. A Comprehensive Survey of Upgradeable Smart Contract Patterns. arXiv 2023, arXiv:2304.03405. [Google Scholar]
  73. Langston, T. 34M Locked in a Smart Contract. Was the Akutars Exploit Avoidable? Available online: https://nftnow.com/features/akutars-exploit-34-million-locked-in-smart-contract/ (accessed on 20 July 2023).
  74. Dannen, C. Introducing Ethereum and Solidity; Springer: Berlin/Heidelberg, Germany, 2017; Volume 1. [Google Scholar]
  75. Vitalik, B.; Yoav, W.; Dror, T.; Shahaf, N.; Alex, F.; Kristof, G.; Tjaden, H. ERC-4337: Account Abstraction Using Alt Mempool. Available online: https://eips.ethereum.org/EIPS/eip-4337 (accessed on 15 December 2023).
  76. Team, A. Introduction to Account Abstraction. Available online: https://docs.alchemy.com/docs/introduction-to-account-abstraction (accessed on 14 December 2023).
  77. Ethereum Foundation Blog. Available online: https://blog.ethereum.org/ (accessed on 17 July 2023).
  78. Team, S. Ask the Solidity Team Anything Nr.1 Recap. Available online: https://blog.soliditylang.org/2020/11/04/solidity-ama-1-recap/#why-do-you-think-people-are-generally-suspicious-of-the-optimizer-and-are-they-right-to-be (accessed on 7 March 2023).
  79. Marchioro, M. Ethereum: How to Save Even More on Gas Price with a Weekly Plan. Available online: https://medium.com/dextf/ethereum-how-to-save-even-more-on-gas-price-with-a-weekly-plan-c6689ac09fe6 (accessed on 7 July 2023).
  80. Go-Ethereum. Available online: https://geth.ethereum.org/ (accessed on 2 August 2023).
  81. Benet, J. Ipfs-content addressed, versioned, p2p file system. arXiv 2014, arXiv:1407.3561. [Google Scholar]
  82. Fravoll. Solidity Patterns. Available online: https://github.com/fravoll/solidity-patterns (accessed on 10 August 2023).
  83. Valverde, J.X. Advanced Gas Optimization Tips for Solidity. Available online: https://coinsbench.com/advanced-gas-optimizations-tips-for-solidity-85c47f413dc5 (accessed on 8 July 2023).
  84. Murray, P.; Welch, N.; Messerman, J. ERC-1167: Minimal Proxy Contract. Available online: https://eips.ethereum.org/EIPS/eip-1167 (accessed on 8 July 2023).
  85. Li, A.; Choi, J.A.; Long, F. Securing smart contract with runtime validation. In Proceedings of the 41st ACM SIGPLAN Conference on Programming Language Design and Implementation, London, UK, 15–20 June 2020; pp. 438–453. [Google Scholar]
  86. Openzeppelin-Contracts. Available online: https://github.com/OpenZeppelin/openzeppelin-contracts (accessed on 1 July 2023).
  87. Manifold Documentation. Available online: https://docs.manifold.xyz/v/manifold-for-developers/ (accessed on 5 August 2023).
  88. Achiando, H. 40 Tips to Optimize Smart Contract Gas Cost. Available online: https://www.linkedin.com/pulse/optimizing-smart-contract-gas-cost-harold-achiando (accessed on 5 August 2023).
  89. An Ethereum Virtual MachineOpcodes Interactive Reference. Available online: https://www.evm.codes/?fork=shanghai (accessed on 5 August 2023).
  90. Di Angelo, M.; Durieux, T.; Ferreira, J.F.; Salzer, G. Evolution of automated weakness detection in Ethereum bytecode: A comprehensive study. arXiv 2023, arXiv:2303.10517. [Google Scholar]
  91. Ivanov, N.; Li, C.; Sun, Z.; Cao, Z.; Luo, X.; Yan, Q. Security Threat Mitigation for Smart Contracts: A Survey. arXiv 2023, arXiv:2302.07347. [Google Scholar] [CrossRef]
  92. Smart Contract Weakness Classification. Available online: https://swcregistry.io/ (accessed on 17 July 2023).
  93. Durieux, T.; Ferreira, J.A.F.; Abreu, R.; Cruz, P. Empirical Review of Automated Analysis Tools on 47,587 Ethereum Smart Contracts. In Proceedings of the ACM/IEEE 42nd International Conference on Software Engineering, New York, NY, USA, 27 June–19 July 2020; pp. 530–541. [Google Scholar] [CrossRef]
  94. Chance. The Gas-Efficient Way of Building and Launching an ERC721 NFT Project for 2022. Available online: https://nftchance.medium.com/the-gas-efficient-way-of-building-and-launching-an-erc721-nft-project-for-2022-b3b1dac5f2e1 (accessed on 2 May 2023).
  95. Nyaletey, E.; Parizi, R.M.; Zhang, Q.; Choo, K.K.R. BlockIPFS–blockchain-enabled interplanetary file system for forensic and trusted data traceability. In Proceedings of the 2019 IEEE International Conference on Blockchain (Blockchain), Seoul, Republic of Korea, 14–17 May 2019; IEEE: Piscataway, NJ, USA, 2019; pp. 18–25. [Google Scholar]
  96. Chen, T.; Li, Z.; Zhou, H.; Chen, J.; Luo, X.; Li, X.; Zhang, X. Towards Saving Money in Using Smart Contracts. In Proceedings of the 40th International Conference on Software Engineering: New Ideas and Emerging Results, New York, NY, USA, 27 May–3 June 2018; pp. 81–84. [Google Scholar] [CrossRef]
  97. Polygon Wiki. Available online: https://wiki.polygon.technology/ (accessed on 18 August 2023).
  98. Aschauer, G.; Sonnleitner, E.; Kurz, M. Cost Efficiency Evaluation of an On-Chain, Decentralized Ride-Sharing Platform. Sustainability 2023, 15, 6230. [Google Scholar] [CrossRef]
  99. Oliveira, L.; Zavolokina, L.; Bauer, I.; Schwabe, G. To token or not to token: Tools for understanding blockchain tokens. Proceedings of International Conference of Information Systems, San Francisco, CA, USA, 13–16 December 2018. [Google Scholar]
  100. Yakovenko, A. Solana: A new architecture for a high performance blockchain (v0.8.13). White Paper. 2018. Available online: https://solana.com/solana-whitepaper.pdf (accessed on 18 December 2023).
Figure 1. Overview of the methodology.
Figure 1. Overview of the methodology.
Electronics 13 00117 g001
Figure 2. The first contract is a contract with a readability focus. The second one focuses on gas efficiency. Constructors and other parts have been omitted to reduce size and to emphasize the main point of this code.
Figure 2. The first contract is a contract with a readability focus. The second one focuses on gas efficiency. Constructors and other parts have been omitted to reduce size and to emphasize the main point of this code.
Electronics 13 00117 g002
Table 1. Results of ERC smart contract deployments with and without the Solidity optimizer in Wei.
Table 1. Results of ERC smart contract deployments with and without the Solidity optimizer in Wei.
Contract TypeDeployment Costs
without Optimizer
in Wei
Deployment Costs
with Optimizer
in Wei
Savings in Percent
ERC-721 Enumerable2,782,2961,501,68946.03
ERC-721A1,685,088960,35443.01
ERC-11552,482,0771,394,60746.81
ERC-721 by Zora 662,983Not modifiable
Table 2. The list of general principles to follow when developing on Ethereum.
Table 2. The list of general principles to follow when developing on Ethereum.
General Principles
NameDescriptionReference
Favour Simplicity and SecuritySimplicity improves security, gas-saving and testing. Complex smart contracts offer more ways to attack and can create undesired behaviour. Finding less complex ways and requiring fewer features is the recommended approach. More compact contracts are smaller and therefore less expensive to deploy and bugs are more easily detected. Clarity should be prioritised over performance, meaning sometimes gas-saving best practices should be neglected for clearness.[11,29,31,32]
Code QualitySimilar software development methodologies should be adopted as are used in aerospace engineering. Code in smart contracts is by default immutable and fixing problems after launching is not trivial. Setting up bug bounties and starting to test in early phases, can help find vulnerabilities. It is not advisable to apply the motto “move fast and break things” [6].[32]
Prepare for FailureNon-trivial smart contracts should be expected to contain bugs and vulnerabilities. Adding a function to pause contracts and including buffers like minimum wait time for execution can help to be able to respond to problems gracefully.[29,30,32]
Adapt the StrategyThe size, functionality and predicted usage of a contract are crucial for determining what to optimize it for. A short-lived contract can be less concerned about gas usage and upgradeability than a library.[28,29]
Table 5. The list of general gas-saving best practices.
Table 5. The list of general gas-saving best practices.
Gas Saving Best Practices
NameDescriptionReference
Solidity OptimizerThe optimizer is recommended to be used with smart contract development. The runs variable can be adapted and it modifies the way the optimizer improves the code. A low number of runs means that the smart contract is optimized for deployment. Choosing a large number results in a less optimized contract for deployment, but lowers the cost of calling functions.[16,94]
Regard the Network StateThe cost of interaction with Ethereum depends heavily on the state of the network. Both urgency and deployment time have an impact on the gas fee. Utilize maxFeePerGas for time uncritical deployments and transactions. This should be done by limiting the maxFeePerGas to an average gas fee below the higher fee of the congested network.[11,60]
Be Mindful of StorageDo not store any data that does not have to be on the blockchain. A popular solution for tokens is to use an IPFS to store additional potentially large data. For example, the metadata is linked with the tokenURI in an ERC-721 project.[32,54,69,95]
Utilize Newer Solidity VersionsNewer Solidity versions do not only bring security updates but can save gas. With Solidity version 0.8.0 an overflow and underflow check was added, making the SafeMath library obsolete on new smart contracts.[11,69]
Learn Peculiarities of SolidityGas costs for operations performed in Solidity can be reduced by small changes. Be wary of how storage and its read and write operations work on Ethereum. The changes can be small, but compound when used by many network participants. These changes should never, without a good reason, reduce readability or the security of the code.[32,34,45,94,96]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

MDPI and ACS Style

Baldauf, M.; Sonnleitner, E.; Kurz, M. Exemplary Ethereum Development Strategies Regarding Security and Gas-Saving. Electronics 2024, 13, 117. https://doi.org/10.3390/electronics13010117

AMA Style

Baldauf M, Sonnleitner E, Kurz M. Exemplary Ethereum Development Strategies Regarding Security and Gas-Saving. Electronics. 2024; 13(1):117. https://doi.org/10.3390/electronics13010117

Chicago/Turabian Style

Baldauf, Manfred, Erik Sonnleitner, and Marc Kurz. 2024. "Exemplary Ethereum Development Strategies Regarding Security and Gas-Saving" Electronics 13, no. 1: 117. https://doi.org/10.3390/electronics13010117

Note that from the first issue of 2016, this journal uses article numbers instead of page numbers. See further details here.

Article Metrics

Back to TopTop