0

How are these 2 functions different in terms of security, there was a question on a forum and i don't understand

function emergencyWithdraw(uint256 _pid) public {
    PoolInfo storage pool = poolInfo[_pid];
    UserInfo storage user = userInfo[_pid][msg.sender];
    pool.token.safeTransfer(address(msg.sender), user.amount);
    emit EmergencyWithdraw(msg.sender, _pid, user.amount);
    user.amount = 0;
    user.rewardDebt = 0;
}

function emergencyWithdraw(uint256 _pid) public {
    PoolInfo storage pool = poolInfo[_pid];
    UserInfo storage user = userInfo[_pid][msg.sender];
    user.amount = 0;
    user.rewardDebt = 0;
    pool.token.safeTransfer(address(msg.sender), user.amount);
    emit EmergencyWithdraw(msg.sender, _pid, user.amount);
    
}

NOTE: I'm new to solidity

1 Answer 1

1

So lets imagine that the pool.token contract in the first function is somehow compromised and now the pool.token.safeTransfer() function is not only transferring the token but also calling again the emergencyWithdraw(). When the function is entered for second time the user.amount will not be 0 and the user will get 2*user.amount instead of once and this will continue untill all tokens are transferred or until the gas is depleted. However the second function is setting user.amount = 0 and even if the contract is compromised every entrance after the first will transfer 0 tokens to the msg.sender which is okay.

This is called Reentrancy attack. Here you can check further explanations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.