Skip to content
Home » Blockchain » Full Guide to Cairo 1.0 | Smart Contract Programming Language

Full Guide to Cairo 1.0 | Smart Contract Programming Language

full-guide-cairo-programming-language-starknet-metaschool

There have previously been various competitors to Solidity such as Fe, Move, and Vyper but one particular competitor, the Cairo 1.0 programming language, has started to gain popularity despite being a relatively new, updated language.

What is Cairo 1.0 programming language?

Cairo is the native programming language for Starknet, a Layer-2 network that is designed to scale the Ethereum blockchain. It was first introduced in 2020.

Recently, in 2023, Cairo underwent massive changes and came out as a brand new language. Its latest version is known as Cairo 1.0, but it should be noted that it is not just an iteration of its previous version. Over 90% of it is inspired by and written in the Rust programming language.

Cairo 1.0 is a STARK-based Turing-complete language used to write STARK-provable programs for general computation. Provable programs are those programs that can be proven through a mathematical argument. In it, you are absolutely sure that your input will give you a certain output. For a provable program written in Cairo 1.0, one party can prove to another one that a certain computation has been executed correctly. Hence it is used to write STARK-based programs that have proof of correctness to them.

Its competitor, Solidity, supports composable computation which is a way of writing code that allows you to easily combine different computations.

A sneak peek into Starknet and how it scales Ethereum

Now that you know what Cairo is and how it works, you would definitely want to know how it is linked to Starknet, right? Well, let me break it down for you.

Starknet

Starkent is a Layer-2 Ethereum solution that was developed by StarkWare, the parent company of Starknet, in November 2021. StarkWare is a company that focuses on the ZK-rollup technology to help scale the Ethereum blockchain. Its vision is to bring exponential scalability to the blockchain without compromising on permissionless interactions, decentralization, and Layer-1 security.

In recent times, we have seen a boom in Ethereum Layer-2 solutions. Examples of these solutions include Polygon, Arbitrum, Immutable X, etc. Starknet is now also included in the list.

When it comes to Ethereum Layer-2 solutions, there are majorly two types: Optimistic rollups or ZK (Zero-Knowledge) rollups.

1. Optimistic rollups

An off-chain Layer-2 solution that is specially designed to enhance Ethereum’s overall throughput and reduce the load and burden from the Ethereum mainnet by processing a chunk of transactions out of it.

2. ZK rollups

ZK rollups, too, are an off-chain Layer-2 protocol but operate on the top of the Ethereum blockchain and are managed by on-chain Ethereum smart contracts. They can further be classified into two proof systems, ZK SNARK, and ZK STARK.

a. ZK SNARK

Short for Zero-Knowledge Succinct Non-Interactive Argument of Knowledge (SNARK), ZK SNARK refers to a proof construction in which one can easily give proof of their possessions.

In ZK SNARK, the user’s identity remains intact because the proof can be in the form of a secret key. So they won’t be revealing information to either the prover or the verifier. But they will be able to prove their possession.

b. ZK STARK

The ZK STARK protocol was introduced later on as an alternative to ZK SNARK. This is the layer protocol that is used by Starknet. Starknet itself is a general-purpose ZK-rollup built on the STARK proof system.

Differences-between-Zkrollups-and-optimistic-rollups
Differences between ZK-roll ups and Optimistic roll ups

Common programming concepts in Cairo 1.0 programming language

Now, this is where it gets a little complex. Although Cairo v0 was also inspired by the Rust programming language, Cairo 1.0 shares even more similarities with it.

Keeping that in mind, there are some major differences between the programming concepts of both, Cairo 1.0 and Cairo v0, which is now obsolete. So, the following concepts are related to Cairo 1.0 only.

Read more: Starknet Alpha and Cairo 1.0 Have Arrived

Data types

Moving on, if you have read about Rust, you would know that Rust is a strongly typed language. Cairo 1.0 is similar. Like Rust and Cairo v0, Cairo 1.0 also has more or less the same tools. It also supports a “type” interface like Rust.

The type system in Cairo 1.0 is divided into 5 types which have sub-types and they are as follows:

1. Basic data types

The basic data types in Cairo 1.0 include four prominent types. Some of these types are divided into sub-types.

  1. Boolean (bool): represents true and false values
  2. Never type: a type of an expression that should not be evaluated in the encapsulating block, but should cause a flow control change
  3. Unit type: a type that has only one value
  4. Numeric types: these types are used for basic mathematical operations like DMAS. Numeric types are further divided into two sub-types.
    felt252: used to represent a field element
    integers: numbers with no fractions

2. Sequence data types

Sequence data types include Tuple, Array and Felt252Dict.

  1. Tuple: a general way of grouping together a number of values with various types into one compound type
  2. Array: similar to a Tuple but in an array, you have a homogenous group of data types, unlike a tuple in which you have a heterogeneous group of data types.
  3. Felt252Dict: used to denote the dictionary type that Cairo 1.0 supports

