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.
Para Linux, macOS y PowerShell en Windows, introduce esto:
mkdir ~/cairo_projects
cd ~/cairo_projects
Para Windows CMD, introduzca esto:
> 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.
También ha inicializado un nuevo repositorio Git junto con un archivo .gitignore
Note: Git is a common version control system. You can stop using version control system by using the
--vcs
flag. Runscarb new -help
to see the available options.
Abra Scarb.toml en su editor de texto preferido. Debería parecerse al código del Listado 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" }
Este archivo se encuentra en formato TOML (Tom’s Obvious, Minimal Language), que es el formato de configuración de Scarb.
La primera línea, [package]
, es un encabezado de sección que indica que las siguientes sentencias están configurando un paquete. A medida que agreguemos más información a este archivo, agregaremos otras secciones.
Las siguientes dos líneas establecen la información de configuración que Scarb necesita para compilar su programa: el nombre y la versión de Scarb a utilizar.
La última línea, [dependencies]
, es el comienzo de una sección para que puedas listar cualquiera de las dependencias de tu proyecto. En Cairo, los paquetes de código se conocen como crates. No necesitaremos ninguna otra crate para este proyecto.
Note: If you're building contracts for Starknet, you will need to add the
starknet
dependency as mentioned in the Scarb documentation.
El otro archivo creado por Scarb es src/lib.cairo
, borremos todo el contenido y pongamos el siguiente contenido, explicaremos la razón más adelante.
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 has instalado Cairo correctamente, deberías ser capaz de ejecutarlo y ver la siguiente salida:
$ 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 onscarb fmt
in Appendix D). The Cairo team has included this tool with the standard Cairo distribution, ascairo-run
is, so it should already be installed on your computer!
Antes de la declaración de la función principal, la línea use debug::PrintTrait;
es responsable de importar un elemento definido en otro módulo. En este caso, estamos importando el elemento PrintTrait
de la biblioteca central de Cairo. Haciendo esto, ganamos la habilidad de usar el método print()
en tipos de datos que son compatibles con la impresión.
El cuerpo de la función main
contiene el siguiente código:
'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.
En primer lugar, el estilo de Cairo es hacer sangrías con cuatro espacios, no con una tabulación.
Segundo, la función print()
es un método del trait PrintTrait
. Este trait se importa de la librería del núcleo de Cairo, y define cómo imprimir valores en la pantalla para diferentes tipos de datos. En nuestro caso, nuestro texto está definido como una "cadena corta", que es una cadena ASCII que puede caber en el tipo de datos básico de Cairo, que es el tipo felt252
. Al llamar a Hello, world!'.print()
, estamos llamando al método print()
de la implementación felt252
del 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
Recapitulemos lo que hemos aprendido hasta ahora sobre 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 thescarb run
command. - We can run tests using the
scarb test
command.
Una ventaja adicional de usar Scarb es que los comandos son los mismos sin importar el sistema operativo en el que estemos trabajando. Así que, en este punto, ya no proporcionaremos instrucciones específicas para Linux y macOS frente a Windows.
Summary
Ya has empezado con buen pie tu viaje en Cairo. En este capítulo, has aprendido cómo:
- 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
Este es un buen momento para construir un programa más sustancial para acostumbrarte a leer y escribir código de Cairo.