Smart contract threats and vulnerabilities: How to avoid them
Published: 2022-10-05 21:34:36

A smart contract is a computer program or a transaction protocol that is intended to automatically execute, control or document legally relevant events and actions according to the terms of a contract or an agreement. They are merely blockchain-based programs that run when specified criteria are met.

The decrease of the requirement for a third party you can trust, the expense of arbitrations, losses from fraud, and the number of malicious and unintentional exceptions are all objectives of smart contracts. The majority of smart contracts are related to cryptocurrencies, and Ethereum's smart contracts are widely regarded as the fundamental building blocks for decentralized finance (DeFi) applications. The sole focus of this article will be on solidity smart contracts.

## Threats and vulnerabilities 

Every user on the blockchain where a smart contract is based can see it. This results in a situation where problems, such as security holes, are readily apparent to everyone but may not be immediately corrected.
Particular issues with Ethereum's smart contracts include ambiguities and simple-yet-insecure constructs in its contract language Solidity, compiler and EVM bugs, attacks on the blockchain network, the immutability of bugs, and the lack of a central repository for information on known vulnerabilities, attacks, and problematic constructs. Let's talk about the typical dangers connected to smart contracts.

### Reentrancy Attacks
This type of attack is extremely dangerous, allowing a vulnerable smart contract to be drained of all its ether. It is also very easy to accidentally commit. Reentrancy attacks occur because of two critical features of solidity: 
i. Smart contracts execute imperatively—that is, they wait for each line to finish before executing the next line. 

ii. Smart contracts can call external, untrusted contracts and wait for the result before proceeding. 
Therefore, when a vulnerable contract A makes an external call to another untrusted contract B, it’s possible that the other contract B can be maliciously changed to make a recursive call back to the original contract A. If the call from contract A to B involves sending any amount of ether, this infinite loop can effectively drain contract A of all its resources before the function finishes. In simple terms, a reentrancy attack occurs when a function makes an external call to another untrusted contract. 


![Reentrancy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwswkjhpqy4e4ylo6q3q.png)

There are three primary techniques to avoid reentrancy attacks
- Checks, Effects, and Interactions (CEI)
- Reentrancy Guard / Mutex:-A modifier that can prevent reentrancy during certain functions.
- Pull Payment

### Frontrunning

Smart contracts and transactions become fully public not when they’re confirmed on the blockchain but the moment you submit them to the network as a pending transaction. These pending transactions are shared throughout the network in the mempools of Ethereum nodes, allowing the miner of a block to select the transactions with the highest gas fees(not the case with ETH 2.0). 
One demerit of this design is that the intended outcome of a smart contract is visible to all for a period of time before it’s confirmed in the blockchain. Assume you have a smart contract that, when executed, will perform an arbitrage that will earn you 1 ETH and will cost you 0.05 ETH to deploy. Malicious actors watching the mempool may see this transaction, recognize the opportunity, and copy your smart contract, submitting it with a gas fee of 0.06 ETH. Then, they’ve successfully "front-run" your contract, stealing your arbitrage opportunity by submitting their transaction first.
In practice, these attacks are often carried out by the miners themselves, resulting in a phenomenon known as MEV (miner extractable value) that is worth thousands of ETH on a daily basis. Unfortunately, they’re fairly difficult to avoid, but splitting transactions into multiple smaller transactions can help reduce the effect.

### Integer Overflow & Underflow

This is a common attack in many programming languages. Let's discuss how this attack might occur in Solidity. 
Solidity smart contracts are built using 256 bits as the word size, which is approximately 4.3 billion. When reducing the value of an unsigned integer by 0, it will loop back around to the maximum value. 
Therefore, an underflow attack can be executed by having a malicious address that is recorded by the smart contract to have zero balance attempt to send 1 unit of Ether, forcing its balance to cycle all the way back to the maximum value allowed: 4.3 billion. 
Then, because the smart contract believes the address to have a balance of 4.3 billion ether, it may permit any withdrawals from that account to continue until the smart contract is drained of funds.
This is easily exploitable for any smart contract that tracks address balances internally. To avoid this, make sure you’re using a 0.8.x version of the Solidity compiler(it automatically checks for overflows and underflows). 

Other vulnerabilities include but not limited to;
- Denial of Service: Contracts that are susceptible to Denial of Service assaults, gas limit reaching, unexpected exception, unexpected kill, or access control breach fall under this category.

- Bad Randomness: This category includes flaws in the creation of random numbers. Smart contracts never have a 100 percent foreseeable outcome. Because of this, it is extremely difficult for them to produce random values. If the contract employs a random number, the attacker can try to exploit it by foreseeing what is predictable. 

- Short Addresses: This vulnerability involves sending function call arguments that have been wrongly filled out such that the EVM cannot properly decode them.

- Time manipulation: We locate time-related vulnerabilities under this category. Due to the fact that a smart contract's timestamp dependency makes this possible, the vulnerability is also known as "timestamp dependency.For instance, the timestamp variable is typically used when a contract wants to lock the sale of a token for a specific period of time. However, there is some flexibility for miners to specify the period the mining took place. Therefore, it is advised against relying on timestamp.

- Unchecked low-level calls: This category includes flaws caused by the value returned by low-level calls, such as call(), callcode(), delegatecall(), and transmit, not being checked ().

Other threats include code vulnerabilities, compromised private keys, e.t.c. These can be avoided by writing more secure smart contract codes, running automated security scans on smart contracts, keeping private keys safe, e.t.c.

### Conclusion
This is my breakdown of some of the threats and vulnerabilities in a solidity smart contract known at the moment, which I know and shared with you so that you can avoid them while writing your own smart contracts.

So, which question do you have for me?
Let me know in comment section. Moreover, If anything else that I may have missed out on, please share it in comment as well 👍.

## 🌎 Let's Connect
[Twitter](https://twitter.com/Ayokunnuolami)
[Linkedin](https://www.linkedin.com/in/junaid-ameenat-162293217/)

To have a much larger overview of this topic, you can check [here](https://swcregistry.io/docs/SWC-100)