Skip to content

Hardhat 节点

Docker 镜像:https://hub.docker.com/r/fuming/hardhat-node

Docker Compose 启动:

yaml
services:
  hardhat-node:
    image: fuming/hardhat-node:latest
    container_name: hardhat-node-instance
    ports:
      - "8545:8545"

Nginx 反向代理

在Nginx中配置:

nginx
    location /hardhat {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_read_timeout 600s;  # Ensure long-lived WebSocket connections are handled
        
        proxy_pass http://host.docker.internal:8545/;
    }

访问 https://your-domain.com/hardhat即可正常使用Hardhat节点服务。

macOS 后台服务

/Library/LaunchDaemons/hardhat_node.plist

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN
        http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>hardhat_node</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Users/f/.nvm/versions/node/v22.14.0/bin/npx</string>
            <string>/Users/f/services/hardhat_node/node_modules/.bin/hardhat</string>
            <string>node</string>
            <string>--hostname</string>
            <string>127.0.0.1</string>
            <string>--port</string>
            <string>18545</string>
        </array>
        <key>WorkingDirectory</key>
        <string>/Users/f/services/hardhat_node</string>
        <key>EnvironmentVariables</key>
        <dict>
            <key>PATH</key>
            <string>/Users/f/.nvm/versions/node/v22.14.0/bin:/usr/local/bin:/usr/bin:/bin</string>
        </dict>
        <key>KeepAlive</key>
        <true/>
        <key>RunAtLoad</key>
        <true/>
        <key>StandardOutPath</key>
        <string>/var/log/hardhat_node.log</string>
        <key>StandardErrorPath</key>
        <string>/var/log/hardhat_node.log</string>
    </dict>
</plist>

未来时间戳的区块

在实际使用中发现,Hardhat 不允许相同时间戳的区块产生,因此如果交易频率过高,会导致未来时间戳区块的出现。合约中存在的时间逻辑会受此影响。多方查找后发现是因为hardhat 采用 NomicFoundation/edr 作为以太坊运行时,以太坊同样不允许区块拥有相同的时间戳,这是 Hardhat 模拟真实链行为的一种方式,但对做精准共识模拟、时间敏感测试时极其反直觉和不稳定

如果使用 Hardhat Network,可以通过设置 allowBlocksWithSameTimestamp 的方式来解决这个问题,但是官方文档并未说明这种方式是否适用于Hardhat Node

经过测试,这种方式是可以在 Hardhat Node 中解决这个问题,具体方式如下。

在运行npx hardhat node目录下的hardhat.config.js中,添加定义:

javascript
module.exports = {
    networks: {
        // 添加对 hardhat network 的配置
        hardhat: {
            allowBlocksWithSameTimestamp: true
        }
    }
};

如此配置之后,hardhat node即可支持相同时间戳的区块。

从 Ganache 迁移