Motoko 智能合约编程语言

Motoko programming language

Notice:The Motoko programming language continues to evolve with each release of the IC SDK and with ongoing updates to the Motoko compiler. Check back regularly to try new features and see what’s changed.  注意:Motoko 编程语言随着 IC SDK 的每个版本以及 Motoko 编译器的不断更新而不断发展。 定期回来尝试新功能并查看发生了什么变化。

What is Motoko?

Motoko is a programming language designed specifically for the Internet Computer. Motoko is a language with all the usual features you would expect from a modern programming language, such as strong typing, automatic memory management, generics, type inference and others.

Motoko 是一种专门为互联网计算机设计的编程语言。 Motoko 是一种具有现代编程语言所期望的所有常见功能的语言,例如强类型、自动内存管理、泛型、类型推断等。

For concurrency Motoko uses the actor model: a computational model for concurrent and distributed systems. Each actor is an autonomous entity which encapsulates state and behavior, and communicates with other actors exclusively through asynchronous message passing. You will learn more about actors later in the tutorial.

对于并发性,Motoko 使用actor模型:并发和分布式系统的计算模型。 每个actor都是一个自治实体,它封装状态和行为,并通过异步消息传递专门与其它actor进行通信。

Motoko is compiled into WebAssembly, which is then executed by the Internet Computer's virtual machine. This means that Motoko is not the only language that can be used to write smart contracts for the Internet Computer. However, Motoko has been designed with the specific requirements of the platform in mind, making it the recommended language for writing smart contracts.

Motoko 被编译成 WebAssembly,然后由互联网计算机的虚拟机执行。 这意味着 Motoko 并不是唯一可用于为互联网计算机编写智能合约的语言。 然而,Motoko 在设计时考虑了平台的具体要求,使其成为编写智能合约的推荐语言。


The Motoko programming language is a new, modern and type safe language for developers who want to build the next generation of distributed applications to run on the Internet Computer blockchain network. Motoko is specifically designed to support the unique features of the Internet Computer and to provide a familiar yet robust programming environment. As a new language, Motoko is constantly evolving with support for new features and other improvements.  

Motoko 编程语言是一种新型、现代且类型安全的语言,适用于想要构建下一代分布式应用程序以在互联网计算机区块链网络上运行的开发人员。 Motoko 专门设计用于支持互联网计算机的独特功能并提供熟悉但强大的编程环境。 作为一种新语言,Motoko 不断发展,支持新功能和其他改进。

The Motoko compiler, documentation and other tooling is open source and released under the Apache 2.0 license. Contributions are welcome.

Motoko 编译器、文档和其他工具是开源的,并根据 Apache 2.0 许可证发布。 欢迎贡献。

Native canister smart contract support

原生Canister容器智能合约支持​

Motoko has native support for Internet Computer canister smart contracts. Motoko 原生支持互联网计算机canister 容器智能合约编程。

A canister smart contract (or canister for short) is expressed as a Motoko actor. An actor is an autonomous object that fully encapsulates its state and communicates with other actors only through asynchronous messages.

Canister 智能合约(或简称 Canister)被表示为 Motoko actor。 Actor 是一个自治对象,完全封装其状态并仅通过异步消息与其它Actor 进行通信。

For example, this code defines a stateful Counter actor.  例如,此代码定义了一个有状态的 Counter actor。

actor {
     var value = 0;
     public func inc() : async Nat {
     value += 1;
     return value;
     };
}

Its single public function, inc(), can be invoked by this and other actors, to both update and read the current state of its private field value.

它的单个公共函数 inc() 可以由该actor和其它actors调用,以更新和读取其私有字段值的当前状态。

Code sequentially in direct style

以直接方式顺序编码

On the Internet Computer, canisters can communicate with other canisters by sending asynchronous messages. 在 Internet 计算机上,canisters容器可以通过发送异步消息与其它容器进行通信。

