Hello, World

Now that you’ve installed Cairo through Scarb, it’s time to write your first Cairo program. It’s traditional when learning a new language to write a little program that prints the text Hello, world! to the screen, so we’ll do the same here!

Note: This book assumes basic familiarity with the command line. Cairo makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an integrated development environment (IDE) instead of the command line, feel free to use your favorite IDE. The Cairo team has developed a VSCode extension for the Cairo language that you can use to get the features from the language server and code highlighting. See Appendix F for more details.

Creating a Project Directory

You’ll start by making a directory to store your Cairo code. It doesn’t matter to Cairo where your code lives, but for the exercises and projects in this book, we suggest making a cairo_projects directory in your home directory and keeping all your projects there.

Open a terminal and enter the following commands to make a cairo_projects directory.

对于Linux、macOS和Windows上的PowerShell,输入:

mkdir ~/cairo_projects
cd ~/cairo_projects

对于Windows CMD,请输入以下内容:

> mkdir "%USERPROFILE%\cairo_projects"
> cd /d "%USERPROFILE%\cairo_projects"

Note: From now on, for each example shown in the book, we assume that you will be working from a Scarb project directory. If you are not using Scarb, and try to run the examples from a different directory, you might need to adjust the commands accordingly or create a Scarb project.

Creating a Project with Scarb

让我们使用 Scarb 创建一个新项目。

Navigate to your cairo_projects directory (or wherever you decided to store your code). Then run the following:

scarb new hello_world

Scarb will ask you about the dependencies you want to add. You will be given two options :

? Which test runner do you want to set up? ›
❯ Starknet Foundry (default)
  Cairo Test

In general, we'll prefer using the first one ❯ Starknet Foundry (default).

This creates a new directory and project called hello_world. We’ve named our project hello_world, and Scarb creates its files in a directory of the same name.

Go into the hello_world directory with the command cd hello_world. You’ll see that Scarb has generated three files and two directory for us: a Scarb.toml file, a src directory with a lib.cairo file inside and a tests directory containing a test_contract.cairo file. For now, we can remove this tests directory.

它还初始化了一个新的Git仓库和一个.gitignore文件

Note: Git is a common version control system. You can stop using version control system by using the --no-vcs flag. Run scarb new --help to see the available options.

Open Scarb.toml in your text editor of choice. It should look similar to the code in Listing 1-1.

文件名:Scarb.toml

[package]
name = "hello_world"
version = "0.1.0"
edition = "2024_07"

# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html

[dependencies]
starknet = "2.8.2"

[dev-dependencies]
snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.31.0" }

[[target.starknet-contract]]
sierra = true

[scripts]
test = "snforge test"

Listing 1-1: Contents of Scarb.toml generated by scarb new

这个文件是TOML(Tom's Obvious, Minimal Language)的格式,是Scarb的配置文件格式。

第一行,[package],是一个章节标题,表示下面的语句是在配置一个包。随着我们向这个文件添加更多的信息,我们将添加其他章节。

The next three lines set the configuration information Scarb needs to compile your program: the name of the package and the version of Scarb to use, and the edition of the prelude to use. The prelude is the collection of the most commonly used items that are automatically imported into every Cairo program. You can learn more about the prelude in Appendix D.

The [dependencies] section, is the start of a section for you to list any of your project’s dependencies. In Cairo, packages of code are referred to as crates. We won’t need any other crates for this project.

Note: By default, using Starknet Foundry adds the starknet dependency, so that you can also build contracts for Starknet.

The [dev-dependencies] section is about dependencies that are required for development, but are not needed for the actual production build of the project.

The [[target.starknet-contract]] section allows to build Starknet smart contracts. We can remove it for now.

The [script] section allows to define custom scripts. By default, there is one script for running tests using snforge with the scarb test command. We can also remove it for now.

The other file created by Scarb is src/lib.cairo, let's delete all the content and put in the following content, we will explain the reason later.

mod hello_world;

Then create a new file called src/hello_world.cairo and put the following code in it:

文件名: src/hello_world.cairo

fn main() {
    println!("Hello, World!");
}

We have just created a file called lib.cairo, which contains a module declaration referencing another module named hello_world, as well as the file hello_world.cairo, containing the implementation details of the hello_world module.

Scarb requires your source files to be located within the src directory.

The top-level project directory is reserved for README files, license information, configuration files, and any other non-code-related content. Scarb ensures a designated location for all project components, maintaining a structured organization.

If you started a project that doesn’t use Scarb, you can convert it to a project that does use Scarb. Move the project code into the src directory and create an appropriate Scarb.toml file. You can also use scarb init command to generate the src folder and the Scarb.toml it contains.

├── Scarb.toml
├── src
│   ├── lib.cairo
│   └── hello_world.cairo

Scarb 项目结构示例

Building a Scarb Project

From your hello_world directory, build your project by entering the following command:

$ scarb build
   Compiling hello_world v0.1.0 (file:///projects/Scarb.toml)
    Finished release target(s) in 0 seconds

This command creates a sierra file in target/dev, let's ignore the sierra file for now.

If you have installed Cairo correctly, you should be able to run the main function of your program with the scarb cairo-run command and see the following output:

$ scarb cairo-run
Running hello_world
Hello, World!
Run completed successfully, returning []

Regardless of your operating system, the string Hello, world! should be printed to the terminal.

If Hello, world! did print, congratulations! You’ve officially written a Cairo program. That makes you a Cairo programmer — welcome!

Anatomy of a Cairo Program

Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle:

fn main() {

}

These lines define a function named main. The main function is special: it is always the first code that runs in every executable Cairo program. Here, the first line declares a function named main that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses ().

The function body is wrapped in {}. Cairo requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between.

Note: If you want to stick to a standard style across Cairo projects, you can use the automatic formatter tool available with scarb fmt to format your code in a particular style (more on scarb fmt in Appendix F). The Cairo team has included this tool with the standard Cairo distribution, as cairo-run is, so it should already be installed on your computer!

main函数的主体包含以下代码:

    println!("Hello, World!");

This line does all the work in this little program: it prints text to the screen. There are four important details to notice here.

首先,Cairo的风格是用四个空格缩进,而不是用制表符。

Second, println! calls a Cairo macro. If it had called a function instead, it would be entered as println (without the !). We’ll discuss Cairo macros in more detail in the "Macros" chapter. For now, you just need to know that using a ! means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions.

Third, you see the "Hello, world!" string. We pass this string as an argument to println!, and the string is printed to the screen.

Fourth, we end the line with a semicolon (;), which indicates that this expression is over and the next one is ready to begin. Most lines of Cairo code end with a semicolon.

Summary

让我们回顾一下到目前为止我们所了解到的关于Scarb的情况:

  • We can install one or multiple Scarb versions, either the latest stable or a specific one, using asdf.
  • We can create a project using scarb new.
  • We can build a project using scarb build to generate the compiled Sierra code.
  • We can execute a Cairo program using the scarb cairo-run command.

使用Scarb的另一个好处是,无论你在哪个操作系统上工作,命令都是一样的。所以我们将不再提供Linux和macOS与Windows的具体说明。

You’re already off to a great start on your Cairo journey! This is a great time to build a more substantial program to get used to reading and writing Cairo code.