Git Product home page Git Product logo

cairo-book.github.io's Introduction

English | 简体中文

All Contributors

The Cairo Programming Language Book

Alexandria

Description

This repository contains the source of "The Cairo Programming Language" book, a comprehensive documentation of the Cairo 1 programming language. This documentation is your go-to resource for mastering Cairo, created and maintained by the Starknet community. You can read the book online.

Created by builders, for builders 📜

Contribute

Setup

  1. Rust related packages:

    • Install toolchain providing cargo using rustup.
    • Install mdBook and the required extensions:
    cargo install mdbook mdbook-i18n-helpers mdbook-last-changed
    
  2. Host machine packages:

    • Install gettext for translations, usually available with regular package manager: sudo apt install gettext.
    • Install mdbook-quiz-cairo following the instructions here to be able to add interactive quizzes.
  3. Clone this repository.

  4. Install mdbook-cairo for Cairo code blocks

    cargo install --path mdbook-cairo
    

Work locally (english, main language)

All the Markdown files MUST be edited in english. To work locally in english:

  • Start a local server with mdbook serve and visit localhost:3000 to view the book. You can use the --open flag to open the browser automatically: mdbook serve --open.

  • Make changes to the book and refresh the browser to see the changes.

  • Open a PR with your changes.

Work locally (translations)

This book is targeting international audience, and aims at being gradually translated in several languages.

All files in the src directory MUST be written in english. This ensures that all the translation files can be auto-generated and updated by translators.

To work with translations, these are the steps to update the translated content:

  • Run a local server for the language you want to edit: ./translations.sh es for instance. If no language is provided, the script will only extract translations from english.

  • Open the translation file you are interested in po/es.po for instance. You can also use editors like poedit to help you on this task.

  • When you are done, you should only have changes into the po/xx.po file. Commit them and open a PR. The PR must start with i18n to let the maintainers know that the PR is only changing translation.

The translation work is inspired from Comprehensive Rust repository.

Initiate a new translation for your language

If you wish to initiate a new translation for your language without running a local server, consider the following tips:

  • Execute the command ./translations.sh new xx (replace xx with your language code). This method can generate the xx.po file of your language for you.
  • To update your xx.po file, execute the command ./translations.sh xx (replace xx with your language code), as mentioned in the previous chapter.
  • If the xx.po file already exists (which means you are not initiating a new translation), you should not run this command.

Work locally (Cairo programs verification)

The cairo-listings tool is designed to wrap all Cairo and Starknet plugins for quickly verifying Cairo programs. You can verify that listings are correct with the verify argument, and generate the corresponding output with the output argument.

Setup

Firstly, you need to have scarb resolved in your path. See here for more details.

To run the cairo-listings helper tool and verify Cairo programs, ensure that you are at the root of the repository (same directory of this README.md file), and run:

cargo run --bin cairo-listings verify

Alternatively, you can also install the tool with:

cargo install --path cairo-listings

and then run:

cairo-listings verify

Usage

The tool scans for all *.cairo files in the specified directory and performs the following actions:

For a Starknet contract:

  • scarb build
  • If it has tests: scarb test

Cairo program:

  • If it has a main function: scarb cairo-run --available-gas=200000000
  • Else, scarb build
  • If it has tests: scarb test
  • scarb fmt -c

To specify which tests to run, you can add a comment at the top of your file with the following format:

// TAG: <tag1>
// TAGS: <tag1>, <tag2>

Here is a list of available tags:

  • does_not_compile: don't run scarb build
  • does_not_run: don't run scarb cairo-run --available-gas=200000000
  • ignore_fmt: don't run scarb fmt
  • tests_fail: don't run scarb test

The mdbook-cairo is a mdbook preprocessor that only removes the // TAG lines in code blocks.

Contributors

Fricoben
Fricoben

🤔 🔍 📆
Mathieu
Mathieu

🤔 💻 🧑‍🏫 👀 📆 🚧 🔧
Nadai
Nadai

🌍
glihm
glihm

💻 🔧
Clément Walter
Clément Walter

👀
V.O.T
V.O.T

💻
Pia
Pia

💻 📝
cryptonerdcn
cryptonerdcn

🌍
Argetlames
Argetlames

🌍
julio4
julio4

💻 🔧
Haresh Gedia
Haresh Gedia

📖
Darlington Nnam
Darlington Nnam

💻
Tiago Neto
Tiago Neto

👀
omahs
omahs

💻
Shramee Srivastav
Shramee Srivastav

💻
Daniel Bejarano
Daniel Bejarano

💻
Tristan
Tristan

