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:

  • The contract keeps track of the wealthiest address, which was originally set to the contract creator’s address.

  • Participants can send Ether to the contract, and if their balance exceeds the current wealthiest address, they become the deal’s new wealthiest participant.

  • The contract stipulates that the richest address has the right to withdraw their earnings at any moment.

  • If a new person becomes the richest, the prior richest participant may withdraw their Ether as well.

Get hands-on with 1200+ tech skills courses.