The Withdrawal Pattern

Learn how the withdrawal pattern works in Solidity.

Withdrawal pattern is a security design pattern in Solidity that helps prevent reentrancy attacks. A reentrancy attack is a type of attack where an attacker can call a function multiple times in a single transaction, draining the contract’s balance.

The withdrawal pattern works by separating the process of requesting and withdrawing funds. First, the recipient of the funds calls a function to request the funds. This function marks the recipient’s balance as pending. The contract then emits an event to notify the recipient that they have pending funds. The recipient can then call a different function to withdraw their pending funds.

The withdrawal pattern is a best practice for transferring Ether within a smart contract after an interaction or impact. While calling transfer calls directly to move Ether is the most direct method, it’s discouraged owing to potential security considerations. Additional information on these issues can be found on the security concerns page.

To ensure the security and stability of smart contracts, the withdrawal pattern requires a careful method of processing Ether transfers. It’s especially important when dealing with financial applications, such as gaming or decentralized finance (DeFi) projects.

Implementing the withdrawal pattern

Here’s how the withdrawal pattern works in a contract inspired by notions like King of the Ether: ...