### 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 moreIn the evolving blockchain landscape, zero knowledge proofs have emerged as the most powerful cryptographic technology allowing more privacy and scalability. Also known as arguments of knowledge, they generate proof that some computation has a particular output while verifying that proof very quickly. The zero knowledge (ZK) part is an additional privacy bonus that keeps some inputs of the computation hidden.

ZK-SNARK is the first and most popular implementation of this cryptographic technology, but modern ZK-EVMs also employ zk-STARK for better efficiency. In this article, we’ll review and compare these two ZK-protocols – **zk-SNARKs vs. zk-STARKs** – shedding light on how they tackle blockchain’s scalability trilemma.

Zero-knowledge protocol, a method that uses ZK-proofs, allows one party to quickly prove that a computation has a particular output without revealing specific inputs to that computation. The secret information to be proved and validated is called a witness.

Sometimes, complex concepts are better understood with simpler, everyday analogies:

Imagine you’re a baker claiming you know a secret ingredient that produces a unique gold crust when added to a basic bread recipe and baked 100 times in a special oven. Instead of making someone bake it 100 times to verify, you provide a quick method to confirm the crust without revealing the secret ingredient. Like the baker’s method, the proof confirms the statement about the secret number without revealing it or undergoing a lengthy process.

In the realm of blockchain, consider the process akin to mining a block:

Imagine a miner claiming, “I have found a nonce that, when appended to a specific block’s header and hashed through SHA256, produces a hash value starting with a certain number of zeros.” Instead of having every participant in the network compute the hash to confirm its validity, which would be immensely time-consuming and energy-draining, the miner provides a succinct proof. This proof allows anyone to rapidly validate the claim without redoing the extensive hashing or discerning the exact nonce used.

Just like in the original scenario, the core idea is verifying a statement quickly without unveiling the specific secrets or redoing all the work.

ZK-proofs are powered by some really clever but very complex math, which we will only outline here. Consider a massive computation where we encode something with an input number and hash it one million times. A “succinct” proof aims to verify a certain output will come out of the computation without mirroring every step. Instead of checking each computation piece, a verifier, through random sampling, examines only a small share of the total parts. If these checks pass, it’s assumed that the entire computation is likely correct.

ZK-proofs bring two crucial benefits:

**Scalability**: For a block that takes ages to verify, only one person can do the computation and produce proofs, like zk-SNARs or zk-STARKs. Other network participants only have to verify the proof.**Privacy**: Leveraging ZK to conceal computation inputs enables parties to transact with enhanced privacy, preventing the disclosure of extraneous information to the public. For instance, you can validate having sufficient ETH in your balance to purchase without exposing the original sender of the cryptocurrency.

Owing to these powerful advantages, cryptographic tools like zk-SNARKs and zk-STARs are ideal for layer 2 scalability – reliably confirming off-chain transitions without re-execution on the main network.

Both zk-SNARKs and zk-STARKs refer to the same cryptographic technology of validating proofs in a really efficient and private way. However, these two tools are different in their implementation. SNARKs produce succinct and non-interactive proofs, while STARKs produce scalable and transparent ones. We’ll cover the difference next.

ZK-SNARKs, or “Zero Knowledge Succinct Non-Interactive Argument of Knowledge,” are cryptographic proofs that allow one to validate the claim without repeating lengthy computations and keeping some inputs private.

The **Succinct** part ensures that the verification process doesn’t take as much time as the computation. Otherwise, the verifiers would compute the output themselves. You can achieve this with *random sampling*, but the process will be fragile: a random check would never spot a deliberately inserted error. The answer to the problem is **polynomial commitments, **and the three main ways they’re implemented are **FRI**, **bulletproofs**, and **Kate**. We won’t go into details because it’s really heavy in the math department, but you can read Buterin’s article.

An important feature of SNARKs is the **Non-Interactive** part, where there’s no need for constant interaction between the prover and verifier. Interactive proving requires both parties, which limits its power. Any generated proof couldn’t be independently verified without initiating a new conversation between the prover and verifier, which is not cost-effective.

With a shared key (a.k.a public parameters) between the prover and verifier, these proofs allowed the prover to establish knowledge of certain data without actually revealing it. Non-interactive proofs streamlined the process, necessitating just one round of communication. The prover inputs the secret data into an algorithm to generate a zero-knowledge proof, which the verifier then checks using another algorithm. Once established, this proof can be verified by anyone with a shared key.

The shared key used for non-interactive proofing, known as the **Common Reference String (CRS)**, is crucial for the protocol’s security. Any compromise in CRS can enable dishonest provers to fabricate false proofs. **Multi-party computation (MPC)** is utilized to counteract these threats, with multiple participants contributing random values during a trusted setup ceremony.

The zk-SNARK protocol’s integrity relies heavily on this trusted setup phase. Any missteps can threaten the security of all circuits of the ZK-EVM. Given its importance, we recommend undergoing a blockchain protocol audit to ensure the setup is executed correctly.

The first real use case of zk-SNARK in Web3 is Z.cash – a cryptocurrency that utilizes ZK-proofs for enhanced transaction privacy. Before its launch in 2016, zk-SNARK was just academic research.

Z.cash has contributed to the widespread use of this concept in ZK-rollups to enhance scalability. ZK-SNARKs have been applied in layer 2 protocols known as ZK-rollups to enhance scalability. Popular ZK-rollups include Loopring, zkSync, ZKSpace, Aztec, etc.