3. Pointer data types

These data types help you in the storage. Pointer data types include the following:

  1. Box: a data type that allows you to store a value on the heap
  2. Snapshot: a type that creates a reference to an object at a given point in time, which can not be changed

4. User-defined types

Short for UDT, user-defined types include the following:

  1. Struct: user-defined data types that allow you to group related data together
  2. Enum: data types that allow you to define a type by enumerating its possible values

5. Helper Macros

Helper Macros in Cairo include the following:

  1. Derive Macro: used to implement traits and structs for enums automatically.

Syntax

Syntax in programming languages is used to tell the computer how to read and interpret the code. Cairo syntax includes the following:

1. Traits

There are functionality blueprints in the Cairo 1.0 programming language that are specified by traits. The specification includes a set of function signatures containing type annotations for the parameters. In order to define a trait, you use the keyword trait followed by the name of the trait in PascalCase then the function signatures in a pair of curly braces.

2. Hint

In Cairo v0, the hint keyword was used to provide hints to the compiler about how to optimize a piece or a block of code. The compiler may use these hints to generate more efficient code.

However, with Cairo 1.0, the user-defined hints have been sidelined within the syntax to some extent. They are now determined by the Sierra – Starknet’s intermediate representation. The hint syntax might be there in Cairo 1.0 in the future (currently there is no room for hints that are not generated by the compiler) but the hint syntax will not be available in Starknet smart contacts.

3. Test functions

As the name goes, test functions are used to test the correctness of Cairo 1.0 programs. They verify that the non-test code is functioning in the expected manner. The test bodies perform the following actions:

  • Set up any needed data or state
  • Run the code you want to test
  • Asserts the results you expect

They are typically written in the spec module. Test functions are also written using the assert statement to check for errors.

Source: Starknet

Ownership

In Cairo 1.0, ownership is a concept also inspired by Rust. This feature helps ensure the memory safety of the programs without a garbage collector. Garbage collection (GC) is a memory recovery feature that is built into programming languages such as C++ and Java. While it is a feature with benefits, it has some drawbacks such as runtime overhead.

The recently updated programming language has a linear type system. The biggest benefit of such a type system is that it helps in the prevention of runtime errors. In it a particular value can not be used twice so the margin of errors reduces then and there. If something has been written to a memory cell twice, it will be detected during compile time.

Ownership rules in Cairo 1.0 programming language

Ownership in Cairo 1.0 has some rules (make the description look good and different)

  • Each value in Cairo has an owner
  • There can only be one owner at a time
  • The value gets dropped when the owner goes out of scope

What is the Cairo v0 memory model like?

The Cairo v0 memory model has a set of rules that govern how memory is accessed and modified by Cairo programs. The memory model ensures that Cairo programs are correct and safe.

It’s a relaxed memory model, which means that it allows for some optimizations that can lead to race conditions. Race conditions are a type of bug that can occur when two threads of execution access the same memory location at the same time.

The developers of Cairo v0 were suggested to be careful about how they access and modify memory to be able to avoid race conditions. However, this problem was greatly resolved in the newer Cairo version, Cairo 1.0.

Benefits of Cairo 1.0 programming language

While Cairo can help build Layer-2 dApps that share the security of Layer-1 dApps, have great throughput, and require minimal gas fees. Here are some other benefits that make it stand out:

1. Powerful syntax

Cairo has a powerful syntax that is easier to read and code. The syntax is heavily inspired by the Rust programming language. This allows users to run almost everything as they write programs in Cairo. The other Cairo benefit is that it is an extensible language. This means that it can be extended with new features and functionality.

2. Turing-Complete

Cairo, as mentioned, is a Turing-complete language. This simply means that it can be used to write any program that can be written in any other Turing-complete language. This makes Cairo a powerful and useful tool for developing and building a wide variety of applications.

3. Sierra

One of the major updates in the Cairo 1.0 programming language and a great benefit of the language is Sierra. Before Cairo 1.0, users would write contracts in Cairo v0 and compile them locally to Cairo assembly (or Casm for short). Later on, they would submit the compilation output to the Starknet sequencer.

With Sierra and Cairo 1.0, this has changed. The role of Casm has been reduced to a great extent now. The contract class now only includes instructions in an intermediate representation known as Sierra also known as Safe Intermediate Representation. This new contract class is then compiled by the sequencer, via the Sierra → Casm compiler, in order to generate the Cairo 1.0 assembly associated with this class.

Sierra, the additional layer, is quite helpful for the overall security and integrity of the Cairo 1.0 code. It removes halting problems and minimizes the risks of DoS attacks by acting as a shield of sorts. It ensures that every program run in Cairo 1.0 is proven.

This function in Cairo 1.0 is introduced keeping in mind one of the core features of Starknet, permissionless-ness. With Cairo v0, nothing like Sierra is to be found which means smart contract attacks.

