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
The Ethereum network, despite its vast capabilities, faces significant scalability challenges, notably high gas fees. Optimism, a Layer 2 solution, emerges as a promising response to these issues, having already helped save $3.83 billion in gas fees by processing transactions as calldata on the mainnet.
In this guide, we’re going to delve into the mechanics and key features of Optimism, shedding light on how this groundbreaking solution is stepping up the game toward a more scalable Ethereum network.
Optimism is a layer-2 scaling solution for the Ethereum blockchain built from the ground up by the three former Ethereum developers—Kevin Ho, Mark Tyneway, and Karl Floersch—in 2019.
The blockchain launched into mainnet in December 2021. The team’s aim was straightforward: to fix Ethereum’s problems and make different chains work better together.
Optimism is based on four ideas: simplicity, practicality, long-term thinking, and positivity. Because of these principles, they used an optimistic rollup method to make Ethereum faster.
In a typical optimistic rollup, the L2 processes transactions off-chain and sends them to the L1 as calldata. This scaling method is called optimistic because it assumes all transactions processed off-chain are valid until there is convincing proof of error or manipulation.
Did Optimism succeed in this goal? Let the figures speak for themselves.
A major infrastructure at the core of Optimism is called the Sequencer. It helps in the overall coordination of the network. The sequencer has these important duties:
At the moment, the Optimism Labs is behind the only sequencer — which is not decentralized enough. The long-term plan of the network is to have everyone participate as block producers.
According to the roadmap, there will still be one sequencer, but the network will run a poly-sequencer model when it is ready for it.
Optimism rolls transactions—better called “deposits”—back to the Ethereum mainnet without any valid proof, as the transactions are assumed to be valid.
But this assumption can be questioned within seven days since the state commitment was made. This seven-day period is commonly called the Challenge Window.
If there is an objection to the validity of a state commitment, it will be examined through the Fault Proof scheme, formerly called the Fraud Proof scheme.
As of the time of writing, Fault Proof is halted due to a need for an upgrade. You can follow the current developments of Fault Proof here.
During the challenge window, a challenger can leverage Ethereum’s data availability and the sequencer’s Merkle root to point out errors or manipulations.
Optimism underwent several audits. However, the team warns people to use Optimism at their own risk because audits are not a 100% guarantee that a protocol is bug-free. Nonetheless, the protocol encourages whitehats to find bugs in a codebase in exchange for a $2 million bounty.
Apart from smart contract security issues, the Optimism team is working on completely decentralizing its protocol upgrades. Currently, the Optimism team is behind the fast upgrade keys, which can be used for every necessary quick improvement in the protocol.
The team plans to adopt multi-client architecture and ZK for a more secure and decentralized upgrade mechanism. Once that is achieved, the fast upgrade keys will be disposed of, and everything will be totally decentralized.
The most obvious distinction between optimistic and ZK rollups is their order of proving transactional validity. Optimistic rollups assume transactions are valid so far and unchallenged, but ZK rollups verify transactional validity with cryptography before committing them to the Ethereum mainnet.
The second difference stems from the first one — variations in withdrawal time. Optimistic rollups have to wait for the Challenge Window to finish before fully committing transactions back to Ethereum.
This often makes their users wait for days before they can withdraw unless they use a third-party bridge. But that is not the case with ZK rollups because they verify fast. In addition, ZK rollups utilize zero-knowledge proofs, while optimistic rollups leverage fault proofs.
|Optimistic Rollups||ZK Rollups|
|Assumes transactional validity||Verifies transactional validity|
|Longer withdrawal time||Shorter withdrawal time|
|Uses fault proofs||Uses zero-knowledge proofs|
Optimism is working towards an end goal of modular architecture, so other rollups and blockchains can leverage the OP Stack to build on Ethereum. Apart from modularity, Optimism has identified several technical bottlenecks it has and how to fix them.
✅OP Mainnet’s migration to Bedrock has concluded and the Bedrock sequencer has started up.— Optimism (✨?_?✨) (@optimismFND) June 6, 2023
Key external OP Mainnet infrastructure is starting to come back online. You can track infrastructure status here:https://t.co/XTtaArdI03
The way forward is to carry out what is called the Bedrock Upgrade. Optimism Labs concluded this upgrade on the 6th of June, 2023. Here are some Improvements that the hard fork introduces.
Data Compression. An object-oriented design can help Optimism enhance the performance of its nodes. The blockchain plans to arrange the bulk L2 transactions into channels to compress the data.
10% Reduction in Fees. Due to the compression mentioned above, Bedrock will wipe off execution gas from Ethereum, taking away about 10% of the fees.
Faster Deposit Time. It takes about 10 minutes for deposits to get confirmed on the legacy network and previous protocol versions. But the Bedrock Upgrade aims to reduce this to only 3 minutes. Optimism plans to ensure this by catering to cases of re-org within the nodes.
Two Withdrawal Checks. Transfer of assets from an L2 to an L1 is termed withdrawal within the Optimism ecosystem. But lack or inefficiency of validation checks for withdrawal can be a bug. This was the case with the Binance Smart Chain when hackers stole $100 million. Therefore, the Bedrock Upgrade is introducing a more secure withdrawal system on Optimism.
Optimized Node Performance. Previous versions of Optimism nodes handle one transaction per block, but Bedrock will allow the nodes to handle transactions in one single rollup block. The nodes will also be able to query transaction data from Ethereum seamlessly.
Optimism is not a layer-1 blockchain; instead, it helps in scaling layer-1 — particularly Ethereum. Recall that some of the founding team members are ex-Ethereum developers. Thus, the main feature of the blockchain is to provide a better user and developer experience for the Ethereum ecosystem. Unlike other scaling solutions, Optimism believes more in the optimistic rollup model and is using it to improve Ethereum.
Since Optimism is on track to scaling Ethereum, it was designed to work with the Ethereum Virtual Machine. Developers can deploy Optimism with Ethereum languages such as Vyper and Solidity. They can also use popular frameworks such as Foundry or Hardhat.
The speed of confirmation is different for different uses. Deposits from Ethereum to Optimism take about 15 minutes before it comes through. But it takes less time on the testnets.
But it is a different case when assets are transferred from Optimism to Ethereum. Due to the fault-proof model, it might take seven days—when the Challenger Window would have elapsed—before the block will be confirmed if the user uses the Optimism Bridge.
There are two forms of fees on Optimism: L1 execution fee and L2 security fee. But Optimism abstracts and makes these fees ridiculously low because it returns transactions to Ethereum as calldata.
Among all the storage methods in Solidity—memory, storage, and calldata—calldata is not stored in the Ethereum state. So it is extremely cheap because it occupies no space within the EVM. So far, Optimism claims to have saved people from paying over $3 billion in gas fees.
The Optimism Collective is focused on funding and supporting public goods. This ecosystem has three constituencies: token holders, builders, and users.
The Collective rewards public goods in retrospect rather than in advance. They believe judging what suffices as a public good is easier if it is already in operation. In addition, the Optimism community is working on the profitization of public goods.
Most protocols and projects are at their best, operating across multiple chains. But Optimism is introducing a more excellent architecture called the Superchain.
The Optimism mainnet can be bound to form a singular chain entirely with any other blockchain. This is envisioned to take the idea of interoperability to the next level. However, the Superchain is not yet here; still a work in progress.
Optimism and Arbitrum are one of the leading L2. Even though their natures are similar, they are different in some grounds.
Virtual Machine Difference. Optimism only works with the Ethereum Virtual Machine, but Arbitrum works with both Ethereum Virtual Machine and Arbitrum Virtual Machine.
Fault Proof Round. Optimism solves transactional irregularities within a single fault-proof session, but Arbitrum permits several sessions.
|Single fault-proof session||Multiple fault proof session|
|EVM & AVM||EVM only|
Launched in May 2022, the $OP token is the native and governance token of the Optimism blockchain. The Collective adopts a democratic system for its administration, and the community members vote with the OP token to reach a consensus.
Token House. The Token House is the governance arm of the Collective. The OP holders can use the token to submit and vote on proposals on protocol upgrades, treasury, grants, and so on.
Common House. This arm is geared towards determining what suffices as a public good. Thus, the OP token holders vote on various retrospective public goods that should be funded.
There is a maximum supply of 4,294,967,296 OP tokens, all of which are in circulation, according to Coingecko. OP has over $867 million in market capitalization as of the time of writing.
Most projects are trooping to Optimism because of their use cases.
DeFi. Optimism currently has about 140 DeFi projects and protocols building on it. Due to its EVM compatibility, Ethereum-native DeFi protocols such as Curve, Aave, and Perpetual are all deployed on Optimism.
Some other protocols, such as Arcadia Finance, were built primarily on Optimism. In addition, Optimism also supports some prominent bridges, including Wormhole, Across, and Stargate.
NFT. There are over 40 NFT platforms and projects deployed on the Optimism mainnet. The blockchain also hosts unique NFT protocols, such as Backed, where NFTs are borrowed and loaned.
DAO. As a blockchain that is geared towards fostering the interaction of people towards common goals, Optimism hosts about 12 solid DAOs as of June 6th, 2023. Layer2DAO is an example of a thriving DAO on Optimism. The DAO contributes funds to invest in promising layer-2 projects.
On-Ramp Solution. Optimism has partnered with FinTechs and crypto exchanges so their users can easily buy crypto on Optimism with their fiat currencies such as dollars. The on-ramp solution supports payment with a credit card, bank transfer, Apple Pay Transak, Moonpay, Binance, or any of the other 17 onboarded platforms.
Tooling dApps. Tools are important for any blockchain’s technical and non-technical users, and Optimism is no different. Optimism has various tools that help everyone in the ecosystem.
On the non-technical side, there are protocols such as NiftyKit, a no-code platform for creators to launch their NFT projects on Optimism. On the technical side are dApps such as Pyth Network, Safe, and Cookbook.
Optimism is compatible with the EVM; Ethereum developers can build with their current stack and framework.
First step. Add Optimism Goerli to your Metamask. Input these details:
Second step. Get some faucets from here.
Third step. Switch your environment to “Injected Web3” on Remix. Upon deployment, Remix will trigger your Optimism Goerli wallet and use the faucets there for deployment. You can check the testnet explorer URL above to see your contract address.
As discussed so far, Optimism, a blockchain platform for developers, has the potential to scale Ethereum beyond its current level. With time, more innovative projects and dApps will likely be deployed on it.
If you’re building your project on Optimism, be sure to get your Optimism smart contract audited by a trusted third party like Hacken. When security is sure, business thrives.
Optimism is a layer-2 blockchain that uses the optimistic rollup model to scale Ethereum.
The major downside of Optimism is its longer withdrawal period of 7 days from Optimism to Ethereum.
Arbitrum is relatively better than Optimism because most of its infrastructure is running already, unlike Optimism, which is still undergoing many upgrades—such as Bedrock—and yet-to-be-created infrastructure, such as Superchain.