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.

Pour Linux, macOS, et PowerShell sur Windows, entrez ceci :

mkdir ~/cairo_projects
cd ~/cairo_projects

Pour l'invite de commande Windows, entrez ceci :

> 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.

Il a également initialisé un nouveau dépôt Git avec un fichier .gitignore.

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.

Ouvrez Scarb.toml dans votre éditeur de texte préféré. Il devrait ressembler au code de l'exemple 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

Ce fichier est au format TOML (Tom’s Obvious, Minimal Language), qui est le format de configuration de Scarb.

La première ligne, [package], est une rubrique de section qui indique que les déclarations suivantes configurent un package. Au fur et à mesure que nous ajouterons davantage d'informations à ce fichier, nous ajouterons d'autres sections.

Les deux lignes suivantes définissent les informations de configuration dont Scarb a besoin pour compiler votre programme : le nom et la version de Scarb à utiliser.

La dernière ligne, [dependencies], marque le début d'une section où vous pouvez répertorier toutes les dépendances de votre projet. En Cairo, les packages de code sont appelés des crates. Nous n'aurons pas besoin d'autres crates pour ce projet.

Note: If you're building contracts for Starknet, you will need to add the starknet dependency as mentioned in the Scarb documentation.

L'autre fichier créé par Scarb est src/lib.cairo, supprimons tout son contenu et insérons le contenu suivant, nous expliquerons la raison plus tard.

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.

Si vous avez installé Cairo correctement, vous devriez pouvoir l'exécuter et voir la sortie suivante :

$ 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!

Avant la déclaration de la fonction principale, la ligne use debug::PrintTrait; est responsable de l'importation d'un élément défini dans un autre module. Dans ce cas, nous importons l'élément PrintTrait de la bibliothèque principale de Cairo. En faisant cela, nous obtenons la possibilité d'utiliser la méthode print() sur les types de données compatibles avec l'impression.

Le corps de la fonction main contient le code suivant :

    '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.

Premièrement, le style Cairo consiste à indenter avec quatre espaces, pas avec une tabulation.

Deuxièmement, la fonction print() appelée est une méthode du trait PrintTrait. Ce trait est importé de la bibliothèque de base de Cairo et il définit comment afficher les valeurs à l'écran pour différents types de données. Dans notre cas, notre texte est défini comme une "short string", qui est une chaîne ASCII pouvant s'adapter au type de données de base de Cairo, qui est le type felt252. En appelant Hello, world!'.print(), nous appelons la méthode print() de l'implémentation felt252 du trait PrintTrait.

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

Récapitulons ce que nous avons appris jusqu'ici à propos de 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.

Un avantage supplémentaire de l'utilisation de Scarb est que les commandes sont les mêmes, peu importe le système d'exploitation sur lequel vous travaillez. À partir de maintenant, nous ne fournirons plus d'instructions spécifiques pour Linux et macOS par rapport à Windows.

Summary

Vous avez déjà fait un excellent début dans votre parcours avec Cairo ! Dans ce chapitre, vous avez appris comment :

  • 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

C'est un bon moment pour créer un programme plus substantiel afin de vous habituer à lire et à écrire du code Cairo.

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