调试
Tact 中调试智能合约常用的函数列表。
require
fun require(condition: Bool, error: String);
检查 condition
并抛出错误,如果 condition
为 false
,则从 error
消息中生成 exit code。 除此之外,别无其他作用。
生成退出码的算法如下:
- 首先,获取
错误
报文String
的SHA-256 哈希值。 - 然后,它的值被作为一个32位的 大端 数字读取,计算方式是对 取模后加上 ,按此顺序进行。
- 最后,它将被放入
.md
编译报告文件,该文件与其他编译工件一起存放在项目的outputs/
或build/
目录中。
保证生成的退出码不在为 TVM 和 Tact 合约错误保留的常用 范围内,这样就可以将退出码与 require()
和任何其他 标准退出码 区分开来。
示例用法:
// now() has to return a value greater than 1000, otherwise an error message will be thrownrequire(now() > 1000, "We're in the first 1000 seconds of 1 January 1970!");
try { // The following will never be true, so this require would always throw require(now() < -1, "Time is an illusion. Lunchtime doubly so.");} catch (e) { // e will be outside of range 0-255 dump(e);}
dump
fun dump(arg);
将参数 arg
打印到合约的调试控制台。 仅当配置文件 中的 “debug “选项设置为 true
时才进行评估,否则不执行任何操作。
可应用于下列类型和值:
Int
Bool
Address
Cell
,Builder
或Slice
String
或StringBuilder
map<K, V>
- Optionals 和
null
value void
,当函数没有定义返回值时隐式返回
示例用法:
// Intdump(42);
// Booldump(true);dump(false);
// Addressdump(myAddress());
// Cell, Builder or Slicedump(emptyCell()); // Celldump(beginCell()); // Builderdump(emptySlice()); // Slice
// String or StringBuilderdump("Hello, my name is..."); // Stringdump(beginTailString()); // StringBuilder
// Mapslet m: map<Int, Int> = emptyMap();m.set(2 + 2, 4);dump(m);
// Special valuesdump(null);dump(emit("msg".asComment())); // As emit() function doesn't return a value, dump() would print #DEBUG#: void.
dumpStack
fun dumpStack();
将 持久状态变量的所有值打印到合约的调试控制台。 仅当配置文件 中的 “debug “选项设置为 true
时才进行评估,否则不执行任何操作。
用法示例:
contract DumpsterFire { var1: Int = 0; var2: Int = 5;
receive() { dumpStack(); // would print 0 5 }}
throw
fun throw(code: Int);
是 nativeThrow()
的别名。
nativeThrow
fun nativeThrow(code: Int);
抛出错误代码等于 code
的异常。 当前上下文的执行将停止(nativeThrow
后的语句将不会执行),控制权将传递给调用栈中的第一个try...catch
块。 如果调用者函数中不存在 try
或 try...catch
块,TVM将终止事务。
试图在 范围之外指定 code
时,会出现 exit code 5异常:Integer out of expected range
。
示例用法:
fun thisWillTerminate() { nativeThrow(1042); // throwing with exit code 1042}
fun butThisDoesNot() { try { nativeThrow(1042); // throwing with exit code 1042 }
// ... follow-up logic ...}
nativeThrowIf
fun nativeThrowIf(code: Int, condition: Bool);
类似于 nativeThrow()
,但会在 condition
等于 true
时有条件地抛出异常。 否则不会抛出。
试图在 范围之外指定 code
时,会出现 exit code 5 异常:Integer out of expected range
。
示例用法:
fun thisWillTerminate() { nativeThrowIf(1042, true); // throwing with exit code 1042}
fun butThisDoesNot() { try { nativeThrowIf(1042, true); // throwing with exit code 1042 } // ... follow-up logic ...}
nativeThrowUnless
fun nativeThrowUnless(code: Int, condition: Bool);
类似于 nativeThrow()
,但会在 condition
等于 false
时有条件地抛出异常。 否则不会抛出。
试图在 范围之外指定 code
时,会出现 exit code 5 异常:Integer out of expected range
。
使用示例:
fun thisWillTerminate() { nativeThrowUnless(1042, false); // throwing with exit code 1042}
fun butThisDoesNot() { try { nativeThrowUnless(1042, false); // throwing with exit code 1042 } // ... follow-up logic ...}