Photo by Max Bender on Unsplash

Smart contracts vulnerability explained : Re-entrancy

Simon Busch
Published in
2 min readFeb 16, 2023

--

Re-entrancy is a type of vulnerability that can occur in smart contracts, particularly those that interact with external contracts or resources. It occurs when a contract calls an external contract and then calls back into itself before the external contract has finished executing. This can create an infinite loop, potentially allowing an attacker to drain the contract's balance.

This is an example of a smart contract that is vulnerable to re-entrancy attacks:

pragma solidity ^0.8.0;

contract Vulnerable {
mapping(address => uint) public balances;

function deposit() public payable {
balances[msg.sender] += msg.value;
}

function withdraw() public {
// 1
uint bal = balances[msg.sender];
require(bal > 0);
// 2
(bool sent, ) = msg.sender.call{value: bal}("");
require(sent, "Failed to send Ether");
// 3
balances[msg.sender] = 0;
}
}
  1. Here, we can see that the function checks if the caller has sufficient balance to make the transfer.
  2. If they do, the function makes a call to msg.sender.
  3. It sets the balance of msg.sender to 0.

Let’s consider this malicious contract:

contract Attack {
Vulnerable public vulnerable…

--

--

Simon Busch

Full Stack JS/TS @code4rena building the future of smart contract auditing. Solidity/blockchain security learner 🚀