Solidity

測試依賴於 block.timestamp 的可靠性函式

  • March 28, 2022

我正在為 Solidity 中的代幣質押編寫智能合約。這是一個範常式式碼片段:

contract Test {

uint lastStakeTime;

function withdraw () {
 if (differenceBetween(lastStakeTime, block.timestamp, ONE_MONTH) {
    revert ("cannot withdraw before one month");
 }
 // Do something here
}

}

函式檢查 1 個月的時間差作為撤回條件並恢復。如何使用 Truffle 和 web3js 進行模擬?

我需要通過以下測試:

it ('cannot withdraw before one month', async() => {
   
   // expecting to revert
   truffleAssert.reverts(Test.withraw(withdrawAmount, {from: accounts[0]}), 
   'cannot withdraw before one month');
 })

你可以下載 Openzeppelin test-helpers這裡是文件

幫助將不同的時間單位轉換為秒。可用的助手有:秒、分鐘、小時、天、周和年

例子:await time.increase(time.duration.hours(1));

引用自:https://ethereum.stackexchange.com/questions/124890