The Complete Guide to Smart Contracts Auditing
- Lendf.me – $25 M loss*
- Synthetix – $ 37 M loss*
- bZx – $645, 000 loss*
- Parity – $150, 000 loss*
- The DAO – $55 M loss*
Do these numbers ring an alarm in your mind?
This is what happened with these tech giants as they ignored smart contract auditing conveniently. Even a minor bug in smart contracts can lead to dire consequences. Thus, auditing them is one of the best decisions you will take for your crypto business.
Widespread use of blockchain has led to increased opportunities for distributed consensus. However, smart contract applications come with their set of concerns and are susceptible to monetary losses and the infamous DAO attacks.
To eliminate all these issues, it is imperative to conduct security contracts from time to time. This guide will help you understand the various attacks, how to conduct the audit process, approaches for the same, the cost of getting an audit done, and other related aspects. Ready, let’s dive in!
What Do We Mean by A Smart Contract Audit?
There are a lot of similarities between a regular code and a smart contract audit. Both do an in-depth investigation of code to find security flaws.
It’s more like testing a bridge before its public announcement is made. In both scenarios, the builders or developers need to test the security and safety of products.
After the audit, you will get a list of potential vulnerabilities. The main objective behind the audit is to do an in-depth analysis of risks and inform the client about the same.
After that, the client will decide which bugs need to be eliminated. Please keep in mind that auditors are not responsible for fixing any bugs.
As we all know, blockchain is a list of replicated appended -only linked “list” of Merkle trees. Since smart contracts can execute on their own, it is important to track all issues and address them before they are launched on the main net.
Common Smart Contract Attacks
The best way to prevent attacks is to analyze them carefully. Here is a list of attacks known till now.
1. Possibility of Executing Unknown code
If there is a fallback function feature in the smart contract, these instances are common. Besides, if signature strings have been passed for encoding or a signature does not exist altogether, the function will also be called. Thus, developers must declare the interface of the called contract correctly.
In Ethereum, you can call the functions of smart contracts to occur synchronously. But, this can cause it to use the contract state of the calling contract. While this is not always obvious fraudulent actions can be taken on behalf of the contract.
3. Incorrect Calculation of The Token Amount
Modern DeFi smart contracts hold a lot of money in form of ETH tokens. With tons of operations connected with token transfers, there is ample room for mistakes connected to fees, calculations, and security. Few such errors also include:
1. Incorrect handling of decimals when dealing with USDT tokens
2. Not following the correct order of operations can also lead to accuracy loss.
4. Naming Issues
A classic example is that of the Rubixi smart contract. In this, the owner could transfer the fees to himself. Normally, the owner is set as the constructor of the contract, and the same logic was applied here.
Earlier, constructors were defined as functions with the contract’s name. While this was removed from the programming languages, if the developer calls the Dynamic Pyramid function, all the accumulated funds will go for a toss.
05. Order of execution
The state of a smart contract is determined by variables. Calling a contract is the same as conducting an ETH transaction. The transactions are finalized only when the next block has been created. So, a user calls a contract function; they cannot be sure if the state of the contract will remain the same or not.
This shows vulnerability in the contract, and developers will need to fix it. Besides, it also becomes dangerous to interact with contracts whose behavior is subject to change over time.
6. Time Component
At times the logic of the contract is dependent on the situation and time. Thus, it becomes easy to achieve consistency with the smart contract’s state. However, this can lead to issues from the miner’s side. They can exploit to their benefit and meddle with the code.
7. Poorly Handled Exceptions
Exception handling is purely based on how contracts interact with each other. Thus, contracts become vulnerable if the exceptions are not dealt with properly. In this case, even the transactions will not be conducted properly.
8. Mismanagement with ERC-20 Token
Modern protocols depend on OpenZeppelin’s implementation of the ERC-20 token. In most cases, it achieves the right functionality for operations. But, even custom implementations need to be run, and it can lead to discrepancies between the ERC20 standard and the newly created token. While it is a small mistake, it can lead to blocked contracts and stuck funds.
The Steps for a Full Smart Contract Audit
Vulnerabilities, bugs, and concerns can be found in the auditing process. Here is the structure you will need to create for a full smart contract audit.
Ensure Audit Is Completed on The Final Stage
Make sure your audit is performed on the final stage and before public release, as this will be closest to the end-user
Provide A Legal Disclaimer
The main purpose of the audit is to discuss bugs and vulnerabilities rather than provide any guarantees.
The next step in line is to establish your authority, build credibility that you can conduct a rigorous analysis, and then do a thorough audit.
Explain The Audit Process
Once you have established your authority, you will need to outline the smart contract and lay out the process you will be using from a security perspective.
Conduct Vulnerability Tests
Now, analyze if any of the above-mentioned attacks can be launched against the contract or not.
Give A Breakdown of Vulnerabilities and Concerns
In this step, you will need to categorize vulnerabilities as high, medium, critical medium, and low severity vulnerabilities. You will also need to give suggestions for fixing that. You might some areas that are not immediate threats but can later become huge hassles. Make sure you note them as well.
Gauge Contract Complexity
As the smart contract complexity increase, so does the likelihood of errors. Thus, make sure you record where complex contract logic has been used and if non-modularized code is present. While these are not red flags, it is best to avoid them.
Analyze Failure Preparation
You need to check how the contract will respond in case of failures. You also need to check if the contract will be paused and if the money risk will be managed or not.
Analyze Code Currency
The latest tool versions can come with vulnerability patches. Thus, it is suggested to use older versions and prevent risks.
Have Untrusted Contracts Been Marked?
To avoid mishaps, make sure you mark external contracts and convey that these code interactions are not safe. One way to do this is to use naming conventions such as UntrustedSender.
Error Handling with External Calls
Contract calls will propagate if they encounter an exception. Also, if this possibility is not handled, the contract will fail.
Have External Calls Been Optimized?
You will need to make sure that external calls are isolated in their own transactions. This will minimize the impact of external call failure.
Has Initial Balance Analysis Been Done?
It is possible that an address has some Wei before a contract has been created. Thus, there should be no initial balance assumption.
Do An In-depth Analysis of On-chain Data
You will need to make sure the appearance of the on-chain is not dependent on contract functionality. Since this data is public, the wrong order could put parties at a loss.
Check N-party Contracts
Will the smart contract function optimally if participants drop out and don’t return? Take this possibility into account and then proceed further.
Have Invariants Been Enforced?
A failed assertion can trigger an assert guard. So, assert() must be used to deal with invariants. One of the examples include assert(this.balance >= total supply);
Has Integer Division Been Conducted?
Here is a fact. All integer divisions are rounded off to the nearest division in Solidity. To solve this, you can choose to use a multiplier instead.
But what happens if Ether is sent forcibly? Well, all you need to do is to analyze invariant coding. This will help you check the contract balance and analyze the impact of forced ETH on code.
Has tx. origin been used?
It is a complete no-no to use tx. origin for the purpose of authorization. This is because it contains your address, and another contract can call yours and be authorized. We would suggest using msg. sender() instead).
Minimizing Timestamp Dependence
The Ethereum timestamp often works differently from a global clock. Also, miners can easily take advantage of this discrepancy. Thus, it would be great if you give out suggestions to minimize it.
Offer the Final Steps
Once you are done with all the above steps, you can suggest fixes to vulnerabilities found and take steps ahead. Also, be ready to answer if these are fixed and the code ready to deploy.
Approaches to A Smart Contract Audit
Developers usually follow two approaches for achieving smart contract security- automatic and manual. A good smart contract audit company has experts in both forms, and they follow a blend of both approaches to achieve highly reliable results.
Automatic Smart Contract Security Analysis
Automatic analysis can save a developer’s time to a great extent. There are many tools that can detect bugs and expedite smart contract vulnerability checking. A bug detection software will find out the parts responsible for input execution and show where the possible bug occurs. Some of the common tools used include Mythril and Sithler.
Manual Smart Contract Analysis
While the automatic approach is faster and offers results, it can also report false positives, which might not be bugs. It happens because the tools cannot fully understand the code context.
But, if they detect the wrong contract vulnerabilities, it can become a huge hassle. Thus, manual analysis is needed for smart contracts.
In manual code analysis, an examination of each code is done by developers. While this is more complex, it does the job well. Luckily, developers will be able to detect hidden problems that are present in the architecture and the contract logic.
Common Mistakes When Auditing Smart Contracts
Smart contracts require coding and building logic such that it is cost-efficient. You also need to check if the contract is well optimized or not. Here are some of the common mistakes that happen during smart contract audits.
Smart Contract Performance Validation
Performance validation is the first step towards a good security audit. Poorly optimized contracts will face delays and also consume more gas. Thus, leading to higher costs.
Performance issues are related to the quality of code, and validation deals with inappropriate orders or mistakes in the contract logic. Besides, a poorly optimized contract will lead to wrong contract functions and make it harder to determine problems.
Another thing that developers need to check is contract upgradability. Even if your contract works well today, there is no guarantee it will work well after you add a new feature to it. So, please remember that an audit should be conducted only after the upgrade or improvements have been made.
When it comes to developing contracts for DeFi projects, it is a must to have the seamless upgrade feature. This is because smart contracts should be adaptable and highly operable to all changes as the user’s money is involved.
Smart Contract Gas Fees Optimization
One of the most common challenges is how to reduce gas fees. Well, the gas fee is the amount you pay for the contract deployment and maintenance.
It varies and increases along with the smart contract complexity. So, it can become a challenge to optimize the fees with the development of a thoughtful, smart contract logic.
Also, if a contract has been written well but has not been optimized in terms of gas fees, it will be too expensive or impossible to deploy.
Here are some of the steps you can do to optimize gas fees for smart contracts:
- Strictly avoid double and triple nesting
- Reduce the number of variables you use
- Do not use your contracts as data storage
- Split bulky procedures into steps
- Pooled operations over consistent ones
- Keep your storage clear to redeem gas costs
- Give preference to fixed-size arrays instead of dynamic
Outsourcing Vs. In-House Smart Contract Auditing
While outsourcing the process might be costlier, chances of identifying vulnerabilities are higher as you will get access to experts who will analyze your project from different angles.
Besides, auditors will analyze your code in-depth to see if your code passes the unit tests for vulnerabilities, best practices, and solid construct usage.
Thus, in the long run, it is beneficial to get your smart contract audited from an audit platform.
But, in some cases, application contracts may not be that interesting to excite the experts.
Yes, there are a whole lot of things that need to be considered when building a smart contract and launching it. Conducting an audit is the most important thing you will do for your blockchain project.
It is suggested that you get multiple audits done to achieve top-notch security. But, where can you find such a platform?
Well, 0defect is a cutting-edge, secure, and one of the most advanced smart contract audit platforms.
Basic security audit, round-the-clock audit, interim audit, or full-security audit, you name it, and 0defect does that!
Moreover, you also get access to 150+ vulnerabilities and an exhaustive audit report. So, go ahead and secure your assets by getting your smart contract audited before it is deployed on the main net!