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 D 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 and a directory for the “Hello, world!” project within the cairo_projects directory.

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.

For Linux, macOS, and PowerShell on Windows, enter this:

mkdir ~/cairo_projects
cd ~/cairo_projects

For Windows CMD, enter this:

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

Creating a Project with Scarb

Let’s create a new project using Scarb.

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

scarb new hello_world

It 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 two files and one directory for us: a Scarb.toml file and a src directory with a lib.cairo file inside.

It has also initialized a new Git repository along with a .gitignore file

Note: Git is a common version control system. You can stop using version control system by using the --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-2.

Filename: Scarb.toml

[package]
name = "hello_world"
version = "0.1.0"

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

[dependencies]
# foo = { path = "vendor/foo" }

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

This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Scarb’s configuration format.

The first line, [package], is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections.

The next two lines set the configuration information Scarb needs to compile your program: the name and the version of Scarb to use.

The last line, [dependencies], 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: If you're building contracts for Starknet, you will need to add the starknet dependency as mentioned in the Scarb documentation.

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:

Filename: src/hello_world.cairo

use debug::PrintTrait;
fn main() {
    'Hello, World!'.print();
}

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.

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 and see the following output:

$ scarb cairo-run
running hello_world ...
[DEBUG] Hello, World!                   (raw: 0x48656c6c6f2c20776f726c6421

Run completed successfully, returning []

Regardless of your operating system, the string Hello, world! should print 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 D). 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!

Prior to the main function declaration, The line use debug::PrintTrait; is responsible for importing an item defined in another module. In this case, we are importing the PrintTrait item from the Cairo core library. By doing so, we gain the ability to use the print() method on data types that are compatible with printing.

The body of the main function holds the following code:

    'Hello, World!'.print();

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

First, Cairo style is to indent with four spaces, not a tab.

Second, the print() function called is a method from the trait PrintTrait. This trait is imported from the Cairo core library, and it defines how to print values to the screen for different data types. In our case, our text is defined as a "short string", which is an ASCII string that can fit in Cairo's basic data type, which is the felt252 type. By calling Hello, world!'.print(), we're calling the print() method of the felt252 implementation of the PrintTrait trait.

Third, you see the 'Hello, World!' short string. We pass this short string as an argument to print(), and the short 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.

Running tests

To run all the tests associated with a particular package, you can use the scarb test command. It is not a test runner by itself, but rather delegates work to a testing solution of choice. Scarb comes with preinstalled scarb cairo-test extension, which bundles Cairo's native test runner. It is the default test runner used by scarb test. To use third-party test runners, please refer to Scarb's documentation.

Test functions are marked with the #[test] attributes, and running scarb test will run all test functions in your codebase under the src/ directory.

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

A sample Scarb project structure

Let’s recap what we’ve learned so far about Scarb:

  • We can create a project using scarb new.
  • We can build a project using scarb build to generate the compiled Sierra code.
  • We can define custom scripts in Scarb.toml and call them with the scarb run command.
  • We can run tests using the scarb test command.

An additional advantage of using Scarb is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows.

Summary

You’re already off to a great start on your Cairo journey! In this chapter, you’ve learned how to:

  • Install the latest stable version of Cairo
  • Write and run a “Hello, Scarb!” program using scarb directly
  • Create and run a new project using the conventions of Scarb
  • Execute tests using the scarb test command

This is a great time to build a more substantial program to get used to reading and writing Cairo code.

Last change: 2023-10-03, commit: eafa093