跳转到主要内容
对于某些类型的测试,跳过时间是很有用的。这可以通过依赖 Virtual Environments 上可用的 2 个 Admin RPC 方法来实现:evm_setNextBlockTimestampevm_setNextBlockTimestamp

获取正确的时间

在交易或 eth_call 执行期间,当合约内访问 block.timestamp 时,其值取决于目标区块(latestpending 区块):
  • 对于 pending 区块block.timestamp == time.now() + adjustment_offset。这表示由时间调整方法调整后的当前时间。
  • 对于 latest 区块block.timestamp == latest_block.timestamp。这是最近挖掘区块的时间戳。
adjustment_offset 来自时间调整方法:
  1. evm_setNextBlockTimestamp: 将时间跳到下一个区块的时间戳:adjustment_offset = timestamp - time.now()
  2. evm_increaseTime: 按相对量向前推进时间。 adjustment_offset += increase_value

示例

按偏移量增加时间

showLineNumbers
VIRTUAL_TESTNET_RPC=https://YOUR-RPC-URL-HERE
curl -s -X POST \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "evm_increaseTime",
    "params": ["0xe10"],
    "id": 2
  }' "$VIRTUAL_TESTNET_RPC"

设置 pending 区块的时间戳

showLineNumbers
VIRTUAL_TESTNET_RPC=https://YOUR-RPC-URL-HERE

# Get the current date in Unix timestamp format
current_date=$(date +%s)

# Use evm_setTime to set the block time to today (current timestamp)
curl -s -X POST \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "evm_setNextBlockTimestamp",
    "params": ["'"$current_date"'"],
    "id": 3
  }' "$VIRTUAL_TESTNET_RPC"