4. Computational Integrity

This is one of the biggest features of the Cairo 1.0 programming language. It helps scale the Ethereum blockchain but how? Via something called computational integrity (CI) which is STARK-proved and efficient.

Computational integrity here means having a sense of ownership, justice and protecting the integrity of the system as a whole. It means running your computation on a Layer-2 protocol just like you would on a Layer-1 protocol.

There are multiple ways of ensuring CI and they are:

  • Delegated accountability
  • Inclusive accountability
  • Trusted execution environments
  • Fraud proofs
  • Cryptographic proofs

Cairo uses cryptographic proof, which is used by ZK-STARKs. In this method, there is a prover and a verifier. A verifier must check the proof provided by the prover to ensure that the CI is maintained. This feature has allowed Cairo 1.0 to greatly scale the Ethereum blockchain.

5. Community

The Cairo 1.0 developer community is quite strong and widespread. With Starknet, Cairo 1.0 devs possess a common goal and that is to deploy their blockchain applications on Starknet and scale Ethereum.

Moreover, it is one of those languages that are completely documented. You can also find additional resources and community support on the Github of Cairo 1.0 and its different socials which are maintained by the stakeholders of the language and the blockchain – Starknet.

Cairo tools, libraries, and frameworks for development

1. Tools

Each language has software programs that help programmers with specific tasks, such as debugging, code formatting, and version control. They are called tools. Cairo has the following:

  • scarb: It is used for project management in Cairo 1.0.
  • protostar – Full-fledged Starknet smart contract development toolchain.

2. Libraries

The collections of pre-written code that can be reused in different programs are known as libraries. Some of the libraries included in the Cairo language are as follows:

  • corelib: Built-in standard Cairo 1.0 library. It is large-scale and quite in-depth.
  • cairo_ml: Used to perform inference in Cairo 1.0 by building neural network models.
  • erc20.cairo: A library one can use for StarkWare’s test erc20 implementation.

3. Frameworks

Frameworks provide a complete blueprint and structure for developing certain types of applications. Cairo 1.0 also has some templates that you can use while building or coding, let’s say a smart contract. This is what they have to offer:

  • auditless/cairo-template: A minimalistic type template that can come in handy when you are writing smart contracts.
  • msaug/cairo1-template: Especially helpful for those who are starting out with Cairo 1.0. It can help you understand the concepts and pretty much make your experience a little more streamlined and organized.
Source: BitKeep Academy

How to write a basic smart contract with Cairo 1.0

Writing a basic smart contract on the Starknet blockchain using Cairo 1.0 can be both a fun and tiring process. But the following few steps try to make it easy for you to understand how to write a Hello World smart contract .

1. Set up an environment and get some testnet tokens

First setup Protostar, the development framework mentioned earlier, and ArgentX, a popular wallet to set up your development environment. Then go to this website and get some test tokens for your testnet account

2. Build your project

Run the following commands to build a basic project:

protostar init hello_cairo
cd hello_cairo

Now, run the following command to build the default smart contract file present in the src/contract

protostar build

3. Deploy your smart contract

In order to deploy your smart contract, the first thing you need to do is export your private key by running the following command:

export PROTOSTAR_ACCOUNT_PRIVATE_KEY=[ARGENTX PRIVATE KEY HERE]

Next, you are to declare your smart contract by running the following command:

protostar declare hello_starknet --network testnet --account-address [ARGENTX ACCOUNT ADDRESS] --max-fee auto

The last stage of deploying your smart contract involves running the following command:

protostar deploy [CLASS HASH] --network testnet --account [ARGENTX ACCOUNT ADDRESS] --max-fee auto

You can find your class hash here: build/hello_starknet.class_hash

Use cases of Cairo

As a programming language, Cairo makes a good fit for many different applications which means that it has various different use cases.

1. ERC-20 tokens

Cairo, with its latest version 1.0, proves to be an excellent choice for creating ERC-20 tokens. This powerful smart contract language enables developers to write secure and efficient code, offering a wide range of features that can be leveraged to design diverse, creative, and highly useful ERC-20 tokens. Cairo can also be used to write and deploy fungible tokens.

2. Automated market makers

A type of decentralized exchange, AMMs use liquidity pooling to trade assets. A developer and user can develop and generate AMMs in Cairo 1.0. It implements a Uniswap V3 protocol which helps create automated market makers. The language can also be used to write an AMM contract which traders can use for liquidity pooling. Thus, Cairo 1.0 makes a very useful tool for the creation of DeFI applications.

Finally,

Cairo 1.0 is not just a better and improved version of Cairo v0, it’s a new programming language is designed for blockchain applications on Starknet. The language is heavily inspired by the Rust programming language, and it provides a number of features that are well-suited for blockchain development. The features include ownership and memory safety, type safety, efficiency, speed, and a Rust-like syntax that is easy to understand.