{"content":{"title":"怎样开发智能合约中的时间锁","body":"这篇文章将会介绍智能合约中的时间锁是什么，并且讲解如何开发它。你将会开发一个智能合约，这个合约可以将 ERC-20 通证的铸造请求按时间排列。\r\n\r\n这个教程将会使用到：\r\n- [Foundry](https:\/\/github.com\/foundry-rs\/foundry)\r\n- [Solidity](https:\/\/docs.soliditylang.org\/)\r\n- [Ethereum](https:\/\/ethereum.org\/)\r\n\r\n教程的代码可以在这个 [GitHub Repo](https:\/\/github.com\/smartcontractkit\/smart-contract-examples\/tree\/main\/timelocked-contracts) 中找到。\r\n## 什么是智能合约的时间锁\r\n本质上，时间锁是用来将智能合约中的某个函数限制在一段时间内的代码。“if”语句就可以实现最简单的时间锁：\r\n```\r\nif (block.timestamp < _timelockTime) {\r\n\r\n    revert ErrorNotReady(block.timestamp, _timelockTime);\r\n\r\n}\r\n```\r\n## 时间锁的应用场景\r\n智能合约中的时间锁有很多潜在的应用场景，它们通常会被用在通证首次公开发行中，用于实现通证销售的一些功能。时间锁也可以被用来按照时间表授权投资资金使用，即用户只有在一段时间以后才可以取出资金。\r\n\r\n另一个可能的场景就是通过智能合约去实现遗嘱。使用 Chainlink Keepers，你可以周期性的检查遗嘱的主人是否还在，一旦死亡证明被发布，这个遗嘱的智能合约就会解锁。\r\n\r\n以上只是很少的一些应用案例，智能合约时间锁有很多种场景去使用。在这个案例中，我们会聚焦于一个 [ERC-20](https:\/\/eips.ethereum.org\/EIPS\/eip-20) 合约，用时间锁实现一个队列来铸造它。\r\n## 怎样创建一个智能合约时间锁\r\n在这个教程中，我们会使用 Foundry 来开发和测试 Solidity 合约。关于 Foundry 这个框架，你可以它的 [GitHub](https:\/\/github.com\/foundry-rs\/foundry#installation) 中找到更多的信息。\r\n### 初始化项目\r\n你可以使用 `forge init` 初始化项目。项目初始化完成后，`forge test` 命令会进行一次检查确保项目初始化的过程没有问题。\r\n```\r\n❯ forge init timelocked-contract\r\n\r\nInitializing \/Users\/rg\/Development\/timelocked-contract...\r\n\r\nInstalling ds-test in \"\/Users\/rg\/Development\/timelocked-contract\/lib\/ds-test\", (url: https:\/\/github.com\/dapphub\/ds-test, tag: None)\r\n\r\n    Installed ds-test\r\n\r\n    Initialized forge project.\r\n\r\n❯ cd timelocked-contract \r\n\r\n❯ forge test\r\n\r\n[⠒] Compiling...\r\n\r\n[⠰] Compiling 3 files with 0.8.10\r\n\r\n[⠔] Solc finished in 143.06ms\r\n\r\nCompiler run successful\r\n\r\n\r\n\r\n\r\nRunning 1 test for src\/test\/Contract.t.sol:ContractTest\r\n\r\n[PASS] testExample() (gas: 190)\r\n\r\nTest result: ok. 1 passed; 0 failed; finished in 469.71µs\r\n```\r\n### 创建测试\r\n\r\n\r\n你需要创建一些测试来确保智能合约可以实现时间锁的所有的要求。需要测试的主要功能就是下面这些：\r\n- 让通证的铸造操作加入队列\r\n- 一旦时间到来就进行铸造\r\n- 取消早在队列中的铸造操作\r\n\r\n除了这些功能以外，你还需要保证智能合约没有重复入列或入列之前铸造这些错误操作。\r\n\r\n当项目被初始化以后，你需要去运行这些测试，因为你需要这些测试用例来保证你的项目的实际执行与设想的没有偏差。这些测试存储在 `src\/test\/Contract.t.sol`中。在 Foundry 中，会使用测试的名字来表示这些测试应该是成功还是失败。比如说 `testThisShouldWork` 表示应该通过，而 `testFailShouldNotWork` 表示只有这个测试被 revert 的时候才会通过。\r\n\r\n还有一些其他的使用惯例。时间锁会基于一个队列，这个队列会使用 `_toAddress`, `_amount`, 和 `time` 这几个参数的哈希值，而  `keccak256` 会被用来计算它们的哈希值。\r\n```\r\n\/\/ Create hash of transaction data for use in the queue\r\n\r\nfunction generateTxnHash(\r\n\r\n    address _to,\r\n\r\n    uint256 _amount,\r\n\r\n    uint256 _timestamp\r\n\r\n) public pure returns (bytes32) {\r\n\r\n    return keccak256(abi.encode(_to, _amount, _timestamp));\r\n\r\n}\r\n```\r\n另外，你需要自己设置测试环境中的时间来模拟有多少时间过去。这点可以通过 Foundry 的 `CheatCode` 实现。\r\n```\r\ninterface CheatCodes {\r\n\r\n    function warp(uint256) external;\r\n\r\n}\r\n```\r\nwrap 函数可以让你设置当前的区块的时间戳。这个函数接受一个 uint 参数来生成新的时间戳。我们需要使用它给当前时间来“增加时间”，模拟时间的流逝。这个可以让我们在测试中按照预期提供时间锁功能所需要的变量。\r\n\r\n把 `src\/test\/Contract.t.sol` 中的内容替换为下面的代码：\r\n```\r\n\/\/ SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.10;\r\n\r\nimport \"ds-test\/test.sol\";\r\nimport \"..\/Contract.sol\";\r\n\r\ninterface CheatCodes {\r\n    function warp(uint256) external;\r\n}\r\n\r\ncontract ContractTest is DSTest {\r\n    \/\/ HEVM_ADDRESS is the pre-defined contract that contains the cheatcodes\r\n    CheatCodes constant cheats = CheatCodes(HEVM_ADDRESS);\r\n\r\n    Contract public c;\r\n    address toAddr = 0x1234567890123456789012345678901234567890;\r\n    function setUp() public {\r\n        c = new Contract();\r\n        c.queueMint(\r\n            toAddr,\r\n            100,\r\n            block.timestamp + 600\r\n        );\r\n    }\r\n\r\n    \/\/ Ensure you can't double queue\r\n    function testFailDoubleQueue() public {\r\n        c.queueMint(\r\n            toAddr,\r\n            100,\r\n            block.timestamp + 600\r\n        );\r\n    }\r\n\r\n    \/\/ Ensure you can't queue in the past\r\n    function testFailPastQueue() public {\r\n        c.queueMint(\r\n            toAddr,\r\n            100,\r\n            block.timestamp - 600\r\n        );\r\n    }\r\n\r\n    \/\/ Minting should work after the time has passed\r\n    function testMintAfterTen() public {\r\n        uint256 targetTime = block.timestamp + 600;\r\n        cheats.warp(targetTime);\r\n        c.executeMint(\r\n            toAddr,\r\n            100,\r\n            targetTime\r\n        );\r\n    }\r\n\r\n    \/\/ Minting should fail if you mint too soon\r\n    function testFailMintNow() public {\r\n        c.executeMint(\r\n            toAddr,\r\n            100,\r\n            block.timestamp + 600\r\n        );\r\n    }\r\n\r\n    \/\/ Minting should fail if you didn't queue\r\n    function testFailMintNonQueued() public {\r\n        c.executeMint(\r\n            toAddr,\r\n            999,\r\n            block.timestamp + 600\r\n        );\r\n    }\r\n\r\n    \/\/ Minting should fail if try to mint twice\r\n    function testFailDoubleMint() public {\r\n        uint256 targetTime = block.timestamp + 600;\r\n        cheats.warp(block.timestamp + 600);\r\n        c.executeMint(\r\n            toAddr,\r\n            100,\r\n            targetTime\r\n        );\r\n        c.executeMint(\r\n            toAddr,\r\n            100,\r\n            block.timestamp + 600\r\n        );\r\n    }\r\n\r\n    \/\/ Minting should fail if you try to mint too late\r\n    function testFailLateMint() public {\r\n        uint256 targetTime = block.timestamp + 600;\r\n        cheats.warp(block.timestamp + 600 + 1801);\r\n        emit log_uint(block.timestamp);\r\n        c.executeMint(\r\n            toAddr,\r\n            100,\r\n            targetTime\r\n        );\r\n    }\r\n\r\n    \/\/ you should be able to cancel a mint\r\n    function testCancelMint() public {\r\n        bytes32 txnHash = c.generateTxnHash(\r\n            toAddr,\r\n            100,\r\n            block.timestamp + 600\r\n        );\r\n        c.cancelMint(txnHash);\r\n    }\r\n\r\n    \/\/ you should be able to cancel a mint once but not twice\r\n    function testFailCancelMint() public {\r\n        bytes32 txnHash = c.generateTxnHash(\r\n            toAddr,\r\n            999,\r\n            block.timestamp + 600\r\n        );\r\n        c.cancelMint(txnHash);\r\n        c.cancelMint(txnHash);\r\n    }\r\n\r\n    \/\/ you shouldn't be able to cancel a mint that doesn't exist\r\n    function testFailCancelMintNonQueued() public {\r\n        bytes32 txnHash = c.generateTxnHash(\r\n            toAddr,\r\n            999,\r\n            block.timestamp + 600\r\n        );\r\n        c.cancelMint(txnHash);\r\n    }\r\n\r\n}\r\n```\r\n### 开发合约\r\n你现在应该可以执行命令 forge test 然后看到许多错误，现在就让我们使这些测试可以被通过。我们现在从一个最基础的 ERC-20 合约开始，所有的代码都存储在 `src\/Contract.sol` 中。\r\n```\r\n\/\/ SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.10;\r\n\r\nimport \"@openzeppelin\/contracts\/token\/ERC20\/ERC20.sol\";\r\nimport \"@openzeppelin\/contracts\/access\/Ownable.sol\";\r\n\r\ncontract Contract is ERC20, Ownable {\r\n    constructor() ERC20(\"TimeLock Token\", \"TLT\") {}\r\n}\r\n```\r\n这里在使用 OpenZeppelin 合约之前，你需要先安装它，并且将 Foundry 指向它们。\r\n运行以下命令安装这些合约：\r\n```\r\n❯ forge install openzeppelin\/openzeppelin-contracts\r\n```\r\n创建 `remappings.txt` 来映射这些 imports \r\n```\r\n@openzeppelin\/=lib\/openzeppelin-contracts\/\r\nds-test\/=lib\/ds-test\/src\/\r\n```\r\n这个 remapping 文件可以让你像在 Hardhat 或者 Remix 中一样使用像OpenZeppelin 合约这样的外部库，因为这个文件将 import 重新映射到了它们所在的文件夹。我通过 `forge install openzeppelin\/openzeppelin-contracts` 安装了 OpenZeppelin 合约，它们在这里会被用来创建 ERC-721 合约。\r\n\r\n如果一切顺利的话，你可以运行 `forge build` 来编译合约。\r\n\r\n完成上述操作以后，就可以写下面的智能合约。这个合约可以让你将一个铸造操作加入队列，然后在某个时间窗口执行这个铸造操作。\r\n```\r\n\/\/ SPDX-License-Identifier: UNLICENSED\r\npragma solidity 0.8.10;\r\n\r\nimport \"@openzeppelin\/contracts\/token\/ERC20\/ERC20.sol\";\r\nimport \"@openzeppelin\/contracts\/access\/Ownable.sol\";\r\n\r\ncontract Contract is ERC20, Ownable {\r\n    \/\/ Error Messages for the contract\r\n    error ErrorAlreadyQueued(bytes32 txnHash);\r\n    error ErrorNotQueued(bytes32 txnHash);\r\n    error ErrorTimeNotInRange(uint256 blockTimestmap, uint256 timestamp);\r\n    error ErrorNotReady(uint256 blockTimestmap, uint256 timestamp);\r\n    error ErrorTimeExpired(uint256 blockTimestamp, uint256 expiresAt);\r\n\r\n    \/\/ Queue Minting Event\r\n    event QueueMint(\r\n        bytes32 indexed txnHash,\r\n        address indexed to,\r\n        uint256 amount,\r\n        uint256 timestamp\r\n    );\r\n\r\n    \/\/ Mint Event\r\n    event ExecuteMint(\r\n        bytes32 indexed txnHash,\r\n        address indexed to,\r\n        uint256 amount,\r\n        uint256 timestamp\r\n    );\r\n\r\n    \/\/ Cancel Mint Event\r\n    event CancelMint(bytes32 indexed txnHash);\r\n\r\n\r\n    \/\/ Constants for minting window\r\n    uint256 public constant MIN_DELAY = 60; \/\/ 1 minute\r\n    uint256 public constant MAX_DELAY = 3600; \/\/ 1 hour\r\n    uint256 public constant GRACE_PERIOD = 1800; \/\/ 30 minutes\r\n\r\n    \/\/ Minting Queue\r\n    mapping(bytes32 => bool) public mintQueue;\r\n\r\n    constructor() ERC20(\"TimeLock Token\", \"TLT\") {}\r\n\r\n    \/\/ Create hash of transaction data for use in the queue\r\n    function generateTxnHash(\r\n        address _to,\r\n        uint256 _amount,\r\n        uint256 _timestamp\r\n    ) public pure returns (bytes32) {\r\n        return keccak256(abi.encode(_to, _amount, _timestamp));\r\n    }\r\n\r\n    \/\/ Queue a mint for a given address amount, and timestamp\r\n    function queueMint(\r\n        address _to,\r\n        uint256 _amount,\r\n        uint256 _timestamp\r\n    ) public onlyOwner {\r\n        \/\/ Generate the transaction hash\r\n        bytes32 txnHash = generateTxnHash(_to, _amount, _timestamp);\r\n\r\n        \/\/ Check if the transaction is already in the queue\r\n        if (mintQueue[txnHash]) {\r\n            revert ErrorAlreadyQueued(txnHash);\r\n        }\r\n\r\n        \/\/ Check if the time is in the range\r\n        if (\r\n            _timestamp < block.timestamp + MIN_DELAY ||\r\n            _timestamp > block.timestamp + MAX_DELAY\r\n        ) {\r\n            revert ErrorTimeNotInRange(_timestamp, block.timestamp);\r\n        }\r\n\r\n        \/\/ Queue the transaction\r\n        mintQueue[txnHash] = true;\r\n\r\n        \/\/ Emit the QueueMint event\r\n        emit QueueMint(txnHash, _to, _amount, _timestamp);\r\n    }\r\n\r\n    \/\/ Execute a mint for a given address, amount, and timestamp\r\n    function executeMint(\r\n        address _to,\r\n        uint256 _amount,\r\n        uint256 _timestamp\r\n    ) external onlyOwner {\r\n\r\n        \/\/ Generate the transaction hash\r\n        bytes32 txnHash = generateTxnHash(_to, _amount, _timestamp);\r\n\r\n        \/\/ Check if the transaction is in the queue\r\n        if (!mintQueue[txnHash]) {\r\n            revert ErrorNotQueued(txnHash);\r\n        }\r\n\r\n        \/\/ Check if the time has passed\r\n        if (block.timestamp < _timestamp) {\r\n            revert ErrorNotReady(block.timestamp, _timestamp);\r\n        }\r\n\r\n        \/\/ Check if the window has expired\r\n        if (block.timestamp > _timestamp + GRACE_PERIOD) {\r\n            revert ErrorTimeExpired(block.timestamp, _timestamp);\r\n        }\r\n\r\n        \/\/ Remove the transaction from the queue\r\n        mintQueue[txnHash] = false;\r\n        \r\n        \/\/ Execute the mint\r\n        mint(_to, _amount);\r\n        \r\n        \/\/ Emit the ExecuteMint event\r\n        emit ExecuteMint(txnHash, _to, _amount, _timestamp);\r\n    }\r\n\r\n\r\n    \/\/ Cancel a mint for a given transaction hash\r\n    function cancelMint(bytes32 _txnHash) external onlyOwner {\r\n        \/\/ Check if the transaction is in the queue\r\n        if (!mintQueue[_txnHash]) {\r\n            revert ErrorNotQueued(_txnHash);\r\n        }\r\n        \/\/ Remove the transaction from the queue\r\n        mintQueue[_txnHash] = false;\r\n        \/\/ Emit the CancelMint event\r\n        emit CancelMint(_txnHash);\r\n    }\r\n\r\n    \/\/ Mint tokens to a given address\r\n    function mint(address to, uint256 amount) internal {\r\n        _mint(to, amount);\r\n    }\r\n}\r\n```\r\n## 接下来可以做什么\r\n智能合约的时间锁非常有用，它们可以让合约内的交易变得更加安全和透明。但是时间锁无法自动触发，所以你需要在某个时间节点回来然后执行这个函数。想要让它们自己执行的话，就需要自动化你的合约。\r\n\r\n[Chainlink Keepers](https:\/\/chain.link\/keepers%20) 可以让你自动化智能合约中的函数。通过使用 Chainlink Keepers，你可以在某一些提前定义好的时间节点，让你智能合约中的函数自动执行。想要了解更多关于 Chainlink Keepers 的信息，请查看 [Keepers 文档](https:\/\/docs.chain.link\/docs\/chainlink-keepers\/job-scheduler\/%20)。\r\n\r\n您可以关注 Chainlink 预言机并且私信加入开发者社区，有大量关于智能合约的学习资料以及关于区块链的话题！"},"author":{"user":"https:\/\/learnblockchain.cn\/people\/398","address":null},"history":null,"timestamp":1663251037,"version":1}