console 调试合约
本章学习如何使用 console
调试智能合约。
通过 hardhat
框架,我们不仅可以编写脚本调试合约,而且还可以在 solidity
代码中直接调试合约。
1. 使用 console.log
hardhat
提供了一个库合约 console.sol
。使用这个库合约,我们就可以在 solidity
代码中直接调用 console.log()
,来打印日志信息和合约变量。
在我们的合约中使用 console.log
,必须先导入 hardhat/console.log
。
示例代码:
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // 引入 console 库合约 import "hardhat/console.sol"; contract Calculator { // 加法 function add(uuint256 a, uuint256 b) external pure returns(uuint256) { // 打印变量a,b console.log("a=%s,b=%s",a,b); return a+b; } // 减法 function sub(uuint256 a, uuint256 b) external pure returns(uuint256) { // 打印变量a,b console.log("a=%s,b=%s",a,b); return a-b; } }
其中,console.log
中的格式化字符,比如 %s, %d,它的用法与 node.js
中 util.format
完全一致。
2. 运行测试
合约加入了 console.log
语句后,运行自动测试脚本的时候,将会输出日志记录:
npx hardhat test
运行结果:
Calculator contract a=5,b=3 ✔ should add two numbers correctly (2072ms) a=10,b=4 ✔ should subtract two numbers correctly 2 passing (2s)
其中 a=5,b=3 和 a=10,b=4,就是由合约输出的内容。