Skip to content

Withdrawal Locking

Let's extend our Smart Contract to do some locking.

You will see that it is very easy to let our code take care of some specific logic to allow/disallow certain actions.

Extend the Smart Contract

What we need is to store the block.timestamp somewhere. There are several methods to go about this, I prefer to let the user know how long is it locked. So, instead of storing the deposit-timestamp, I will store the lockedUntil timestamp. Let's see what happens here:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.1;

contract SendMoneyExample {

    uint public balanceReceived;
    uint public lockedUntil;

    function receiveMoney() public payable {
        balanceReceived += msg.value;
        lockedUntil = block.timestamp + 1 minutes;
    }

    function getBalance() public view returns(uint) {
        return address(this).balance;
    }

    function withdrawMoney() public {
        if(lockedUntil < block.timestamp) {
            address payable to = payable(msg.sender);
            to.transfer(getBalance());
        }
    }

    function withdrawMoneyTo(address payable _to) public {
        if(lockedUntil < block.timestamp) {
            _to.transfer(getBalance());
        }
    }
}

Deploy and Test the Smart Contract

Let's deploy the Smart Contract, same procedure as before:

  1. Deploy a new Instance version
  2. Remove the old Instance
  3. Send 1 Ether to the Smart Contract (don't forget the value field) by clicking on "receiveMoney"
  4. Check the Balance!

Alright, now what? Well, check the "lockedUntil" by clicking on the button. It will give you the timestamp until nothing happens when you click withdrawMoney or withdrawMoneyTo.

  1. Click "withdrawMoney" - and nothing happens. The Balance stays the same until 1 Minute passed since you hit "receiveMoney".

Try it yourself!

But doing nothing, no feedback, that's not really user-friendly. You will learn later about Exceptions: Require, Assert, Revert, how we can make this more user-friendly.

That's it for now, good job!


Last update: April 17, 2021