Skip to main content

Intro to Script

A Script

in Nervos CKB is a binary executable that can be executed on-chain. It is Turing-complete and can perform arbitrary logic to guard and protect your on-chain assets. You can think of it as smart contract.

How a Script Works

When executing a Script, CKB takes the executables and runs them in a virtual machine environment called CKB-VM

. After the execution, if the program returns a code of 0, we consider the Script successful; any non-zero return codes will be considered Script failures.

When you submit a transaction to CKB, it executes all the Scripts from the transaction to ensure that each Script succeeds. If any Script fails, the transaction will not be included on-chain.

In this way, we can allow the Cell to carry different Scripts to perform various validations for the current transaction, similar to how smart contracts work in other blockchains.

Script Types

A Script can be one of two types:

  • Lock Script - Used to control ownership and access to a Cell.
  • Type Script - Used to control how a Cell is used in a transaction.

In most cases, Lock Script works the same with Type Script. The difference is that, only the Lock Script from the input Cells will be executed in the transaction, while the Type Script from both the input Cells and output Cells will be executed in the transaction.

This difference has lead to the different usecases of Lock Script and Type Script as we have mentioned above. Lock Script is often used to control owner ship of a Cell while Type Script defines what kinds of changes of a Cell is valid for the transaction.

Script Structure

Script has the following structure:

pub struct Script {
pub code_hash: H256,
pub hash_type: ScriptHashType,
pub args: JsonBytes,
}

The code_hash serves to identify a Script code, allowing the CKB-VM to load the binary code of the Script correctly.

A Script also includes the args part, which differentiates one Script from another using the same Script code. The args can provide additional arguments for a CKB Script; for example, while multiple users might utilize the same default Lock Script code, each user can have their own public key hash stored in args. This setup allows each user to have a unique Lock Script while sharing the same Lock Script code.

hash_type indicates the method CKB-VM uses to locate the Script code for a Script. Possible values include type, data, data1, and data2. Each specifies a different way of referencing the required Script code.