Smart contract security best practices: PART 1

Yuvarajan
InfoSec Write-ups
Published in
3 min readAug 5, 2022

--

Hello all, hope you are doing good, Today, we’ll go over smart contract security, which is something that every developer should be aware of before creating a smart contract. Smart contracts are pieces of code that run on the blockchain and handle millions of dollars. A simple flaw could result in the loss of a million dollars. To avoid this, we will learn about security best practices today.

Let’s get started

State change has to be done before external calls:

According to Consensys “If you are making a call to an untrusted external contract, avoid state changes after the call.” To understand it better, let's have a look at vulnerable code.

Example:

The above contract has two functionality namely deposit and withdraw. Imagine it as a bank. Users can deposit their money and can also withdraw it.

The problem here is there are no checks implemented on whether the user has enough money to withdraw or not.

Second one could be usage of .call() function. This could open up a possibility for a reentrancy attack. Note that .call() does nothing to mitigate reentrancy attacks, so other precautions must be taken.

The third flaw could be balance is getting updated after transferring the amount to the caller.

So How to fix this?

To fix this we need to use the checks-effects-interactions pattern.

What is Checks-effects-interactions pattern?

The checks-effects-interactions pattern refers to the various checks that must be performed prior to transferring funds to an external contract. In this way, we can prevent the loss of funds.

Let’s have a look at the fixed code.

In the above contract, withdraw function has certain checks including 1)whether the user has enough balance or not

2) State change is getting done before transferring the funds

3) Usage of .transfer() function instead of .call(). Note that transfer() function has a gas limit of 2300, This way it will prevent reentrancy attack.

We lost twice as much money in the first six months of 2022 as we did in the entire year of 2021. To avoid these hacks, developers should incorporate security best practices in their smart contracts.

UPDATE: PART 2 Has been released!!!, check it out from here.

To learn more about web3 security follow me on Twitter.

https://twitter.com/UV_virus\

From Infosec Writeups: A lot is coming up in the Infosec every day that it’s hard to keep up with. Join our weekly newsletter to get all the latest Infosec trends in the form of 5 articles, 4 Threads, 3 videos, 2 Github Repos and tools, and 1 job alert for FREE!

--

--

Security guy who post articles on topics related to cyber security, web3, Digital forensics, malware analysis