Gas Optimization In Solidity: Strategies For Cost-Effective Smart Contracts
Gas is the “fuel” that powers smart contract execution. This article offers practical strategies for Solidity gas optimization.
🇺🇦 Hacken stands with Ukraine!Learn more
Blockchain networks face a scalability trilemma where they cannot have everything all at once: robust security, genuine decentralization, and high throughput. However, layer 2 projects are the most promising solutions to higher blockchain scalability.
It’s easy to agree with Vitalik Buterin’s perspective that layer 2 blockchains are becoming increasingly diverse, with ZK-rollups appearing as a separate technology stack, alongside optimistic rollups, optimum, validium, and plasma. In this article, we focus on ZK-rollups – layer 2 rollups utilizing zero-knowledge proofs (ZK-proofs or ZKP).
ZK-rollup is a layer 2 scaling solution that helps process transactions faster by handling them off the main blockchain (off-chain) but still records the transaction data on the main blockchain (on-chain). It uses ZK-proofs to ensure that these transactions are valid without revealing any private information.
Currently, there are 11 active ZK-rollups with over $1 billion in total value locked, and the most popular implementations are zkSync, dYdX, and Starknet.
The most distinctive features of ZK-rollups are validity proofs and on-chain data availability.
Validity Proofs: These are checks done by zero-knowledge proofs, a kind of cryptographic proof that can confirm the result of a calculation quickly and without revealing certain details of that calculation. There are various types of these proofs, including zk-SNARKs and zk-STARKs, which have their own unique properties.
On-Chain Data Availability: While the actual transactions are processed off the main blockchain, ZK-rollups ensure some important pieces of data are stored on the main (layer 1) blockchain. This storage is key to the consensus mechanism and makes ZK-rollups general-purpose. With this setup, anyone can independently verify all the transactions in a rollup, and it’s even compatible with Ethereum’s Virtual Machine, allowing it to support a wide range of applications.
Off-Chain Computation, Reduced Gas & Data Compression. Unlike plasma and validiums, rollups (both ZK and optimistic) don’t fully implement layer 2 scaling. In particular, rollups don’t provide 100% off-chain data storage. Instead, they only move state storage and computation off-chain. Hence, the rollup solution has a hard cap on scalability: it’s limited by the data bandwidth of the underlying blockchain.
Despite this, rollups still offer a monumental leap forward compared to the base layer. For example, ERC20 token approval on Ethereum costs 45,000 gas, whereas most rollups take less than 300 gas for the same operation. In addition, a rollup compresses transaction data. A typical ETH transfer takes around 110 bytes, compared to 12 bytes in a rollup. Here, the signature compression provides the largest reduction in size. On Ethereum, a signature takes 68 bytes. By contrast, a rollup can batch ~100 transactions under a single signature, reducing the size to 0.5 bytes.
Enhanced Security. A crucial feature of ZK-rollups is a security guarantee that the user can always bring the asset back to layer 1. This is important because other layer 2 solutions don’t offer that guarantee. For example, validiums can lose assets in case of a data availability failure. ZK-rollups won’t face any data availability problems, meaning attackers cannot cause extensive damage. Moreover, data availability removes the need to map assets to owners, which is a great advantage of rollups over other L2 solutions.
At their core, ZK-rollups work through a smart contract on the layer 1 blockchain. This smart contract is crucial as it maintains an authoritative record known as the state root.
State Root: The state root is a Merkle tree of batches of information about the rollup’s accounts, balances, and contract code. Users, like the sequencer, publish new batches (a compressed collection of transactions) along with the old and new state roots (pre- and post-state roots). The smart contract then checks the old state root against the current root. If they match, it switches the current version to the new state root.
Deposits & Withdrawals: Naturally, rollups have to allow inputs and outputs from the “outside” to enable withdrawals and deposits. The transaction that submits the batch containing “outside” inputs also moves assets to the smart contract. When the transaction submits the batch containing “outside” outputs, the contract initiates the withdrawal process. Hence, the underlying smart contract synchronizes state changes across the base-layer and the rollup.
Post-State Verification: How to verify the correctness of the post-state root? Up until now, a malicious actor would have been able to submit any version of the state root (e.g., where they transfer all assets to their account). However, rollups have addressed this issue in two different ways: validity proofs and fraud proofs. Hence, we have two schemes: zero-knowledge and optimistic rollups.
Validity Proofs: ZK-rollups rely on validity proofs to ensure the post-state root contains no manipulations. For that reason, every new batch of transactions comes with a zk-SNARK (or zk-STARK) – an argument of knowledge that proves the batch computation indeed produces the same result as the new state root. And the most important part: even the heaviest computations can be verified quickly on-chain thanks to the highly complex math behind ZK-proofs.
Verification-Only Data: ZK rollups eliminate the need to store verification-only data on-chain due to zk-SNARKs, unlike optimistic rollups, which require it for fraud checks.
In ZK-rollups, data that’s only relevant for verification does not need to be stored on-chain because the ZK-proof implicitly confirms that any necessary verification data was provided. In contrast, fraud proofs used in optimistic rollups validate transactions post-factum and require more information. Hence, optimistic rollups store all data relevant for verification on-chain, regardless of the dispute status.
Privacy Preserving: ZK-rollups store more transaction details off-chain, which makes them better suited for preserving privacy. In a privacy-preserving withdrawal scenario, an optimistic rollup requires a total of 296 bytes per transaction, combining various elements like the root index, nullifier, recipient information, and a ZK-SNARK proof. This results in a 77x efficiency increase (compared to L1). On the other hand, a ZK rollup needs only 40 bytes per transaction since it doesn’t require the zk-SNARK proof on-chain, leading to a 570x increase in efficiency (compared to L1). Both methods are based on a comparable number of transactions (~380,000). Moreover, the gas cost per on-chain transaction is lower for ZK-rollups.
Gas Cost Per Batch: Compared to fraud proofs, verifying zk-SNARKs with every batch is costly. ZK-SNARK technology is generally way more complicated and harder for generalizability. Hence, optimistic rollups are cheaper per batch: 40,000 gas vs 500,000 gas.
Withdrawal Time: Optimistic rollups delay withdrawals to give enough time (e.g., 7 days) for dispute resolutions. By contrast, ZK-rollups allow for instantaneous withdrawal.
Application & Real-World Use: Optimistic rollups are more widespread mostly because they are better suited for general-purpose EVM computation. The total value locked in optimistic rollups is over $10 billion, which is ten times greater than the TVL in ZK-rollups.
Traditionally, ZK-rollups have been better suited for simple computations, exchange, and application-specific uses. But the latest advances in SNARKs have given rise to universal ZK-rollups too.
|Max TPS||Addressed Risks|
|dYdX||Exchange||1||$378M||9d or 2d delay||11.45||4.5/5|
|Loopring||Tokens, NFTs, AMM||0||$96.43M||Yes||1.48||4/5|
|Polygon zkEVM||Universal||0||$72.85M||10d or no delay||1.41||3.5/5|
|zkSync Lite||Payment, Tokens||1||$72.02M||21d or no delay||3.29||4.5/5|
|ZKSpace||Tokens, NFTs, AMM||0||$22.26M||8d delay||n/a||4.5/5|
Currently, there are a dozen active ZK-rollups with a total value locked of $1.3 billion. Most of those projects are in the early stages, under “full training wheels” (i.e., run by operators).
Among projects, the clear winners regarding TPS capacity are zkSync Era, dYdX, and Starknet. These networks all have more than $100M in TVL and process around 10M monthly transactions. Most rollups employ zk-SNARKs; the only exceptions are Starknet and dYdX, which both use zk-STARKs.
|Off-chain computation with on-chain data availability||Computational overhead|
|Security guarantee of bringing assets back to L1||Less suited for general-purpose computations|
|10x transaction data compression||Lower EVM compatibility|
|Lower gas costs per on-chain transaction & privacy preserving withdrawals||Complexity of ZK-proofs|
To sum up, ZK-rollups is a layer 2 scaling solution that uses validity proofs for off-chain computation and stores a small amount of transaction data on the chain.
The complexity of SNARK-proving and on-chain data availability are the main costs of ZK-rollups operations, making them less attractive for a general-purpose EVM. For that reason, optimistic rollups take the lead in terms of market adoption. On top of that, even the most popular ZK-rollup projects – zkSync Era, Starknet, and Loopring – are only in the early stages of development and don’t run autonomously.
However, the future of ZK-rollups is very bright. Advancements in the complex zero-knowledge technology will make ZK-rollups more compatible for EVM and universal applications. The privacy-preserving feature, coupled with instantaneous withdrawals and lower per on-chain transaction costs, make ZK-rollups a perfect option for layer 2 scaling.