¡Hola, mundo!

Ahora que has instalado Cairo, es hora de escribir tu primer programa Cairo. Es tradicional cuando se aprende un nuevo lenguaje se escriba un pequeño programa que imprima el texto Hello, world! en la pantalla, ¡así que haremos lo mismo aquí!

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.

Creando un Directorio de Proyecto

Empezarás creando un directorio para almacenar tu código de Cairo. A Cairo no le importa a Cairo dónde vive tu código, pero para los ejercicios y proyectos de este libro, sugerimos hacer un directorio cairo_projects en tu directorio home y mantener todos tus proyectos allí.

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

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"

Nota: De ahora en adelante, para cada ejemplo mostrado en el libro, asumimos que estarás trabajando desde un directorio de proyecto Scarb. Si no estás utilizando Scarb, e intentas ejecutar los ejemplos desde un directorio diferente, puede que tengas que ajustar los comandos en consecuencia o crear un proyecto Scarb.

Crear un Proyecto con Scarb

Vamos a crear un nuevo proyecto usando 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.

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

Filename: Scarb.toml

[package]
name = "test"
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.9.2"

[dev-dependencies]
snforge_std = "0.35.1"
assert_macros = "2.9.2"

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

[scripts]
test = "snforge test"

# ...

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

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.

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.

The [dev-dependencies] section is about dependencies that are required for development, but are not needed for the actual production build of the project. snforge_std and assert_macros are two examples of such dependencies. If you want to test your project without using Starknet Foundry, you can use cairo_test.

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.

Starknet Foundry also have more options, check out Starknet Foundry documentation for more information.

By default, using Starknet Foundry adds the starknet dependency and the [[target.starknet-contract]] section, so that you can build contracts for Starknet out of the box. We will start with only Cairo programs, so you can edit your Scarb.toml file to the following:

Filename: Scarb.toml

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

[dependencies]

Listing 1-2: Contents of modified Scarb.toml

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

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

A sample Scarb project structure

Crear un proyecto con Scarb

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

$ scarb build 
   Compiling hello_world v0.1.0 (listings/ch01-getting-started/no_listing_01_hello_world/Scarb.toml)
    Finished `dev` profile target(s) in 8 seconds

This command creates a hello_world.sierra.json 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 
   Compiling hello_world v0.1.0 (listings/ch01-getting-started/no_listing_01_hello_world/Scarb.toml)
    Finished `dev` profile target(s) in 15 seconds
     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!

Anatomía de un Programa Cairo

Revisemos este programa “Hello, world!” en detalle. Aquí está la primera pieza del rompecabezas:

fn main() {

}

Estas líneas definen una función llamada main. La función main es especial: siempre es el primer código que se ejecuta en cada programa ejecutable de Cairo. Aquí, la primera línea declara una función llamada main que no tiene parámetros y devuelve nada. Si hubiera parámetros, irían dentro de los paréntesis ().

El cuerpo de la función está envuelto en {}. Cairo requiere llaves alrededor de todos los cuerpos de funciones. Es una buena práctica colocar la llave de apertura en la misma línea que la declaración de la función, añadiendo un espacio en medio.

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!

El cuerpo de la función main contiene el siguiente código:

    println!("Hello, World!");

Esta línea hace todo el trabajo en este pequeño programa: imprime texto en la pantalla. Hay cuatro detalles importantes a tener en cuenta aquí.

Primero, el estilo de Cairo es identar con cuatro espacios, no con una tabulación.

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.

En tercer lugar, ves la short string 'Hello, world!'. Pasamos este short string como argumento a print(), y la cadena corta se imprime en la pantalla.

Cuarto, terminamos la línea con un punto y coma (;), que indica que esta expresión ha terminado y la siguiente está lista para comenzar. La mayoría de las líneas de código de Cairo terminan con punto y coma.

Resumen

Recapitulemos lo que hemos aprendido hasta ahora sobre Scarb:

  • We can install one or multiple Scarb versions, either the latest stable or a specific one, using asdf.
  • Podemos crear un proyecto utilizando scarb new.
  • Podemos construir un proyecto usando scarb build para generar el código compilado de Sierra.
  • We can execute a Cairo program using the scarb cairo-run 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.

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.