Smart contracts seem secure, thanks to their immutability and blockchain-powered decentralization and security. These characteristics make it difficult for anyone to alter the terms of the agreement, breach the contract, or commit any other kind of fraud.
However, this is one side of the story. If this were true 100%, we would not have heard of smart contract scams and millions of funds being stolen taking advantage of smart contract loopholes.
Smart contract vulnerabilities are minor loopholes in the system that hackers use to tweak the code of the contract and steal the assets or money associated with that contract. Some of the common challenges that smart contracts face are reentry attacks, gas grieving, DOS attacks, and integer overflows.
In the first quarter of 2024, over $430 million was stolen in just 50 attacks, the majority of which occurred due to vulnerabilities in smart contract codes. Feeling stressed? Don’t worry, you can easily avoid these attacks with simple steps. This blog explores some common smart contract vulnerabilities and ways to overcome them.
Wondering how you can secure your smart contracts with artificial intelligence? Read this article.
Common Smart Contract Vulnerabilities And Their Solution
Smart contract vulnerabilities pose a threat to the rising Defi sector, putting investors and users at high risk. Here are some common smart contract loopholes and strategies to mitigate them.
1. Reentry Attacks
Reentry attacks are one of the dangerous smart contract hacking techniques. In this method, hackers take advantage of the external call to steal the funds.
How is it possible when a smart contract is immutable?
Reentry attacks are possible during the imperative execution of Solidity smart contracts. By imperative execution, we mean that when a smart contract calls another external smart contract, the execution of the calling contract is put on hold till the return of the call.
Now hackers enter the calling contract with the help of an external contract. They make malicious smart contracts and then steal these external calls to make recrursive call back to the original contract.
In simple terms, hackers enter the original contract through an external contract and alter the code of the original contract to withdraw the funds.
The simple solution to avoid reentry attacks is to ensure that your smart contract updates its balance before making external calls. You can also use advanced function modifiers to prevent hackers from using callback functions to change the contract’s code.
Learn more about smart contract wallets and how they function by reading this article.
2. Gas Griefing
If you are into blockchain or cryptocurrencies, you already know what gas fees are. It is the amount required to execute your smart contract or, in simple words, your transaction on the blockchain. The amount depends on the complexity of your transaction and the network congestion at the time of processing.
Sometimes a malicious user pays insufficient gas fees to stop the proper execution of the smart contract. The amount is enough for the main contract to execute but not enough for the contract to make subcalls or external calls. Hackers do so to halt the smart contract from processing, disrupt the system, and cause delays or financial losses. This is what we call gas griefing.
What you can do to prevent gas griefing is ensure that there is enough gas for the entire contract to execute, including the subcalls. You can verify the amount of gas fees sent by each user and reject the significantly low ones.
3. Oracle Manipulation
Oracle manipulation has become the biggest issue for Defi applications. It is a type of data manipulation with malicious intent to cheat the Defi applications and get away with huge profits.
Let’s understand in detail.
Oracles are bridges that connect the blockchain network from the outside world. Blockchain networks depend on Oracal to fetch data from sources outside of the blockchain. For example, a smart contract for DeFi will ask Oracle to check the price of a stock or cryptocurrency.
Oracle manipulation is when someone tampers with this data so the smart contract gets the wrong data and the user can successfully execute his fraudulent plans.
Take the example of a DeFi platform that gives collateral-based loans. Users can take loans by keeping their assets as collateral on the platform. The amount of the loan depends on the value of the collateral asset. Also, the DeFi app uses Oracles to verify the market price of the collateral the users submit.
Now a malicious user applies for a flash loan to pump up the price of his asset on the Oracle feed. He then uses the same inflated asset as collateral and gets a large loan from the Defi application. Once he receives the amount, he sells off his assets and repays the flash loan. In the end, the user keeps the borrowed funds from the DeFi app as profit, whereas the application is left with an undervalued asset.
Here we see that hackers don’t break the rules of the blockchain but take advantage of how oracles are designed and their interaction with the blockchain networks.
The best way to avoid oracle manipulation is to use reliable decentralized oracles like Chainlink or multiple oracles to cross-check the data before executing the contract. Another way is to use time-weighted average prices (TWAP) to avoid reactions to sudden price changes.
4. Frontrunning Attacks
Smart contracts are visible on the blockchain network. But who knew that hackers would use this visibility to steal your funds?
What happens is when you put smart contracts for processing, it is added to the pool of pending transactions (especially when there is high traffic on the network). The miners then choose the contract with higher fees to execute first.
While your transaction is pending on the network, someone else might copy your contract and front run it. It means that someone can easily see your contract details and create an identical contract with higher gas fees so that it’s executed before your original contract.
There are several proven solutions to avoid frontrunning attacks, like the commit and reveal scheme, batch processing, randomized transaction ordering, Fair Sequencing Service (FSS), gas limiting, and more. The best possible solution is to batch multiple transactions and forward them for processing together. This stops the hackers from targeting a specific transaction. You can also cap the gas fee for certain operations or time-lock your contract so that hackers don’t benefit from delayed processing.
If you want to learn how to build smart contracts on Ethereum, follow this step-by-step guide here.
5. Integer Overflow and Underflow
Another common smart contract vulnerability is integer overflow and underflow, which result from arithmetic operations surpassing a fixed value.
Solidity smart contract runs on 255 bits, meaning that unit8 can carry value from 0 to 255. If the value exceeds the upper limit (255 + 2), the value will reset to 0. And if the number goes below the lower limit, it resets to 255.
In these cases, the Solidity compiler will not execute the contract with codes containing integer overflows or underflows as it alters the logic of the contract.
Imagine a scenario where a smart contract for managing the reward system tracks the rewards of the users. The users play a game and earn points, which are tracked using the unit8 variable. Now a malicious user enters the group and leverages the integer overflow. He somehow hacks into the system and performs an action to intentionally add one more point to the current maximum value (255). This resets the total points earned by players in the group, resulting in some players even losing their rewards as well.
One of the solutions is to use Solidity compiler 0.8.0 or later, which checks for underflows and overflows. If you are using a compiler below the 0.8.0 version, you can deploy OpenZeppelin’s SafeMath library, which avoids underflows or overflows and reverses the transactions in such scenarios.
Conclusion
Smart contracts are indeed one of the innovations that have made decentralized finance a reality. However, its vulnerabilities can result in loss of trust in Defi applications and need to be checked or proper measures should be implemented to mitigate them. Only then the users retain their faith in DeFi applications, which is critical for its growth and widespread adoption.