一个简单的智能合约示例

sCrypt中的合约(contract)在概念上类似于面向对象编程中的类(class)。每个contract都为特定类型的合约(如:P2PKH或多重签名)提供了模板,可被实例化为可运行的合约对象。

contract Test {
    int x;

    constructor(int x) {
        this.x = x;
    }

    public function equal(int y) {
        require(y == this.x);
    }
}

构造函数(constructor)

每个合约最多只能有一个构造函数。用于初始化合约的成员变量。例如,初始化P2PKH合约的公钥哈希,或者哈希谜题(hash puzzle)合约的secret hash。

默认构造函数

当没有构造函数时,编译器会生成一个默认的构造函数,按照声明顺序初始化每一个成员变量。例如:

contract Test {
    int x1;
    bytes x2;
    bool x3;

    public function equal(int y) {}
}

在功能上等同于

contract Test {
    int x1;
    bytes x2;
    bool x3;

    constructor(int x1, bytes x2, bool x3) {
        this.x1 = x1;
        this.x2 = x2;
        this.x3 = x3;
    }

    public function equal(int y) {}
}

require()

require() 函数指定合约的限制条款/条件。它的参数是一个布尔条件表达式。如果条件表达式的值为假,合约将终止执行并失败。否则,将继续执行。

公有函数

Each contract has at least one public function. It is denoted with the public keyword and does not return any value. The function body corresponds to locking script and its arguments unlocking script. It is visible outside the contract and acts as the entry point into the contract (like main in C and Java).

A public function must end with a require() call. require() can also appear in other parts of a public function. A contract can only be fulfilled and succeed when its called public function runs to completion without violating any conditions in require(). In the above example, only unlockingScript (i.e., y) equal to this.x can fulfill the contract.

A public function can be regarded as a mathematical boolean function. f is the function body and x the function arguments. A contract call succeeds if and only if f(x) returns true.

sCrypt logo

多个公有函数

A contract can have multiple public functions, representing different ways to fulfill a contract. Only one of the public functions can be called at a time. In this case, the last operator of unlockingScript has to be the index of the public function called, starting from 0. For example, if public function larger is called, unlockingScript of y 2 can fulfill the contract below, in which 2 is the public function index.

contract Test {
    int x;

    public function equal(int y) {
        require(y == this.x);
    }

    public function smaller(int y) {
        require(y < this.x);
    }

    public function larger(int y) {
        require(y > this.x);
    }
}