Canister 入门

236 阅读1分钟

Canister 智能合约的结构

image.png

生命周期

image.png

  1. 已创建 (Created),无代码,无内存,不能接收和发送消息
  2. 正常运行 (Running) ,可以接收和发送消息
  3. 预备停止 (Stopping) ,只允许收到之前发送消息的回复
  4. 停止运行 (Stopped),此时可以升级代码

Canister的方法调用

Canister只有接收到消息才会开始运行,每个消息相当于一次异步调用。只有调用完成之后,状态才会保存。

Update和Query 的区别

Update(更新调用)Query(查询调用)
共识不要
安全性
响应时间2-3秒100毫秒
改变状态持久化不保存
执行顺序顺序并行
调用方式2步1步

给Canister发送消息

image.png

消息的返回结果

image.png

消息处理逻辑

image.png

示例代码

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;
      }
  }

}