Read-Only Reentrancy

Gideon Shadrack

Smart Contract Engineer
Technical Writer
Solidity Engineer
Medium
Remix IDE
In essence, read-only reentrancy refers to a situation where a view-only function returns misleading values due to an outdated state. This phenomenon occurs in smart contracts when external functions are triggered while the contract remains in an outdated state. Consequently, view functions, designed to read the state, provide values based on the old, un-updated state.
The issue arises in scenarios involving the risk of reentrancy in a contract, especially during the execution of external functions. Even if the primary function modifying the state is protected against reentrancy attacks with a ReentrancyGuard, a malicious actor can exploit the contract by reentering through a view-only function. This exploitation results in the view function returning data that inaccurately represents the current state of the contract.

Example Scenario:

Let’s consider a simple staking contract where users deposit a staking token to earn rewards. When a user deposits, the pool undergoes an update, and the pending reward is calculated and transferred. However, if the rewardDebt variable (tracking the accounted reward for each user) isn’t updated before the transfer, there’s a potential for exploitation. Despite the function being guarded with a ReentrancyGuard, a malicious user could call the getPendingRewards function right after receiving the pending rewards but before the rewardDebt is updated. This would display an inflated reward value, misleading the user about their pending rewards after the deposit.

Preventing Read-Only Reentrancy:

The key to preventing read-only reentrancy is to adhere to the well-established “checks-effects-interactions” pattern in smart contract development. This pattern involves carefully organizing the code to first perform checks, then execute state-altering operations, and finally interact with external entities. In an upcoming post, I will delve into the details of this pattern.
Partner With Gideon
View Services

More Projects by Gideon