💻 🚧 👀
okhai.stark ( Tony Stark )
okhai.stark ( Tony Stark )

💻
shwang
shwang

💻
kwkr
kwkr

💻
ArnaudBD
ArnaudBD

💻
Jimmy Fate
Jimmy Fate

💻
SimplementeCao
SimplementeCao

💻
Lucas @ StarkWare
Lucas @ StarkWare

💻
Rémy Baranx
Rémy Baranx

💻
Steven Cordero
Steven Cordero

📖
Symmaque
Symmaque

📖 💻
Asher
Asher

💻
Nenad Misić
Nenad Misić

📖 💻

cairo-book.github.io's People

Contributors

0xeniotna avatar allcontributors[bot] avatar ametel01 avatar boorich avatar cryptonerdcn avatar enitrat avatar fricoben avatar gaetbout avatar glihm avatar julio4 avatar kwkr avatar lucaslvy avatar misicnenad avatar nadai2010 avatar okhaimie-dev avatar orangeryang avatar remybar avatar rodrigo-pino avatar shramee avatar simplementecao avatar sinsotec avatar suiwater avatar symmaque avatar tadev0 avatar th0rgal avatar trangnv avatar trbutler4 avatar tserg avatar wenzhenxiang avatar zarboq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cairo-book.github.io's Issues

Cairo Projects: Packages and Crates

  • Explain what a crate is
  • Create a package with scarb and explain the package structure (lib.cairo default crate root module..)

Estimated time: 1 hour

Starknet contracts: ABIs and cross-contract interactions

This section will cover more advanced concepts around smart contracts:

  • Declaring contract interfaces with #[abi], and what happens under the hood
  • Regular contract calls using the dispatcher pattern (if relevant, introduce how the dispatcher plugin works )
  • Library calls

This section will follow the same standard as the rest of the book, making sure that all concepts are explained properly to someone new to Starknet/Cairo, and will include an example of interactions between contracts/libraries

@milancermak would you be interested in taking this? I think it would be great since you wrote this cairopractice blog post

Estimated time: 3 hours

Hello, Scarb

Hello, Scarb session with basic hello world program, including the installation of Scarb
Estimated time: 1 hour

Feedback

Hey,

since I can't get access to the TG group and I'm too lazy to fix the issues myself, I'm writing here a couple of disjoint points I found so far while glossing over the book.

  1. In felt type, I find the latex notation used to define P quite strange.
  2. In boolean type: "Booleans are one byte in size." IMO that statement is not true. Did you want to say one bit? But then it's felts all the way down, so not sure if that's 100% correct either.
  3. In short string, you should mention that the max length of a short string is 31 chars and also the reason why. It's valuable to know.
  4. A lot of the code snippets are formatted in a weird way. Consider running cairo-format (which is, coincidentally, mentioned in the appendix) on all of them, so people get a habit of creating properly formatted code.

In any case, great work overall, you absolute chads!

Section on Scarb

Scarb is Cairo's default package manager. Scarb is integrated into the language server and becomes mandatory as Cairo projects grow in size.

This section presents Scarb, how to start a scarb project, and various features. It can be inspired from the Cargo section of the rust book.
It will introduce the basics of Scarb. It will link the official Scarb documentation for more complex use cases.

Estimated time: 1 to 2 hours

Error Handling: Unrecoverable Errors with `panic()`

  • Explain what panic does.
  • Explain what actually happens when a Cairo program panics. (read this article to understand what panics actually are).

Given that panics are not very exploitable nor informative in Cairo, this chapter is pretty short.

Estimated time: 1 hour

Control Flow

A section on the Cairo control flow: if statements, loops(still alpha, might be for another issue)
This section doesn't include match statements, which are specific to Cairo (and Rust)

Estimated time: 1 hour

Protostar

Hey,

I've recently started using Protostar and it's got a great support for cairo 1. Perhaps it would be a good idea to add a chapter on the tool?

Cairo's Ownership system

Cairo has an ownership system that is used for its linear type system, ensuring that all values are used exactly once.
This ensures that:

  • Dictionaries are squashed before the end of a program, ensuring the soundness of Cairo programs
  • Array indices can't be written twice.

The chapter will introduce the Cairo ownership system and why it's required for the safety of the language (a good part is covered here )
It will give various examples of what can / cannot be copied, can / cannot be dropped, introduce destructors and how to use them.
This part doesn't introduce ref and @ snapshots yet

Estimated time: 3 to 4 hours

reference: sw-repo doc

Generic Data Types

This part should introduce how to use Generic data types in Cairo, including:

  • How to define generic functions
  • How to define generic function, while restricting the T type that can be used with this function
  • How to define generic structs
  • How to define generic enums
  • How to define generic methods (generic trait + generic impl on a type T)

