blockchainsolidityreentrancy

Reentrancy Prevention


Is it good to update the state variable before hitting the external transaction to another contract, and event emission also in solidity to protect from reentrancy?

I am very confused realated to reentrancy prevention in solidity, the states variables need to be updated first before the call to the external contract. The emission of the events are also done before that external call or after that. If we do that before the external call, and then external call fails but the event has already been trigered. Please help me with this.


Solution

  • Yes, it is always recommended to update the state variables before the external call. Here, check the Checks-Effects-Interactions pattern to avoid re-entrancy attack.

    Regarding the event, if the function execution fails, event is not emitted. So, no need to worry for event.