Speed Dump Pattern in Solidity

Delay in withdraw can save smart contract from malicious activity. Here is the example how you can apply a delay in smart contract.

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract speedbumpPattern{
    
    uint constant withdrawalWaitPeriod = 20 days;
    
    struct withdrawalRequest{
        uint amount;
        uint time;
    }
    
    mapping( address => uint ) balance;
    
    mapping( address => withdrawalRequest ) withdrawalRequests;
    
    function RequestForWithdraw(uint _amount)public {
        require(_amount <= balance[msg.sender] && _amount > 0,"Insufficient Balance");
        
        balance[msg.sender] -= _amount;
        
        withdrawalRequests[msg.sender] = withdrawalRequest({
            amount: _amount,
            time: block.timestamp
        });
    } 
    
    function withdraw()public {
        require(withdrawalRequests[msg.sender].amount > 0 && block.timestamp > withdrawalRequests[msg.sender].time + withdrawalWaitPeriod ,"Error in balance or Period for withdraw");
    
        uint withdrawalAmount = withdrawalRequests[msg.sender].amount;
        withdrawalRequests[msg.sender].amount = 0;
        withdrawalRequests[msg.sender].time = 0;
        
        require(payable(msg.sender).send(withdrawalAmount));
        
        
    }
    
}

By Shabair

Frontend | Blockchain | Smart Contract Developer