Estimated time: 4 hours

Summay section misplaced

The summary of chapter 2 is at the end of control flows while there is another subsection which is called common collections

Starknet Contracts: Basics

In this section, we'll break down the structure of Starknet smart contracts in the Cairo language. We'll cover these main points:

  • Discuss the #[contract] attribute's purpose and how the compiler expands the code to make it easier for developers to write contracts. We will also include code snippets of the contract expanded by the compiler, so that the reader can better understand what's actually happening behind the hood.
  • Explain the storage Struct and how to access storage values
  • Introduce constructors, view, and external functions

We'll use a complete contract example and explain it step by step, dividing it into sections to clarify each element.

Estimated time: 3 hours

Common Programming concepts

In this section, we present how common programming concepts are materialized in Cairo.
We don't go very deep into the language details, and just provide the developer with what's required for a basic program.

Subsections: Variables, Data Types, Functions, Comments, Control Flow

An Example Program Using Structs

  • Simple program without structs
  • The equivalent using tuples
  • Using struct to add meaning to our data (named fields)
  • Derive traits (Drop, Copy, Clone, Destruct) note: this will be linked to the Ownership chapter that explains these traits
  • implement Print for your struct to debug it

Estimated: 1 - 2 hours

Foreword

Foreword: A little bit of history about Cairo, who this book is for, and what can you expect to find in the book.

Estimated: ± 1 hour

Common Collections: Arrays (& Spans)

I think we should move the Array from Data Types to a Common Collection section, along with Dictionaries.

