Canister 智能合约的结构
生命周期
- 已创建 (Created),无代码,无内存,不能接收和发送消息
- 正常运行 (Running) ,可以接收和发送消息
- 预备停止 (Stopping) ,只允许收到之前发送消息的回复
- 停止运行 (Stopped),此时可以升级代码
Canister的方法调用
Canister只有接收到消息才会开始运行,每个消息相当于一次异步调用。只有调用完成之后,状态才会保存。
Update和Query 的区别
| Update(更新调用) | Query(查询调用) | |
|---|---|---|
| 共识 | 要 | 不要 |
| 安全性 | 高 | 低 |
| 响应时间 | 2-3秒 | 100毫秒 |
| 改变状态 | 持久化 | 不保存 |
| 执行顺序 | 顺序 | 并行 |
| 调用方式 | 2步 | 1步 |
给Canister发送消息
消息的返回结果
消息处理逻辑
示例代码
import Text "mo:base/Text";
import Nat "mo:base/Nat";
import Debug "mo:base/Debug";
actor Counter {
stable var currentValue : Nat = 0;
// Increment the counter with the increment function.
public func increment() : async () {
currentValue += 1;
};
// Read the counter value with a get function.
public query func get() : async Nat {
currentValue
};
// Write an arbitrary value with a set function.
public func set(n: Nat) : async () {
currentValue := n;
};
type HttpRequest = {
body: Blob;
headers: [HeaderField];
method: Text;
url: Text;
};
type HttpResponse = {
body: Blob;
headers: [HeaderField];
status_code: Nat16 ;
};
type HeaderField = (Text, Text);
public query func http_request(arg:HttpRequest) : async HttpResponse {
//获取currentValue的值
let counter = Nat.toText(currentValue);
Debug.print(counter);
{
body= Text.encodeUtf8("counter:" # counter# ",bye");
headers= [];
status_code= 200;
}
}
}