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
In the evolving Web3 era, the critical role of smart contracts in powering decentralized applications and ecosystems cannot be overstated. As these systems expand in complexity and scale, the risk of errors multiplies correspondingly. For Web3 developers aiming for seamless, error-free operations, smart contract audits are not merely an option, but a necessity.
In this article, we take you through the tried-and-tested audit process at Hacken, a methodology that we’ve continually fine-tuned since our first audit in 2017. Notably, this approach has helped us maintain a track record of zero exploits among all the projects we audited in 2022, underscoring the reliability and effectiveness of our methods.
A smart contract audit refers to the process of scrutinizing the underlying code of a smart contract with the goal to pinpoint and rectify any latent security vulnerabilities, errors, or inefficiencies. This audit is designed to guarantee that your contract operates as expected, offers robust security, and is fully compliant with the recognized industry standards and best practices.
Put simply, a smart contract audit is an assurance that your contract is primed for smooth, safe operation once it is deployed.
The significance of thorough preparation and meticulous documentation cannot be overstated. It promotes clarity, economizes resources, and makes the entire process more efficient.
To ensure you gain the most from your audit, you should consider the following steps:
Meeting these criteria enables us to conduct an in-depth review of your project and accurately evaluate the code against your specifications. This level of preparation is necessary even if you don’t intend to pursue an external audit.
Functional requirements serve as a roadmap for auditors to grasp the specific objectives of your project. They need to be articulate, succinct, and devoid of ambiguity.
❌ Ambiguous requirement: Users should be able to earn tokens.
✅ Specific requirement: The contract should enable users to stake ABC tokens and earn XYZ tokens as rewards.
Providing as many functional details as possible can help auditors confirm the code performs as intended.
Here are a few additional examples of well-defined functional requirements:
While your smart contract code may be secure, it might not align with your intended goals. This is another reason why it’s beneficial to get an external opinion to ensure the application functions as intended.
How can auditors verify functionality and guarantee anything if they don’t understand what the app is about? Exactly! Clear and comprehensive functional requirements act as a yardstick to measure success. This is the only way to really benefit from an external review.
A comprehensive technical overview plays a vital role in audit preparation. Your focus should be on the following:
This information helps us navigate through your code, especially when your smart contracts are complex and interrelated. Again, it’s important to note that documenting vital aspects of your code is beneficial even if you have no plans to engage external specialists.
We consistently encourage our clients to configure a development environment for their projects. Tools like Truffle or Hardhat offer a comprehensive suite of automation tools, removing any justification for avoiding this step.
A dedicated development environment allows for:
Given these advantages, bypassing the creation of a development environment would be a missed opportunity.
Creating comprehensive unit tests to cover your code is not just advisable, it’s indispensable. It optimizes the auditing process, saves resources, and bolsters your app’s security.
We suggest striving for 100% test coverage, encompassing both positive and negative scenarios. Furthermore, we encourage the development of multi-user tests to evaluate the system’s resilience against potential DoS attacks. Simulating contracts for multiple concurrent users also guarantees that user operations remain unaffected by each other unless it’s part of your design.
By following these steps, you can detect security vulnerabilities even before initiating the audit. As a result, during the audit, we can leverage these tests, concentrating our efforts on the more complicated problems, thereby reinforcing your security measures.
Following official language style guides and formatting norms is yet another cost-effective and straightforward way to facilitate both auditing and any planned upgrades to your contract.
Adherence to these best practices decreases the time devoted to problem detection and lessens the likelihood of error oversight in fresh code additions. To put it simply, complying with best practices is an effective strategy for saving both time and money.
Now, let’s get to the most crucial part: the process of auditing your smart contracts.
At Hacken, we’ve honed our methodology over the years and suggest adhering to the following steps for the most effective and efficient error detection:
The initial phase of our audit aims to spot any problem areas needing attention before the in-depth review begins.
In the pre-audit stage, we peruse your provided repository, ensuring a comprehensive audit scope.
The pre-auditor evaluates the development environment for any potential compilation problems, executes the provided tests, and verifies both the functional and non-functional requirements.
Smart Contract Audit Tools
For Solidity contracts, we employ the following security analysis tools to unearth basic issues and gain a deeper understanding of the contracts:
For Rust contracts, we rely on the following tools:
Moreover, we run several in-house security analysis programs, details of which we don’t disclose, but with the aforementioned tools, you can achieve substantial results.
At the end of this stage, we provide you with a preliminary report, giving you the chance to make any last-minute modifications before the official audit commences.
Let the audit begin! Our aim at this stage is to equip you with validated insights that guide your decision-making process on the necessary modifications for enhanced code security.
Finding & documenting issues. In the exhaustive line-by-line review – independently conducted by a pair of skilled auditors – we meticulously examine each segment of your code for all possible vulnerabilities, including:
While the complete list of checked items is too lengthy to enumerate here, rest assured that key items for most programming languages are duly checked:
|Default Visibility||Functions and state variables visibility should be explicitly set.|
|Integer Overflow and Underflow||All math operations should be safe from overflows and underflows if unchecked math is used.|
|Outdated Compiler Version||A recent version of the respective compiler (Solidity or Rust) is recommended.|
|Access Control & Authorization||All crucial functions should be protected to prevent ownership takeover.|
|Assets integrity||Funds are protected and cannot be withdrawn without proper permissions or be locked in the contract.|
|Data Consistency||Smart contract data should be consistent all over the data flow.|
It’s essential to recognize that all issues are not identical. For this reason, we utilize more than 50 language-specific parameters for EVM (Solidity, Vyper, Yul) and Rust-based contracts (Solana, Near, CosmWas).
Testing. In addition, we thoroughly assess the test coverage. If we identify any gaps, no matter how small, we develop and implement additional cases to accommodate all potential positive and negative scenarios.
Bear in mind that some problems can only be replicated with incorrect configurations of dependent contracts. Accordingly, our auditors intentionally devise such configurations and run associated tests.
Each issue is classified as either Passed, Failed, or Not Related.
This crucial stage of the audit process truly showcases the merits of our unique methodology. Until this point, our auditors have been conducting their examinations independently, allowing for unbiased scrutiny and in-depth exploration of the code from their respective perspectives.
Now, these auditors come together for the first time, bringing their individual insights and discoveries into a joint discussion under the guidance of the lead auditor. We examine, converse about, and even argue over the identified issues in an open dialogue, fostering a more well-rounded understanding of your project’s potential vulnerabilities.
Moreover, the team compiles an internal document spotlighting the key aspects and possible weak spots of your project, in tandem with a detailed advisory report suggesting measures to bolster your project’s security and improve its audit rating.
The lead auditor goes over all the materials thoroughly to ensure they are complete, accurate, and represent the collective audit findings accurately. After this final check, the consolidated audit report is then delivered to you, serving as a robust assessment of your project’s security.
After an intensive cross-review of the findings, our team collectively formulates a detailed final report covering crucial issues, vulnerabilities, and executed tests.
The Executive Summary in the audit report offers a snapshot of key findings and overall assessment. The Checked Items section lists all reviewed elements, while the Findings provides detailed insights into identified issues and remedial recommendations. And the Disclaimers clarify the scope of the audit.
Essentially, the report presents a comprehensive review of the audit, empowering you with verified information to bolster your smart contract’s security and dependability.
External users. The final audit report is also an invaluable resource for external stakeholders such as community members and investors. They peruse it to make informed decisions when considering depositing/investing in your project.
Audit score. We also assign a final audit score based on three criteria:
This score provides an accessible way for external and non-technical users to get a picture of your project’s viability.
Some security companies may employ a streamlined workforce, where only 1-2 employees handle all responsibilities. Although this may cut labor costs, it risks quality compromise and places an undue load on those few individuals.
At Hacken, we embrace a more focused strategy where each professional is devoted to a singular key task. We advocate for role specialization, as it enables us to dedicate more valuable time to resolve problems at hand.
Undoubtedly, this method demands a higher investment in human resources, but over time we have found that the long-term benefits for both us and our clients are worthwhile.
At Hacken, we emphasize the absolute necessity of regular smart contract audits. With the immutable nature of blockchain applications, an undiscovered flaw in your smart contract can spell lasting issues.
Proactive audits help identify such vulnerabilities early, enabling you to secure your applications effectively and reliably.
Here’s a brief overview of our audit process for any blockchain:
Join us in our mission to make Web3 a safer space, one audit at a time!