Asynchronous programming is hard, so Motoko enables you to author asynchronous code in much simpler, sequential style. Asynchronous messages are function calls that return a future, and the await construct allows you to suspend execution until a future has completed. This simple feature avoids the "callback hell" of explicit asynchronous programming in other languages.

异步编程很困难,因此 Motoko 使程序能够以更简单、顺序的方式编写异步代码。 异步消息是返回 future 的函数调用,await 结构允许程序暂停执行,直到 future 完成。 这个简单的功能避免了其它语言中显式异步编程的“回调地狱”。

actor {

  var last = 1;

  public func next() : async Nat {
    last *= await Counter.inc();
    return last;
  }
};

ignore await Factorial.next();
ignore await Factorial.next();
await Factorial.next();

Modern type system  现代类型系统

Motoko has been designed to be intuitive to those familiar with JavaScript and other popular languages, but offers modern features such as sound structural types, generics, variant types, and statically checked pattern matching.

Motoko 的设计对于熟悉 JavaScript 和其它流行语言的人来说是直观的,但提供了现代功能,例如健全的结构类型、泛型、变体类型和静态检查模式匹配。

type Tree<T> = {
  #leaf : T;
  #branch : {left : Tree<T>; right : Tree<T>};
};

func iterTree<T>(tree : Tree<T>, f : T -> ()) {
  switch (tree) {
    case (#leaf(x)) { f(x) };
    case (#branch{left; right}) {
      iterTree(left, f);
      iterTree(right, f);
    };
  }
};

// Compute the sum of all leaf nodes in a tree
let tree = #branch { left = #leaf 1; right = #leaf 2 };
var sum = 0;
iterTree<Nat>(tree, func (leaf) { sum += leaf });
sum

Autogenerated IDL files  IDL文件自动生成

A Motoko actor always presents a typed interface to its clients as a suite of named functions with argument and (future) result types.

Motoko actor 始终向其客户端呈现一个类型化接口,作为一组具有参数和(future)结果类型的命名函数。

The Motoko compiler (and SDK) can emit this interface in a language neutral format called Candid, so other canisters, browser resident code and smart phone apps that support Candid can use the actor’s services. The Motoko compiler can consume and produce Candid files, allowing Motoko to seamlessly interact with canisters implemented in other programming languages (provided they support Candid).

Motoko 编译器(和 SDK)可以以一种称为 Candid 的语言中性格式导出此界面,因此支持 Candid 的其它容器、浏览器驻留代码和智能手机应用程序可以使用该actor的服务。 Motoko 编译器可以使用和生成 Candid 文件,从而允许 Motoko 与其它编程语言实现的容器无缝交互(前提是它们支持 Candid)。

For example, the previous Motoko Counter actor has the following Candid interface:

例如,之前的 Motoko Counter actor 有以下 Candid 界面:

service Counter : {
  inc : () -> (nat);
}

Orthogonal persistence 正交持久性储存

The Internet Computer persists the memory and other state of your canister as it executes. Thus the state of a Motoko actor, including its in-memory data structures, survive indefinitely. Actor state does not need to be explicitly "restored" and "saved" to external storage, with every message.

互联网计算机在执行时会保留canister容器的内存和其它状态。 因此,Motoko actor 的状态,包括其内存中的数据结构,可以无限期地保存。 Actor 状态不需要针对每条消息显式“恢复”和“保存”到外部存储。

For example, in the following Registry actor (canister), that assigns sequential IDs to textual names, the state of the hash table is preserved across calls, even though the state of the actor is replicated across many Internet Computer node machines, and typically not resident in memory.

例如,在以下注册表参与者(canister)中,它将连续 ID 分配给文本名称,哈希表的状态在调用之间保留,即使actor的状态在许多互联网计算机节点计算机上复制,并且通常不会 常驻记忆中。

import Text "mo:base/Text";
import Map "mo:base/HashMap";

actor {

     let map = Map.HashMap<Text, Nat>(10, Text.equal, Text.hash);

     public func register(name : Text) : async () {
     switch (map.get(name)) {
       case null {
                 map.put(name, map.size());
          };
       case (?id) { };
    }
  };

  public func lookup(name : Text) : async ?Nat {
    map.get(name);
  };
};

await Registry.register("hello");
(await Registry.lookup("hello"), await Registry.lookup("world"))

Upgrades 程序升级

Motoko provides numerous features to help you leverage orthogonal persistence, including language features that allow you to retain a canister’s data as you upgrade the code of the canister.

Motoko 提供了许多功能来帮助程序利用正交持久性,包括允许程序在升级canister容器代码时保留canister容器数据的语言功能。


For example, Motoko lets you declare certain variables as stable. The values of stable variables are automatically preserved across canister upgrades.

例如,Motoko 允许程序将某些变量声明为稳定的。 稳定变量的值会在canister容器升级过程中自动保留。

Consider a stable counter:

actor {

  stable var value = 0;

  public func inc() : async Nat {
    value += 1;
    return value;
  };
}

It can be installed, incremented n times, and then upgraded, without interruption, to, for example, the richer implementation:

它可以安装、递增 n 次,然后不间断地升级到例如更丰富的实现:

actor {

  stable var value = 0;

  public func inc() : async Nat {
    value += 1;
    return value;
  };

  public func reset() : async () {
    value := 0;
  }
}

Because value was declared stable, the current state, n, of the service is retained after the upgrade. Counting will continue from n, not restart from 0.

由于值已声明为稳定 :stable,因此升级后将保留服务的当前状态 n。 计数将从 n 继续,而不是从 0 重新开始。


Because the new interface is compatible with the previous one, existing clients referencing the canister will continue to work, but new clients will be able to exploit its upgraded functionality (the additional reset function).

由于新界面与之前的界面兼容,因此引用该容器的现有客户端将继续工作,但新客户端将能够利用其升级后的功能(附加重置功能)。

For scenarios that can’t be solved using stable variables alone, Motoko provides user-definable upgrade hooks that run immediately before and after upgrade, and allow you to migrate arbitrary state to stable variables.

对于无法单独使用稳定变量解决的场景,Motoko 提供了用户可定义的升级挂钩,这些挂钩在升级之前和之后立即运行,并允许程序将任意状态迁移到稳定变量。

And more …​ 更多功能……

Motoko provides many other developer productivity features, including subtyping, arbitrary precision arithmetic and garbage collection.

 Motoko 提供了许多其他开发人员生产力功能,包括子类型、任意精度算术和内存垃圾收集。

Motoko is not, and is not intended to be, the only language for implementing canister smart contracts. If it doesn’t suit your needs, there is a canister development kit (CDK) for the Rust programming language. Our goal is to enable any language (with a compiler that targets WebAssembly) to be able to produce canister smart contracts that run on the Internet Computer and interoperate with other, perhaps foreign, canister smart contracts through language neutral Candid interfaces.

Motoko 不是、也无意成为实现容器智能合约的唯一语言。 如果它不能满足程序的需求,还有一个适用于 Rust 编程语言的容器开发套件 (CDK)。 我们的目标是使任何语言(具有针对 WebAssembly 的编译器)都能够生成在互联网计算机上运行的容器智能合约,并通过语言中立的 Candid 接口与其它(可能是外围的)Canister容器智能合约进行互操作。

Its tailored design means Motoko should be the easiest and safest language for coding on the Internet Computer, at least for the forseeable future.

其量身定制的设计意味着 Motoko 应该成为互联网计算机上最简单、最安全的编码语言,至少在可预见的未来是如此。

Motoko 智能合约编程语言
arkMeta Crypto Network Limited, arkSong 2023年10月28日
标签
登录 留下评论

Q06:变体类型、结果类型、HTTP 请求和容器间消息
Variant types, Result type, HTTP request & Intercanister messages