Example: A Minimal Script
A Minimal Scriptβ
As we have learned before, a Script that returns 0 is considered successful. The simplest CKB Script code in Rust looks like this:
pub fn program_entry() -> i8 {
0
}
The simplest CKB Script code, often called always-success, always returns 0 as its return code. You might think this simplest Script code is also the dumbest one because if you use this as your Lock Script, your tokens could be taken by anyone.
However, this simplest Script proves useful in a development environment. When testing Scripts on a local blockchain for your dApp, you might allow the testing Cells to have an always-success Lock Script to simplify your testing workflow.
Despite its utility, the always-success Script is not very interesting due to its simplicity.
Here we will start with a more interesting idea:
Personally I dislike carrot. I do know that carrot is great from a nutritional point of view, but I still want to avoid it due to the taste. Now what if I want to set a rule, that none of my Cells on CKB has data that begin with the word
carrot?
Letβs write a Script code to ensure this.
Below is a step-by-step guide, and you can also clone the full code example from the Github at carrot-script.
Carrot-Forbidden Scriptβ
The first step is to create a new Script project. We use ckb-script-templates for this purpose. Make sure you have the following dependencies installed:
Init a Script Projectβ
Now let's run the command to generate a new Script project called my-first-contract-workspace:
- Command
- Response
alias create-ckb-scripts="cargo generate gh:cryptape/ckb-script-templates workspace"
create-ckb-scripts
β οΈ Favorite `gh:cryptape/ckb-script-templates` not found in config, using it as a git repository: https://github.com/cryptape/ckb-script-templates.git
π€· Project Name: my-first-contract-workspace
π§ Destination: /tmp/my-first-contract-workspace ...
π§ project-name: my-first-contract-workspace ...
π§ Generating template ...
π§ Moving generated files into: `/tmp/my-first-contract-workspace`...
π§ Initializing a fresh Git repository
β¨ Done! New project created /tmp/my-first-contract-workspace
Create a New Scriptβ
Letβs create a new Script called carrot.
- Command
- Response
cd my-first-contract-workspace
make generate
π€· Project Name: carrot
π§ Destination: /tmp/my-first-contract-workspace/contracts/carrot ...
π§ project-name: carrot ...
π§ Generating template ...
π§ Moving generated files into: `/tmp/my-first-contract-workspace/contracts/carrot`...
π§ Initializing a fresh Git repository
β¨ Done! New project created /tmp/my-first-contract-workspace/contracts/carrot
Our project is successfully setup! You can run tree . to show the project structure:
- Command
- Response
tree .
.
βββ Cargo.lock
βββ Cargo.toml
βββ Makefile
βββ README.md
βββ contracts
β βββ carrot
β βββ Cargo.toml
β βββ Makefile
β βββ README.md
β βββ src
β βββ main.rs