Smart contracts are specialized programs stored on a blockchain typically used to automate the execution of an agreement so that all parties can be certain of the outcome without the need to trust one another or any intermediaries.
A smart contract guarantees that its execution will correspond exactly to the logic that was originally written in it. And after the execution of said predetermined logic, the final state on the network will stay immutable. Despite their potential, smart contracts are not immune to vulnerabilities and attacks.
In this blog post, we will delve into the shadow of the smart contract world and uncover the most common vulnerabilities that have plagued these futuristic contracts.
What is Smart Contract?
“Smart Contracts are computer protocols designed to digitally facilitate, verify and enforce the negotiation or performance of a contract.”
They act as self-executing contracts within blockchain-based transactions. They do not demand human intervention in advance to authenticate and sanction the conditions, allowing parties to exchange money, property, shares, or anything of value transparent and conflict-free.
Smart contracts are powered by digital assets and held in escrow, ensuring that all parties involved follow through with their end of the agreement. The foundation of its operation lies in three fundamental attributes: expressing value, transparency, and immutability.
However, these advantages also make them a prominent target for hackers and cybercriminals seeking to take advantage of vulnerable security systems. Recently, security issues related to smart contracts have been rampant. In February 2022, almost $320 million was stolen from Solana and Ethereum due to the Wormhole Cross Chain Bridge Attack.
On March 2021, DODO DEX fell victim to a devastating smart contract hack which unfortunately resulted in the loss of approximately $3.8 million worth of cryptocurrency.
It’s essential to note that smart contract attacks not only cause notable monetary losses but also damage the protocol's and its team's trustworthiness. The long-term ramifications of this are likely to be much more profound than the short-term loss.
What are Smart Contract Vulnerabilities?
Smart contract vulnerabilities are weaknesses that malicious actors can exploit in smart contracts. These vulnerabilities are typically identified and exploited through code analysis, but they can also be identified indirectly through testing or monitoring the network for suspicious activity.
Some of the most common smart contract vulnerabilities include insecure coding practices, poor system design, incorrect implementation, lack of proper security controls, and reliance on third-party libraries.
Unlike most forms of agreement, smart contracts are largely focused on monetary assets. Therefore, due to the immutable nature of Blockchain technology, errors in these sorts of contracts cannot be undone after they have been deployed.
Smart contract vulnerabilities are a grave concern and an inviting target for malicious hackers, as evidenced by successful attacks. Even when there is no external threat, the potential for financial losses due to capital collapse remains high.
8 Most Common Smart Contract Vulnerabilities
1) Integer Arithmetic Errors
Integer arithmetic errors are one of the most common contract vulnerabilities. Smart contracts typically employ integers to represent values because they do not feature floating-point support.
When dealing with figures in financial software, it is practical to reduce the value to a smaller unit for more accuracy when using whole numbers.
A straightforward example of value representation is in cents rather than dollars, as it would be difficult to reflect $0.5 otherwise accurately. Furthermore, smart contracts almost always reduce the number even further and allow up to 18 decimal places for various tokens.
Currently, developers are well aware of the threat that integers may overflow. When computers store integers, they have a predetermined upper limit which, once exceeded, causes the value to reset back to its lowest point. Similarly, subtracting 4 from 3 in an unsigned integer will lead to underflow and thus generate an excessively high number.
Since these scenarios are not always properly handled, attackers can exploit integer arithmetic errors to deceive a contract.
2) Reentrancy Attacks
Reentrancy attacks are malicious smart contracts that take advantage of the vulnerabilities in another smart contract to steal its funds. It occurs when a smart contract calls another smart contract in its code and, when the new call is finished, continues with execution. To safeguard against potential vulnerability, this action necessitates the contract to make an external call.
Cybercriminals take advantage of the callback function to intercept external calls and make fraudulent calls back to the contract. With malicious code, they can spawn an agreement at any external address.
Suppose a smart contract fails to update its status before sending funds. In that case, the hacker has the potential of repeatedly calling on the withdraw function and depleting all financial resources in that particular contract. This can cause problems, such as draining funds from a contract or overwriting critical data without the owner’s knowledge.
To protect against this type of attack, it is important to ensure that all functions are properly coded to limit the number of times they can be called. Additionally, it is important to review and audit smart contract codes for any potential vulnerabilities before launching the contract.
3) Integer Overflow and Underflow
Integer Overflow and Underflow occur when a smart contract cannot process an operation correctly due to the numbers involved being too large or too small. This can lead to unexpected and unintended results, as well as malicious actors exploiting such vulnerabilities for their benefit.
A stellar example of overflow and underflow vulnerabilities can be seen in the infamous PoWH (Proof of Week Hands Coin) cryptocurrency Ponzi scheme. The project promised a genuine pyramid scheme and rapidly escalated to be valued at more than one million dollars. However, on just one evening, the currency plummeted by an alarming $800k due to miscalculations in its arithmetic.
By establishing ERC-20 for the project, users could authorize a second user to move their tokens. Unfortunately, it also opened up an opportunity for malicious actors; one individual could sell off coins from another person’s account without authorization! Subsequently, coins were removed from the second account's balance. This had the unintended consequence of causing a negative integer underflow that left the second account with an outrageous amount of PoWH Coins in its possession.
4) Incorrect Calculation of the Output Token Amount
Smart contracts are not immune to flaws, especially those managing large volumes of money in the form of tokens or ETH value. These weaknesses have been particularly evident with recent DeFi smart contracts.
Regarding smart contract protocols, the contract logic is often heavily intertwined with token transfers. This opens up a world of potential errors related to accurate percentages, fee calculations, and profit estimation.
Common mistakes to be aware of include the following:
- When dealing with a token such as USDT, incorrect decimal handling can be particularly problematic.
- Calculating fees with incorrect order of operations can result in a major decrease in accuracy.
- The accuracy constant, which was inadvertently omitted from the mathematical calculations, has been overlooked.
All of these mistakes inevitably result in users losing money or tokens that are locked away forever. Therefore, a contract auditor is responsible for confirming the accuracy of mathematical operations. Many modern automated tools and static analyzers also perform such checks to ensure security and reliability.
5) Front Running attacks
It’s fascinating to note that smart contracts and transactions become totally public the moment they are submitted as pending transactions. Not only can these be viewed in entirety by all nodes on the Ethereum network, but miners also have access to them through mem pools, where they can select those with higher gas fees for faster confirmation.
There is a significant side effect of this visibility. It allows malicious actors to see the intended outcome of a smart contract before it’s confirmed on the blockchain. Imagine you have a smart contract that, when run, will execute an arbitrage that costs 0,04 ETH to deploy.
Be aware that hackers can easily duplicate your smart contract and submit it with an elevated gas fee. This allows them to take advantage of you by front-running their transaction, preventing yours from happening first and thus stealing the arbitrage opportunity for themselves.
While it may be difficult to prevent these breaches, the good news is that there are modern measures you can take to protect your agreement. Gas limiting and pre-commit schemes are two methods for secure transactions. Gas limiting allows only those transactions with a gas price below the accepted threshold to be processed. At the same time, the pre-commit scheme requires submitting a hash of your data in place of details initially, then providing them later.
6) Default Visibility
When creating a contract, its author needs to keep the visibility of their public functions in mind. One common mistake developers make is leaving their functions set to “public” by default.
By default, functions are publicly visible and can be accessed internally and externally by users. Visibility is what determines whether a function may or may not be called.
Failure to properly filter or limit access when making an agreement public can result in an attacker being able to alter the code and rewrite entire sections of the contract, leaving the contract vulnerable to malicious exploits.
7) Incorrect work with ERC-20 Token
The ERC-20 token implemented by OpenZeppelin is a popularly used standard in today’s protocols. Generally speaking, its functionalities are sufficient for carrying out financial transactions precisely and accurately — making it an ideal solution for most cases.
Although there is a need for custom implementations of the token standard, it can cause discrepancies between the new tokens and actual ERC-20 standards. These small inconsistencies may include things like missing return values in transfer() functions.
Although these errors may seem minuscule, they can create big problems for contracts. In the long run, this tiny mistake — which is often not detected during testing — will render them non-functional and result in funds being stuck or, even worse, blocked.
8) Time Component/Manipulation
When a smart contract uses the block.timestamp function to display StartTime and EndTime, malicious miners can take advantage of this by manipulating the timestamp for their own benefit; this is why it’s discouraged to utilize the block.timestamp feature due to its decentralized nature in blockchain technology.
It’s essential to note that this vulnerability is only concerning if utilized in the vital elements of a smart contract.
To avoid this issue, you have two options: abstain from using the block.timestamp function or permit a discrepancy of up to 900 seconds — meaning that even if the timestamp value returned by the node increases anywhere between 1 and 900 seconds, it won’t have drastic consequences on your contract.
How to avoid Smart Contract Vulnerabilities?
1) Conduct a Smart Contract Audit
It may seem like a no-brainer, but it is an essential step you can take. An audit can help you identify and eliminate vulnerabilities in your contract, optimize gas consumption, and guarantee its accuracy and efficiency, ultimately improving the overall performance of your source code. This makes it a vital component during any smart contract development process!
Smart contract auditors cannot only identify security vulnerabilities within your smart contracts but also guide how to fix any issues and ensure that your smart contracts run optimally.
2) Document smart contract vulnerabilities and security practices
Taking advantage of prior mistakes made by others is a smart way to stay ahead in the world of smart contracts. Documenting all smart contract issues can help you guard against repeating them while checking your own contracts for any security flaws.
Once all known security issues have been addressed, it’s always wise to double-check your code against existing ones to ensure you are not exposed to any foreseeable risk.
Organizations should create a list of the most effective smart contract security used by the leading players for optimum protection. This could include keeping code off-chain whenever possible, writing concise functions and partitioning logic into multiple contracts, and thoroughly documenting all code.
3) Perform internal security checks
Establish an in-house security team to monitor the safety of your smart contracts regularly by auditing the source code for any potential bugs and ensuring there are no loopholes that malicious hackers can exploit.
4) Use a bug bounty program
A bug bounty program can be employed after performing a smart contract security audit to secure your smart contract further. By doing so, you can guarantee an even higher level of safety for the code base.
Bug bounty programs offer ethical hackers the opportunity to detect smart contract vulnerabilities — and get rewarded for it! In this program, individuals are paid for successfully uncovering security flaws.
5) Opt for a Security Monitor Tool/Alert Tool
To defend yourself from hackers, a smart move is to either use an alert service or deploy a tool that notifies you when someone blacklisted attempts to tamper with your smart contract. This way, you can remain one step ahead and protect yourself against malicious actors.
Lossless Aegis provides security monitoring that can be used to detect any malicious activity on your smart contracts. It also gives real-time alerts for suspicious activity.
You can keep your smart contracts safe and secure by following the right security measures and preventive steps. Taking the time to document, audit, and continually monitor your smart contracts is an invaluable investment that will benefit you in the long run.
Smart contracts are the backbone of blockchain applications but are also subject to vulnerabilities that can be exploited if not adequately handled. Developers must ensure their smart contracts are secure and have no flaws.
By following the steps outlined above — such as conducting a security audit, documenting smart contract vulnerabilities, performing internal checks, using bug bounty programs, and opting for a security monitor tool — you can almost guarantee that your smart contracts are secure and safe from malicious attackers. Investing in a comprehensive security infrastructure is the best way to protect your smart contracts.
Restoring trust in web3 security. Lossless incorporates a new layer of blockchain transaction security, protecting projects and their communities from malicious exploits and associated financial loss.
Lossless protocol implements an additional layer of blockchain transaction security for ERC-20 standard tokens, mitigating the financial impact of smart contract exploits and private key theft. Lossless protocol utilizes community-driven threat identification tools and a unique stake-based reporting system to identify suspicious transactions, providing real-time protection.