ZK-STARKs, or “Zero Knowledge Scalable Transparent Argument of Knowledge,” are a specific type of zk-SNARKs. STARK protocols are ideal when working with witnesses of large size. They also provide higher transparency.

ZK-STARKs have higher verification overhead than zk-SNARK, but they are way more cost-effective when working with big witnesses. In other words, STARK is a great solution when you need **scale**.

Another important feature of the STARK protocol is no need for a trusted setup because it uses publicly verifiable randomness to generate public parameters. Hence, it’s considered more transparent for situations where the credibility of the CRS process is unknown.

Like zkSNARKs, zkSTARKs are used for generating validity proofs to confirm the integrity of all the computations and transactions for ZK-Rollups. The pioneer project in zk-STARKs is Starkware. The company has developed its ZK-friendly language Cairo and the Starknet layer 2.

ZK-SNARK | ZK-STARK | |

Proof Size | Low. Allow for EVM data availability | High. Driving the costs up |

Trust Setup | Requires a trusted setup | Does not require a trusted setup |

Verification Time | Fast verification times | Faster times only with large datasets |

Quantum Security | Not quantum-resistant | Quantum-resistant |

Transparency | Less transparent due to trusted setup | More transparent using public verifiable randomness |

Scalability | Less scalable, linear increase | Highly scalable |

Use Cases | Best for systems where proof size and speed are key | Best where transparency and quantum-resistance are priorities |

**Data Availability**: The largest advantage of zk-SNARK over zk-STARK is data availability, which explains why they are more popular, especially in L1 rollups.**Security:**ZK-SNARKs require a trusted setup involving the creation of a Common Reference String (CRS). If malicious actors access this setup data, they could produce false proofs. One potential solution is an MPC ceremony that relies on honest participants. Conversely, zk-STARKs don’t rely on such setups, making them quantum-resistant and less susceptible to potential threats.**Transparency:**ZK-SNARK’s trusted setup might be perceived as less transparent due to its reliance on a CRS and the need for trust in participants to act honestly. In contrast, zk-STARKs are innately more transparent, depending on public randomness to establish parameters, which ensures open and trustless verification.**Scalability:**Both cryptographic methods offer scalability for blockchains. ZK-SNARKs scale*linearly*with the size of the underlying computation, while zk-STARKs, although having larger proof sizes, are better suited for larger computations. Their proving and verification times increase quasilinearly, which can make them faster than zk-SNARKs for extensive datasets.**Use Cases:**ZK-SNARKs are commonly used in privacy coins, identity verification, and decentralized finance (DeFi), benefiting from their compact proof sizes and consistent verification times. Meanwhile, zk-STARKs, due to their transparency and scalability benefits, are prominently utilized in Layer-2 solutions.

A critical and emerging transition in the block validation process is the rise of ZK-EVMs.

ZK-EVM enables EVM (Ethereum Virtual Machine) execution for layer 2 protocols known as ZK-rollups. Some of these rollups are already in progress: ZK-EVM Community Solution, Polygon zkEVM, ZKSync Era, Scroll’s ZK-EVM, and others.

There are generally four types of ZK-EVM depending on the level of compatibility and equivalency with EVM. For example, Ty[e 1 ZK-EVM permits a 1:1 EVM compatibility: smart contracts written for Ethereum can be deployed *as it is* on ZK-EVM-based layer 2. So, Solidity can be used instead of dedicated languages for ZK-proofs like Circom and Cairo.

Here, it’s important to mention that modern ZK-EVMs employ both SNARK and STARK for higher efficiency. Another caveat is that “zero knowledge” is not used in existing ZK-Rollups, only succinctness (computation compression).

- High data availability but linear scalability.
- Possibility of a non-interactive computation.
- The security of zk-SNARKs hinges on the CRS setup. An error here would affect all circuits and allow false proof generation.
- ZK-SNARKs are preferred for their compact proof sizes and consistent verification time, making them cost-effective for L1 verification in ZK-rollups.

- No need for the initial trusted setup.
- Very salable. Especially when handling extensive data, as their proving and verification times increase slower than zk-SNARKs.
- Larger proof sizes result in higher verification costs.
- ZK-STARKs are resistant to quantum computing threats.

ZK-SNARKs and ZK-STARKs are groundbreaking cryptographic tools that can revolutionize how we view scalability and privacy in blockchain systems. Many believe that ZK-STARKs is an improvement from zk-SNARKs because of its quantum-resistance, scalability, and transparency. Yet, the current downside with STARKs is larger proof sizes and higher costs. Hence, SNARKs won’t go anywhere anytime soon.

As research progresses, it’s clear that both will continue to play pivotal roles in shaping the future of decentralized systems and ensuring cheap, swift, and private transactions.

Ben-Sasson, E., Bentov, I., Horesh, Y., & Riabzev, M. (2018). “Scalable, transparent, and post-quantum secure computational integrity.” https://eprint.iacr.org/2018/046

Buterin, V. (2022). “Some ways to use ZK-SNARKs for privacy.” https://vitalik.ca/general/2022/06/15/using_snarks.html

Buterin, V. (2021). “An approximate introduction to how ZK-SNARKs are possible.” https://vitalik.ca/general/2021/01/26/snarks.html

Chen, T., Hui Lu, H., Kunpittaya, T., & Luo, A. (2022). “A Review of ZK-SNARKs.” https://arxiv.org/abs/2202.06877

Ethereum.org (2023). “Zero Knowledge Rollups.” https://ethereum.org/en/developers/docs/scaling/zk-rollups/