Blockchain/Solidity

Send Ether to the Smart Contract (2) 및 block.timestamp 개념 - 공부하는 도비

DOVISH WISDOM 2023. 2. 1. 21:46  
728x90
반응형

저번 피드에서 스마트 계약으로 이더를 보내는 방법을 알아보았습니다. 

2023.01.04 - [Blockchain/Solidity] - Send Ether to the Smart Contract (1) 및 payable 개념 - 공부하는 도비

 

Send Ether to the Smart Contract (1) 및 payable 개념 - 공부하는 도비

Solidity에서 ether를 전송하는 스마트 컨트랙트를 작성하기 위해선, payable의 개념이 필수적입니다. "payable means that you can transfer ether with the transaction." payable엔 두 가지 종류가 있습니다. 1. address payab

yang-wistory1009.tistory.com

오늘은 block.timestamp를 이용해서 이더를 입금하고, 바로 인출하지 못하도록 인출 잠금 시간을 설정해 보겠습니다. 


* block.timestamp *

유닉스 시간으로 현재 블록의 시간을 의미합니다. (current block timestamp as seconds since unix epoch)

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract temp {

    function viewBlockTime() public view returns (uint) {
        return block.timestamp;
        
    } 
}


* send/withdraw ether to the smart contract *

현재의 예시는 시간에 상관없이 언제든 스마트 계약에 있는 이더를 출금할 수 있습니다.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract SendMoneyEx {

    uint public balanceReceived;

    function receiveMoney() public payable {
        balanceReceived += msg.value;       // msg.value : number of wei sent with the message 
    }

    function getBalance() public view returns (uint) {
        return address(this).balance;   // address(this) converts the Smart Contract instance to an address. 
    }
    
    function withdrawMoney() public{
        address payable to = payable(msg.sender);
        to.transfer(getBalance());
        balanceReceived = 0;
    }
    
    function withdrawMoneyTo(address payable _to, uint256 amount) public {
        require(address(this).balance >= amount, "ERROR");
        _to.transfer(amount);
        balanceReceived -= amount;
    }
}

 

위 코드에 block.timestamp를 추가하여 입금 1분 후, 1시간 후 등등 후에 출금이 가능하도록 코드를 수정해보겠습니다. 


* withdrawal locking with block.timestamp * 

1. receiveMoney() 함수가 실행되면, lockedTime 변수에 현재 블록의 시간 + 1분이라는 값이 저장

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract SendMoneyEx {

    uint public balanceReceived;
    uint public lockedTime;

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

  
}

ether를 전송 후, lockedTime을 눌렀을 때

2. lockedTime이 block.timestamp보다 작으면 오류 발생

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract SendMoneyEx {

    uint public balanceReceived;
    uint public lockedTime;


    function receiveMoney() public payable {
        balanceReceived += msg.value;       // msg.value : number of wei sent with the message 
        lockedTime = block.timestamp + 1 minutes;   

    }

    function getBalance() public view returns (uint) {
        return address(this).balance;   // address(this) converts the Smart Contract instance to an address. 
                                        // So, this line essentially returns the amount of Ether that are stored on the Smart Contract itself.
    }
    
    function withdrawMoney() public{
        // block.timestamp : current block timestamp as seconds since unix epoch 
        require(lockedTime < block.timestamp, "ERROR");        
        address payable to = payable(msg.sender);
        to.transfer(getBalance());
        balanceReceived = 0;

    }
    
    function withdrawMoneyTo(address payable _to, uint256 amount) public {
        require(address(this).balance >= amount && lockedTime < block.timestamp, "ERROR");
        _to.transfer(amount);
        balanceReceived -= amount;

    }


}

require 조건에 충족하지 않고, withdraw함수를 실행시켰을 때 결과

require 조건에 충족했을 땐, withdrawMoney()함수가 정상적으로 실행이 됩니다. 


* Time Units * 

출처 :&nbsp;https://docs.soliditylang.org/en/v0.5.3/units-and-global-variables.html?#time-units

 


* require *

2023.01.02 - [Blockchain/Solidity] - require() 사용 - 공부하는 도비

 

require() 사용 - 공부하는 도비

Solidity는 에러를 제어하기 위해 다양한 함수를 제공하고, 일반적으로 에러가 발생하면 원래의 상태로 돌아갑니다. 에러를 컨트롤하기 위해서, 다음과 같은 메소드들이 있습니다. ● require(bool con

yang-wistory1009.tistory.com

 

반응형