-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
45dabcd
commit 84a80b0
Showing
4 changed files
with
60 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# 环境与内置函数 | ||
|
||
## 环境 | ||
|
||
您可以通过Liquid中的环境模块访问某些区块链执行环境信息(如合约的调用者地址)。通过如下形式可在合约方法中使用环境模块中的接口: | ||
|
||
```rust | ||
self.env().get_caller(); | ||
``` | ||
|
||
其中`self`是执行合约方法时当前合约对象的引用。在编译合约时,Liquid会自动为您的合约实现一个名为`env`的私有方法。`env`方法不接受任何参数,但会返回一个环境访问器对象, 您无需关心环境访问器的具体实现细节,只需要知道能且仅能通过环境访问器访问区块链执行环境信息。获得环境访问器后,您便可以在其上调用您所需要接口了。目前Liquid中提供了以下访问区块链执行环境信息的接口: | ||
|
||
- `get_caller` | ||
|
||
签名:`get_caller() -> Address` | ||
|
||
功能:获取直接调用当前合约的调用者的地址。 | ||
|
||
- `emit` | ||
|
||
签名:`emit<E>(event: E)`,其中`E`为事件类型,即您标注了`#[liquid(event)]`的结构体类型(可参考[事件](./event.html)) | ||
|
||
功能:触发一个事件,事件会以日志的形式记录在交易的回执中。 | ||
|
||
每次调用环境相关的的接口时,都需要消耗一个环境访问器对象,因此您不能通过如下方式复用环境访问器对象: | ||
|
||
```rust | ||
// 环境访问器对象无法复用,编译报错 | ||
let env_access = &self.env(); | ||
let caller = env_access.get_caller(); | ||
env_access.emit(some_event); | ||
``` | ||
|
||
正确的方式每次调用环境相关的接口时都创建一个环境访问器对象,环境访问器极为轻量,因为您无需担心创建时的性能开销: | ||
|
||
```rust | ||
let caller = self.env().get_caller(); | ||
self.env().emit(some_event); | ||
``` | ||
|
||
## 内置函数 | ||
|
||
Liquid提供了一些基本的内置函数。在合约编译时,Liquid会自动导入这些函数,因此您可以在合约中直接使用这些函数。内置函数包括: | ||
|
||
- `require` | ||
|
||
签名:`require<Q>(expr: bool, msg: Q)`,其中泛型参数Q需要实现`AsRef<str>`,常见的`str`、`String`等类型均可以作为`msg`参数的类型 | ||
|
||
功能:断言函数,用于判断某个值为布尔类型的表达式`expr`是否成立。若成立,合约继续向下执行;若不成立,则引发交易回滚,并向外抛出所指定的异常信息`msg`,异常信息会随着交易回执一并返回至用户。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters