if 语句在一段时间后激活一个函数(solidity)

if statement to activate a function after a time period (solidity)

我希望在合约部署 6 分钟(360 秒)后激活以下功能,因为我的任务需要提款锁。我应该将 if (block.timestamp > 360) 放在函数之前还是在函数内部剩余代码之前?

 function withdraw(uint256 amount) external updateReward(msg.sender) nonReentrant {
        if (block.timestamp > 360) {
        s_totalSupply -= amount;
        s_balances[msg.sender] -= amount;
        emit WithdrewStake(msg.sender, amount);
        // transfer: send tokens from contract back to msg.sender.
        bool success = s_stakingToken.transfer(msg.sender, amount);
        if (!success) {
            revert TransferFailed(); // revert resets everything done in a failed transaction.
        }}
    }

但我什至不确定 if (block.timestamp > 360) 是否适合这种情况。

兄弟帮你想出来了:

pragma solidity ^0.8.7;
import "hardhat/console.sol";
contract TimeTest{
    uint256 public initialTime;
    constructor () public{
        initialTime = block.timestamp;
    }
    function withdraw() public {
        uint256 nowTime = block.timestamp-initialTime; // time between deployment of contract and now.
        console.log(nowTime);
        if (nowTime > 60) {
            console.log("Time is up");
        }
    }

}

你必须这样做的原因是因为block.timestamp不代表自部署合约以来的时间,而是自unix纪元以来的时间。变量名有点误导。

您可以在此处找到更多信息:https://docs.soliditylang.org/en/v0.8.13/units-and-global-variables.html

或此处:https://programtheblockchain.com/posts/2018/01/12/writing-a-contract-that-handles-time/(只知道自版本 0.0.7 以来“now”不再存在。“now”等同于“block.timestamp”。但教程仍然有效,如果您将“现在”替换为“block.timestamp”。