Logo
linkedinStart Free Trial

Gas optimizations in Smart Contracts | How to deal with Gas Wars?

4 min read • October 3, 2022

Article image

Share article

linkedinXFacebookInstagram

Introduction

 

On-chain smart contracts are programs that are saved. The Ethereum Virtual Machine (EVM) is the Ethereum blockchain's execution environment. The Ethereum Virtual Machine (EVM) is in charge of executing smart contracts on the Ethereum blockchain. The execution process is constrained to a set number of computational steps to avoid program execution that may contain infinite loops. The EVM is a quasi–Turing-complete state machine because of this constraint of computational steps. 

 

Without this restriction, Ethereum nodes could become stuck when executing Turing complete programs that never end. The EVM has a gas mechanism built in to help with this constraint of computing steps. The amount of computational effort required to perform various operations on the Ethereum network is measured in gas.

 

Users change the status of the Ethereum blockchain by executing transactions from externally controlled wallets. A basic value transfer costs a fixed amount of gas, whereas a smart contract cost gas according to the computing effort. A poorly drafted smart contract consumes a lot of gas, and the cost burden is shared by all smart contract users. As a result, it's critical to build smart contracts that use the least amount of gas to execute. This article discusses Solidity smart contract optimization ideas and strategies.

 

Costs of EVM storage and gas

The Ethereum Virtual Machine (EVM) is a small virtual machine that runs smart contracts recorded on the Ethereum blockchain.

 

EVM is capable of dealing with three main types of storage:

It's a read-only stack-based data location called call data. Call data is a non-modifiable, non-persistent region that stores function arguments and functions similarly to memory. The parameters for the function call are stored in this location.

 

The memory is volatile, and it is reset when the function is completed. This is a byte array that is created at runtime. This array's slots can each hold 32 bytes of data. The cost of gas for writing to memory is less than the cost of gas for writing to storage. It also has a cost of growth, which means that writing to previously unused memory costs gas. For the first 724 bytes, the cost grows linearly, then quadratically after that.

 

Persistent storage is what this is. The storage is divided into 2256 pieces, each of which is 32 bytes long. The storage is significantly underutilized. Understanding the storage implementation can be illustrated by a mapping of 32byte keys to 32byte values. The cost of changing values within storage is the highest.

 

It is also possible to change the data location while the program is running. When data is assigned to different data locations, an independent copy of the data is created. Assignments between the same data places, on the other hand, simply produce references.

 

One of the most expensive operations done by the EVM is writing to persistent storage (SSTORE). A write for an EVM storage slot costs $20,000 for the first time. It costs 5000 to write to an established storage place again. A contract can have as many storage assignments (SSTORE invocation) as it wants, and these assignments might drive up gas prices. Understanding how EVM stores different data types in the storage can help you grasp the SSTORE opcode.

 

Mappings

Inside the storage, mappings are key-value pairs that are sparsely stored. In a Solidity contract, there could be several mappings. Data could be stored on two distinct mappings using the same key. As a result, the key that is used to actually store the value is produced by combining the hash of the contract's key with the slot position.

 

The variables (a and b) are crammed into the first slot available. The reason for this is because variables a and b are both 16-byte variables. Solidity tries to group storage variables together and move them in 32-byte chunks, as previously described. The compiler groups these variables together in the first slot because of this packing characteristic. The third variable is inserted within the next available slot because the first storage slot is filled and contains 32bytes of data (16 bytes of a and 16 bytes of b). This is referred to as storage packing. It's significant since it reduces the number of SSTORE commands and lowers gas expenses.

 

It's crucial to understand how the compiler generates assembly programs if you want to save money on storage. JUMP opcodes are used by the stack machine to jump to a certain address and resume execution. Opcodes like JUMP and JUMPI in EVM require exact addresses that can change quickly. As a result, the inline assembly would include labels/tags to facilitate the use of jumps. There are certain limits to the solidity optimizer that may be removed in the future. The optimizer can only optimize within each tag, not between them. In most cases, different function calls result in separate tags in the assembly code. As a result, if the code has distinct routines to update the store, the number of SSTORE calls may rise.

 

We hope that this blog post will be beneficial for you. We will continue to create useful works in order to get inspired by everyone. We are sure that we will achieve splendid things altogether. Keep on following Finage for the best and more.  


You can get your Real-Time and Historical Cryptocurrency Data with a Finage free Crypto Data API key.

Build with us today!

Start Free Trial

Share article

linkedinXFacebookInstagram

Claim Your Free API Key Today

Access stock, forex and crypto market data with a free API key—no credit card required.

Logo Pattern Desktop

Stay Informed, Stay Ahead

Finage Blog: Data-Driven Insights & Ideas

Discover company news, announcements, updates, guides and more

Finage Logo
TwitterLinkedInInstagramGitHubYouTubeEmail
Finage is a financial market data and software provider. We do not offer financial or investment advice, manage customer funds, or facilitate trading or financial transactions. Please note that all data provided under Finage and on this website, including the prices displayed on the ticker and charts pages, are not necessarily real-time or accurate. They are strictly intended for informational purposes and should not be relied upon for investing or trading decisions. Redistribution of the information displayed on or provided by Finage is strictly prohibited. Please be aware that the data types offered are not sourced directly or indirectly from any exchanges, but rather from over-the-counter, peer-to-peer, and market makers. Therefore, the prices may not be accurate and could differ from the actual market prices. We want to emphasize that we are not liable for any trading or investing losses that you may incur. By using the data, charts, or any related information, you accept all responsibility for any risks involved. Finage will not accept any liability for losses or damages arising from the use of our data or related services. By accessing our website or using our services, all users/visitors are deemed to have accepted these conditions.
Finage LTD 2025 © Copyright