Hello, World
Sekarang bahwa Anda telah menginstal Cairo melalui Scarb, saatnya untuk menulis program Cairo pertama Anda. Adalah tradisi ketika belajar bahasa baru untuk menulis program kecil yang mencetak teks Hello, world! ke layar, jadi kita akan melakukan hal yang sama di sini!
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.
Membuat Direktori Proyek
Anda akan memulai dengan membuat direktori untuk menyimpan kode Cairo Anda. Tidak masalah bagi Cairo di mana kode Anda berada, tetapi untuk latihan dan proyek dalam buku ini, kami menyarankan untuk membuat direktori cairo_projects di direktori rumah Anda dan menyimpan semua proyek Anda di sana.
Open a terminal and enter the following commands to make a cairo_projects directory.
Untuk Linux, macOS, dan PowerShell di Windows, masukkan ini:
mkdir ~/cairo_projects
cd ~/cairo_projects
Untuk Windows CMD, enter this:
> mkdir "%USERPROFILE%\cairo_projects"
> cd /d "%USERPROFILE%\cairo_projects"
Catatan: Mulai dari sekarang, untuk setiap contoh yang ditunjukkan dalam buku ini, kami mengasumsikan bahwa Anda akan bekerja dari direktori proyek Scarb. Jika Anda tidak menggunakan Scarb, dan mencoba menjalankan contoh-contoh dari direktori yang berbeda, Anda mungkin perlu menyesuaikan perintah-perintahnya atau membuat proyek Scarb.
Membuat Projek dengan Scarb
Mari membuat sebuah projek menggunakan 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.
Scarb juga telah menginisialisasi repositori Git baru bersama dengan file .gitignore
Note: Git is a common version control system. You can stop using version control system by using the
--no-vcs
flag. Runscarb 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
File ini menggunakan format TOML (Tom’s Obvious, Minimal Language), yang mana merupakan format konfigurasi Scarb.
Baris pertama, [package]
, adalah judul bagian yang menunjukkan bahwa pernyataan berikut sedang mengonfigurasi sebuah paket. Saat kami menambahkan lebih banyak informasi ke file ini, kami akan menambahkan bagian lain.
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
Mulai membangun Projek 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!
Anatomi Program Cairo
Mari kita ulas “Hello, world!” program ini secara detail. Ini bagian pertama dari teka-teki:
fn main() {
}
Baris-baris ini mendefinisikan fungsi bernama main
. Fungsi main
adalah spesial: itu selalu menjadi kode pertama yang dijalankan di setiap program Cairo yang dapat dieksekusi.Di sini, baris pertama mendeklarasikan fungsi bernama main
yang tidak memiliki parameterdan tidak mengembalikan apa pun. Jika ada parameter, parameter tersebut akan masuk ke dalam tanda kurung ()
.
Fungsi badan dibungkus dengan {}
. Cairo memerlukan tanda kurung kurawal di sekelilingnya semua badan berfungsi. Sebaiknya letakkan tanda kurung kurawal pembuka di baris yang sama dengan deklarasi fungsi, menambahkan satu spasi di antaranya.
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 F). The Cairo team has included this tool with the standard Cairo distribution, ascairo-run
is, so it should already be installed on your computer!
Badan fungsi main
berisi kode berikut:
println!("Hello, World!");
Baris ini melakukan semua pekerjaan dalam program kecil ini: ia mencetak teks kelayar. Ada empat detail penting yang perlu diperhatikan di sini.
Pertama, gaya Cairo adalah membuat indentasi dengan empat spasi, bukan tab.
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.
Keempat, kita mengakhiri baris dengan titik koma (;
), yang menunjukkan bahwa Ekspresi ini sudah selesai dan yang berikutnya siap dimulai. Sebagian besar jalur di Cairokode diakhiri dengan titik koma.
Ringkasan
Mari kita rekap apa yang telah kita pelajari sejauh ini tentang Scarb:
- We can install one or multiple Scarb versions, either the latest stable or a specific one, using asdf.
- Kita dapat membuat proyek menggunakan
scarb new
. - Kita dapat membangun proyek menggunakan
scarb build
untuk menghasilkan kode Sierra yang telah dikompilasi. - We can execute a Cairo program using the
scarb cairo-run
command.
Keuntungan tambahan menggunakan Scarb adalah perintahnya sama, tidaktidak peduli sistem operasi apa yang sedang Anda gunakan. Jadi, pada titik ini, kami tidak akan melakukannyalagi memberikan instruksi khusus untuk Linux dan macOS versus 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.