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 digital age, Web2’s centralization, dominated by state-regulated banks, social media, and e-commerce giants, contrasts sharply with Web3’s promise of returning control to individuals through decentralization, data privacy, and blockchain technology. While Web3 champions trust in technology over people, the evolving landscape has exposed the pressing need for enhanced security.
In 2023, the Web3 realm was hacked for about $600 million. Stark reminders, like the $126m Multichain hack where CEO Zhaojun controlled all keys, emphasize the importance of robust operational security and genuine decentralization. Similarly, the Atomic Wallet exploit, compromising $100m in assets and affecting millions of users, underscores the urgent need for improved cybersecurity standards in this nascent space.
Coming from a development background, you must be familiar with the concept of tech stacks. A web development stack called MERN uses MongoDB for the database, Express.js for the back end, React for the front end, and Node.js for runtime.
There are, of course, countless other stacks for each area of software development, and blockchain is no exception. A Web3 security stack follows the same logic but refers to a set of services and tools for cybersecurity in blockchain platforms and applications.
Web3 stacks are generally more fluid, but professionals generally distinguish between the following verticals regarding security: infrastructure, smart contract security, and ecosystem. Let’s take a closer look.
Essential security measures:
Web3 relies on Web2 technologies for front-end interactions, such as APIs, to bridge the user-friendly Web2 front-ends with decentralized back-ends. However, these communications usually lack encryption methods, making them vulnerable to on-path attacks and data interception, much like the unsecured Web2 applications.
The suitable answer to these risks is penetration testing and dApp audits for these off-chain components. Penetration testing is the most essential security measure to assess the strengths of your systems in the real world. Pentesting is widespread in software development, and core principles remain the same, but Web3 projects require a distinct approach that is tailored to the context of crypto markets.
In Web3, access to the private key is paramount, as it’s the only true indicator of asset ownership. Hence, efforts related to threat modeling must focus on protecting private key and seed phrases. For example, our security engineers use several layers of proprietary tools to identify multi-vector attacks that could lead to data breaches:
When choosing a pentesting provider, look at how well their service fits your operations. For example, Hacken Blockchain Penetration Testing is conducted in a safe and controlled environment minimizing any risks to business activity.
The specifics of a dApp audit depend on your application. For a wallet, it involves a secure code review & static security analysis targeting off-chain components, privacy & confidentiality, and UI security design. For a bridge, dApp Audit uses similar tools to detect issues with chain reorganization/finality, mixing of chain IDs, signature forgery, and code/architecture vulnerabilities.
Not your keys, not your crypto – is the most vital Web3 dogma that applies to individuals as well as projects. Here, the most crucial task is to find the right balance between cold and warm storage, which primarily depends on your liquidity needs. Either way, the standard for asset storage is BIP-44, which introduced Multi-Account Hierarchy for Deterministic Wallets. Large organizations are also recommended to use passphrases introduced by BIP-39.
Regarding asset management and custody, the top tools on the market are Safe and BitGoas which offer reliable multisig functionality. Wallet-as-a-service provides even broader functionality, allowing the creation of thousands of wallets for your entire infrastructure. For example, Fireblocks is an option in this category as it had undergone a CCSS Level III audit.
For hot storage and smaller needs, we can confidently recommend MetaMask because it’s the only crypto wallet that achieved 90+ scores in CER rating across all platforms.
Tools like Hacken Extractor detect attacks at early stages. These tools are fully automatic, work 24/7, and allow a wide range of triggers, events, alerts, and preset actions. Extractor and others provide many useful features and hands-on value, alerting contract owners on suspicious activity that usually precedes hacks. Another good tool is OpenZeppelin Defender, which offers similar functionality. Others include Forta and Tenderly Alerts.
Essential security measures:
Top auditors like Hacken, Consensus Diligence, and OpenZeppelin provide professional security services to all Web3 projects that use smart contracts in their implementations.
A smart contract audit is the foundation of Web3 security. A thorough 3rd party audit validates the security and desired behavior of your smart contracts, potentially saving millions in losses due to unchecked vulnerabilities. A comprehensive audit can easily detect the most common exploit patterns, including reentrancy, overflows, front running, and math errors.
The rationale behind an external review is simple: your developers are primarily tasked with making things work and may leave unintentional weaknesses. By contrast, the auditor’s task is to scrutinize every line of your code and uncover what can go wrong.
That being said, not all auditors are created equal. Some are more likely to miss vulnerabilities, as seen in the Rekt leaderboard. Generally speaking, the difference between a good auditor and a bad one is consistency in terms of detecting vulnerabilities. That requires sufficient knowledge and expertise, systemic enforcement of standards and methodology, and considerate communications with the client.
Top tools in the industry:
Fuzzing is an automated testing technique that generates lots of semi-random inputs to find security vulnerabilities by triggering unexpected or invalid behavior in the system.
Hacken-Fuzzer is a proprietary tool developed by Hacken engineers that uses the power of cloud computing to take testing to the next level. Our auditors use it when conducting Blockchain Protocol Audit and Smart Contract Audits.
In smart contract fuzzing, Hacken auditors analyze the ABI or bytecode, generating randomized valid inputs for their functions, executing the contract with these inputs, and examining the results to identify and report any weaknesses.
Let’s review another tool called Diffusc, which uses differential fuzzing to simplify the process of reviewing smart contract upgrades. It’s hardly a tool for day-to-day operations but may prove useful when comparing two smart contract implementations.
Other great tools for smart contract fuzzing right now are Echidna and Foundry, each with its pros and cons.
Top tools in the industry:
These two methods examine the smart contract code for bugs and errors both with and without running it. Hacken Security Toolkit seamlessly integrates both analyses. But it’s important to understand the standalone tools that exist for this process. Some of the most popular multi-purpose tools are MythX, Mythri, Slither, and Contract-Library.
There are also tools that target specific vulnerabilities or languages. For example, MadMax addresses gas DoS vulnerabilities, Caracal specializes in contracts for Starknet, and SolidtyScan is optimized for Solidity.
Formal verification uses a mathematical model to prove the system’s correctness. It’s similar to the previous methods but focuses more on the contract’s behavior rather than weaknesses. The top services in this area are Hacken Security Toolkit, Runtime Verification, and Consensus Diligence. There are also automatic verification tools like Certora and Scribble.
Bug bounty providers connect Web3 projects with security researchers and ethical hackers. The workflow is simple and cost-effective as the project only pays for bugs once when they are found:
The top players in the crypto bounty space include HackenProof, Immunefi, Intigrity, HackerOne, Hats Finance, and BugCrowd. Yet, among these platforms, only HackenProof and Immunefi are custom-tailored for Web3 projects.
Pro Tip: Choose bounty platforms with a flexible offering that can be tailored to your specific needs. For example, HackenProof provides access to 20k researchers, verifies the scope, severity level, and relevancy of each bug, delivers reports, and manages bounty payments.
The most comprehensive all-in-one package for protocol risk management is Hacken Blockchain Protocol Audit. During this audit, our team conducts deep research into the inner workings of a protocol to discover inherent vulnerabilities, analyzing the core protocol subsystems, internal architecture, known attack vectors, and vulnerabilities.
From July 2022 to July 2023, Hacken conducted 20+ audits for various layer-1 and layer-2 protocols, identifying dozens of critical vulnerabilities related to protocol nodes, Virtual Machines (VMs), consensus implementations, and cryptographic primitives, among many other components.
Research platforms like CER.live provide the most comprehensive ranking and security assessment of top crypto wallets across different platforms:
CER.live also ranks the security of dozens of other DeFi projects to keep you aware of the threats.
Chainalysis is a stable source of quality analytics and statistics from the world of blockchain. We highly recommend subscribing to their reports. Another useful resource is TRM labs.
The tool called evm.storage lets you check the storage and state of any contract on the Ethereum blockchain.
The future of Web3 will bring more security standards, whether through regulations or self-imposed. All cryptocurrency systems seeking compliance with the latest security standards, including SOC2 Type 2 & PCI DSS at Level 3, require a CCSS Audit. A certified CCSS Auditor can conduct it, and Hacken has the most CCSSAs on the market, granting us the expertise and resources to provide this most comprehensive service.
Web3’s rise has made integrating AI and ML in security essential. With decentralized platforms growing, user security on-chain can’t be ignored. As auditors keep pace, they’re blending these techs for advanced crypto protection. In fact, just as smart contract developers turn to ChatGPT for help with code, companies like Hacken are using AI to bolster their security tools, like the Extractor. The industry isn’t just stopping at detection; they’re diving deep into research to improve formal verification with AI and ML as well as automated response. The aim is clear: spot potential threats and odd patterns with a higher degree of confidence before the attack enters its irreversible stage.
The shift from Web2 to Web3 brings a transformative promise of decentralization and user empowerment. However, it is equally met with security challenges that can jeopardize this vision. Recent incidents underline the urgency for developers to prioritize security in their Web3 applications. From smart contract vulnerabilities to infrastructure threats, it’s vital to employ comprehensive security stacks and stay updated with emerging tools. A proactive, security-first approach is not just recommended but imperative for all Web3 projects.
Web3 security is a process of keeping digital assets such as cryptocurrency and identity safe from cyber threats.
Web3 is a novel invention and lacks rigid standards and security controls, increasing the risks of exploits, scams, and hacks.
One is unlikely to hack the entirety of Web3, but individuals, projects, apps, and protocols will be hacked if bad actors manage to find and exploit their vulnerabilities.