Estimated time: 1 hour (move & improve existing section, introduce Spans and where they're used)

Cairo Projects: Defining modules

  • Declaring modules (inline, or in a file)
  • Declaring submodules
  • Paths to code in modules
  • The use keyword
  • Organizing your related code in modules

Estimated time: 2 to 3 hours

Cairo Projects: Bringing Paths into Scope with the use Keyword

  • Full paths and shortcuts to paths (e.g. import a module and then call module::foo)
  • Idiomatic paths (full paths for Traits, Structs, Impls, Enums)
    -Using external packages (with Scarb)
  • Re-export names in module files (in module a you can import foo with use a::b::c::foo, so that you can now import foo in other places using only use a::foo

Estimated time: 2 hours

Following your last answer

Iam a bit confused, what you mean is that i should uninstall cairo After installing scarb ?
Before installing scarb the cairo-run command would execute my code , After installing scarb it just print a bunch of options With argument not found at the end. If i uninstall cairo would cairo-run command work ? Opening this New issue because you closed last one

References and Snapshot

This part introduces references and snapshots as a way to work with Cairo's ownership system.

  • What are snapshots, actually? What are the differences between the snapshot of a copyable type T and a non-copyable type (arrays?)
  • How do mutable references work?

Estimated time: 2 to 3 hours

Functions

Overview of Cairo functions: syntax, parameters, bodies, return values

Estimated time: 2 hours

Wrong tuple example

The example is
let tup: (x: felt252, y: felt252) = (2,3);
where is should have been
let (x, y): (felt252, felt252) = (2, 3);

Hello World

Using a basic hello world program, this subsection under Getting Started shows the syntax of the main function, how to print something to the screen, and how to run the program (this assumes the user has followed the installation steps and has the cairo binaries registered in his $PATH)

Estimated time: 1 hour

Data Types

Succinctly introduce the felt type and its characteristics. Emphasize that developers should try to avoid felts in their applications and use the core library types that offer more features/security.

Also introduce tuples here
Follow the format of the rust book for data types. Adapt to Cairo

Estimated time: 2 hours

The match Control Flow Construct

  • Intro to the match statement
  • Patterns that bind to values
  • Matching with Option
  • Matches are exhaustive
  • Catch-all patterns and the _ placeholder

Estimated time: 1 hour

Control Flow: loops

Explain how loop works in Cairo in the Control Flow section

Estimated time: 1hr

Comments

Document comments usage in Cairo

Method syntax

Introduce the method syntax. In Cairo, methods are defined in the context of a trait, unlike Rust where it can be defined for a struct/enum/trait

  • Defining methods
  • Explain the struct/trait/impl pattern
  • Functions associated with a type (type of the self parameter)
  • Multiple trait implementation for the same Struct

This section will need to introduce Traits and Impls but stay succint and make a reference to a future chapter about traits and generic types. You can add a TODO as a comment so we don't forget it later.
Estimated: 2 to 3 hours

cairo-run command suddenly output "argument not found"

Afetr insatlling scarb and writing my first hello_scarb cairo-run command just do not recognize the file argument i pass , i tried starting a new project and it is the same
full output usage: cairo-run [-h] [-v] [--program PROGRAM] [--program_input PROGRAM_INPUT] [--steps STEPS] [--min_steps MIN_STEPS] [--debug_error] [--no_end] [--print_memory] [--relocate_prints] [--secure_run] [--no_secure_run] [--print_info] [--print_segments] [--print_output] [--memory_file MEMORY_FILE] [--trace_file TRACE_FILE] [--run_from_cairo_pie RUN_FROM_CAIRO_PIE] [--cairo_pie_output CAIRO_PIE_OUTPUT] [--debug_info_file DEBUG_INFO_FILE] [--air_public_input AIR_PUBLIC_INPUT] [--air_private_input AIR_PRIVATE_INPUT] [--layout {plain,small,dex,recursive,starknet,recursive_large_output,all_solidity,starknet_with_keccak,dynamic}] [--tracer] [--profile_output PROFILE_OUTPUT] [--proof_mode] [--show_trace] [--flavor {Debug,Release,RelWithDebInfo}] [--python_dependencies PYTHON_DEPENDENCIES] cairo-run: error: unrecognized arguments: src/lib.cairo

Common Collections: Dictionaries

This chapter will be extremely detailed, and will need provide an extensive description of how dictionaries work on the lower level, inspired by the current Cairo docs to describe why dicts need to be squashed.

This will probably require explaining concepts from Cairo 0, to really understand how dictionaries really work in the context of an immutable memory (related: DictAccess, dict_squash, etc)

Estimated time: 3 -4 hours

Explain every steps more in details

This book is supposed to be beginner friendly yet it lacks details.
Like how to install scarb on any machine ? You just Saïd download the archive and unzip it ... This Can work if i use windows OS or Mac OS, but i use linux inside windows.
I tried looking for a link to curl or wget the scarb archive but it just donwload the zipped file to my windows machine . I tried asking on twitter, got ignored. Iam stuck at scarb installation on WSL for 2 days already... This is what you call beginner friendly ?

Cairo's trait system

  • How to define a trait
  • How to implement a trait on a type
  • Managing different implementations for the same trait (e.g. you can have one impl in mod a and another one in mod b. You will need to import the correct one to use the method syntax on your type)

Estimated time: 2 hours

Unit tests: Discuss where they should be located

This issue is a discussion related to #38 https://cairo-book.github.io/ch09-02-test-organization.html#unit-tests

I'm not sure exactly how we should present it. If we're writing pure Cairo programs it doesn't really matter but most people will be using Cairo for Starknet contracts. Even if you're writing unit tests in a library, including tests in the library directory means that the tests will be shown on block explorer when verifying contracts that depend on this library, which is not great.

Reviews and Organization

Reviews, Creation of issues, Creation of the groups and discussion, research for contributors, discussion with the different parties involved about the doc strategy, meetings for funding...

Defining an Enum

  • Enum variants, values
  • enums combined with custom types
  • traits implementations for enums
  • The Option Enum and its advantages

Estimated: 2 hours

Recoverable Errors with `Result<T,E>`

  • Explain how you can handle an execution error by introducing the Result enum
  • Give an example with existing core library operations (handling e.g. overflowing addition)
  • Shortcuts to panic on error: expect, unwrap methods defined on the ResultTrait trait
  • Error propagation (see rustbook)
  • The ? operator

As this concept shares a lot of similarities with Rust, the submitted PR will follow the content of the Rust book, adapting all examples to Cairo, and removing concepts that don't have an equivalent. The examples will need to make sense in the context in the execution of a Cairo program.

Estimated time: 2-3 hours

Defining and Instantiating Structs

  • how to define structs
  • how to mutate struct fields
  • how to use as function return types
  • using the field init shorthand
  • unit-like structs without any fields

Estimated: 1 hour

Testing Cairo programs

This will chapter cover testing pure Cairo programs.

  • Test modules ( mod tests {...} ) should be annotated with the #[cfg(tests)] attribute to reduce the size of the compiled code
  • How to check values with the assert function
  • How to expect failure from a test (with/without an expected error message)
  • Differentiating unit tests and integration tests

Note: Unlike Rust, unit tests should not be with the source code.
Estimated time: 4 hours

Introduction

The introduction should make a succint presentation of what Cairo is for, what you can do with it, and how different it is from other programming languages (immutable memory, etc).
It might make more sense to write the introduction once we have some content written rather than at the beginning.
Estimated time: 2 to 3 hours

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.