Hello World in Cairo: Complete Solution & Deep Dive Guide

macbook pro on brown wooden table

The Ultimate Cairo "Hello, World!" Guide: Your First Step to Starknet Mastery

A "Hello, World!" program in Cairo is your foundational entry into Starknet development. It involves creating a main function that returns the short string literal 'Hello, World!' as a felt252 type. This simple exercise validates your toolchain setup, including the Scarb package manager, and introduces Cairo's core syntax.

You’ve heard the whispers about Layer 2 scaling, the promise of STARK proofs, and the revolutionary potential of Cairo for building verifiable applications on the blockchain. The ambition to build the next groundbreaking dApp on Starknet is palpable, but every grand journey starts with a single, crucial first step. For developers, that step has always been the humble "Hello, World!".

But in Cairo, this isn't just about printing text to a screen. It's your initiation rite. It’s the moment you confirm your development environment is perfectly configured, the compiler understands your commands, and you've written your very first piece of verifiable code. This guide will walk you through that rite of passage, transforming you from a Cairo-curious enthusiast to a developer who has officially written and tested their first Cairo program.


What is the "Hello, World!" Program?

The "Hello, World!" tradition is a time-honored ritual in the world of programming. Its origins trace back to a 1974 internal memorandum at Bell Laboratories by Brian Kernighan, one of the co-authors of the C programming language. The goal is simple: write the most basic program possible in a new language to produce the output "Hello, World!".

Its enduring popularity stems from its utility as a sanity check. If you can get "Hello, World!" to run, it means several critical things have gone right:

  • The language's compiler or interpreter is correctly installed.
  • The development environment and toolchain are functioning.
  • You understand the most fundamental syntax for creating an executable piece of code.
  • The build and execution process works as expected.

In the context of a systems language like Cairo, which is designed for creating provable programs for a virtual machine (the Cairo VM), this first step is even more significant. It's your first interaction with concepts that are unique to the Starknet ecosystem.


Why is This the First Step in the Kodikra Cairo Path?

Within the exclusive Kodikra learning path for Cairo, "Hello, World!" is positioned as the non-negotiable first module for a reason. It’s not just about syntax; it’s about establishing a solid foundation with the Cairo ecosystem's tools and core data types.

Validating Your Development Environment

The most immediate goal is to verify your setup. The Cairo world revolves around its official package manager and build tool, Scarb. Successfully compiling and testing "Hello, World!" is definitive proof that Scarb is installed correctly and your system's PATH variables are configured to find the Cairo compiler.

Introducing Core Syntax and Structure

This simple program forces you to engage with the essential building blocks of a Cairo program:

  • Function Definition: You'll learn how to declare a function using the fn keyword.
  • Entry Point: You'll use the main function, the standard entry point for many programs.
  • Return Types: You will explicitly declare a return type using ->, a concept familiar to Rust developers.
  • Primitive Data Types: You get your first look at felt252, the fundamental data type in Cairo, representing a field element in a 252-bit prime field.

Understanding Short Strings in Cairo

Perhaps the most unique lesson here is how Cairo handles strings. Unlike many languages where strings are complex, heap-allocated objects, Cairo treats short strings (up to 31 characters) as a special case. They can be packed directly into a single felt252 value. This exercise immediately introduces you to this performance optimization and the mathematical nature of Cairo's data types.

    ● Start: Setup Environment
    │
    ▼
  ┌───────────────────┐
  │ Install Cairo & Scarb │
  └─────────┬─────────┘
            │
            ▼
  ┌───────────────────┐
  │ `scarb new hello_world` │
  └─────────┬─────────┘
            │
            ▼
  ┌───────────────────┐
  │ Edit `src/lib.cairo` │
  └─────────┬─────────┘
            │
            ▼
    ◆ Write the function:
    │ `fn main() -> felt252`
    │ `  'Hello, World!'`
    │
    ▼
  ┌───────────────────┐
  │ Run `scarb test`    │
  └─────────┬─────────┘
            │
            ▼
    ◆ Test Passes?
   ╱              ╲
  Yes              No
  │                │
  ▼                ▼
[Success!]     [Debug Code]
  │
  ▼
 ● End: Ready for next module

How to Write and Run "Hello, World!" in Cairo

Let's move from theory to practice. We will now build, test, and understand your first Cairo program from scratch. This is the core of the kodikra.com module.

Step 1: Environment Setup & Project Initialization

First, ensure you have the Cairo toolchain installed. If you haven't, follow the official instructions to install `cairo-up`, which will provide you with the compiler and Scarb.

Once installed, open your terminal and create a new project using Scarb. This command scaffolds a new Cairo library project with the necessary file structure.


# Create a new cairo project named "hello_world"
scarb new hello_world

This will create a directory named hello_world with the following structure:


hello_world/
├── Scarb.toml
└── src
    └── lib.cairo
  • Scarb.toml: This is the manifest file for your project. It contains metadata like the project name, dependencies, and compiler settings. It's similar to Cargo.toml in Rust or package.json in Node.js.
  • src/lib.cairo: This is where your Cairo source code lives. By default, Scarb creates a library file.

Step 2: The Cairo Code Solution

Open the src/lib.cairo file in your favorite code editor. You will see some boilerplate code. Replace it entirely with the following solution.


// The main function, which serves as the entry point for our program.
// In this context, our test will call this function to check its output.
// It is defined to return a value of type felt252.
fn main() -> felt252 {
    // This is a short string literal. In Cairo, short strings (up to 31 ASCII characters)
    // are a special syntax that gets compiled directly into a felt252 value.
    // The single quotes are mandatory for this syntax.
    'Hello, World!'
}

Step 3: Detailed Code Walkthrough

Let's dissect every piece of this code to understand what's happening.

fn main() -> felt252 {

  • fn: This is the keyword in Cairo used to declare a new function.
  • main: This is the name we've given our function. While main is a special name for the entry point in many languages, here it's just a function that our test will specifically call.
  • (): These parentheses indicate that the function takes no arguments or parameters.
  • -> felt252: This is the return type annotation. The arrow -> signifies that the function will return a value, and felt252 specifies that the type of this value will be a field element. This is a mandatory part of the function signature if it returns something.
  • {: This curly brace opens the function body, where the logic resides.

'Hello, World!'

  • This is the core of our program. It might look like a simple string, but it's a powerful Cairo feature.
  • Single Quotes ('...'): This syntax is crucial. In Cairo, single quotes denote a "short string literal". The compiler takes this human-readable string and encodes it into a single, large integer that fits within a felt252.
  • Implicit Return: Notice the absence of a return keyword or a semicolon (;). Like Rust, Cairo is an expression-based language. The last expression in a function body is automatically its return value. So, the 'Hello, World!' expression is the value that the main function returns.

}

  • This closing curly brace marks the end of the function body.

The magic here is the compiler's ability to convert a sequence of up to 31 ASCII characters into a number. This is possible because a felt252 is a massive number, and each character can be represented by its 8-bit ASCII value. The compiler combines these values into one large integer.

  'H'   'e'   'l'   'l'   'o' ... (String)
   │     │     │     │     │
   ▼     ▼     ▼     ▼     ▼
  0x48  0x65  0x6C  0x6C  0x6F ... (ASCII Hex Values)
   │     │     │     │     │
   └─────┴─────┴─────┴─────┴───┐
                               │
                               ▼
                        ┌──────────────────┐
                        │ Mathematical     │
                        │ Encoding Process │
                        └────────┬─────────┘
                                 │
                                 ▼
                       ┌───────────────────┐
                       │ Single Large Number │
                       │ (A felt252 Value) │
                       └───────────────────┘

Step 4: Compiling and Testing

With the code in place, it's time to test it. The kodikra.com learning environment provides a test suite that checks if your main function returns the correct felt252 value. You can run these tests locally using Scarb.

Navigate back to your terminal, ensuring you are in the root of your hello_world project directory, and run the test command:


# This command compiles your code and runs any tests associated with it.
scarb test

If your code is correct, you will see a successful output, indicating that all tests have passed:


testing hello_world ...
running 1 test
test hello_world::tests::test_main ... ok
test result: ok. 1 passed; 0 failed; 0 ignored

Congratulations! You have successfully written, compiled, and tested your first Cairo program. You've verified your toolchain and taken a significant step towards mastering Cairo development.


Common Pitfalls and Best Practices

Even in a simple program, there are common mistakes that newcomers make. Understanding these can save you a lot of debugging time in the future.

Pitfall / Mistake Why It Happens How to Fix It
Using Double Quotes ("Hello, World!") This is the standard string syntax in most other languages (Python, JavaScript, C++, etc.). It's an easy habit to carry over. In Cairo, always use single quotes ('...') for short string literals that you want to be treated as a felt252. Double quotes are for different string types that are not part of the core language yet.
Forgetting the Return Type fn main() { ... } If a function returns a value, you must declare its type. Add -> felt252 to the function signature. The Cairo compiler is very strict about types.
Adding a Semicolon 'Hello, World!'; A semicolon (;) turns an expression into a statement. A statement evaluates to a "unit type" (), not a felt252. This will cause a type mismatch error. For an implicit return, omit the semicolon on the last line.
String is Too Long 'This string is definitely longer than thirty-one characters...' A short string literal must be 31 characters or less to fit into a felt252. For longer strings, you need to use more advanced types like ByteArray, which is beyond the scope of this initial exercise.

Frequently Asked Questions (FAQ)

1. What exactly is a felt252?

felt252 stands for "field element". It is the fundamental data type in Cairo. It's an integer in the range [0, P-1], where P is a very large prime number (specifically, 2^251 + 17 * 2^192 + 1). All computations in the Cairo VM are ultimately performed on these field elements. They are used to represent numbers, memory addresses, and even encoded short strings.

2. Why does Cairo use single quotes for this string?

The single quotes are syntactic sugar. They are a special instruction to the Cairo compiler to perform the encoding of an ASCII string into a single felt252 number at compile time. This is a highly efficient way to handle short, constant strings on-chain.

3. Can I print to the console from a Cairo smart contract?

No, not in the traditional sense. A smart contract runs on a decentralized network, not on a single machine with a console. There is no standard output. For debugging or logging information, you emit "events". These events are recorded on the blockchain and can be read by off-chain applications and block explorers.

4. What is Scarb and why do I need it?

Scarb is the official package manager and build tool for Cairo. It's an indispensable part of the modern Cairo workflow. Scarb handles dependency management, compiling your code into Sierra (an intermediate representation), building contracts, and running tests. It simplifies the entire development lifecycle.

5. How is Cairo different from Solidity or Rust?

While its syntax is heavily inspired by Rust, Cairo's core purpose is different. It's designed to create *provable* programs. Every Cairo program's execution trace can be used to generate a STARK proof, cryptographically proving the computation was done correctly. This is fundamentally different from Solidity, which runs on the EVM without this native provability feature.

6. What is the absolute maximum length of a short string?

A short string can have a maximum of 31 ASCII characters. This is because a felt252 has 251 bits of usable space for this encoding (the highest bit is reserved), and 31 characters * 8 bits/character = 248 bits, which fits comfortably.

7. Where can I learn more about Cairo's basic types?

This "Hello, World!" module is just the beginning. To dive deeper into Cairo's type system, including integers, booleans, and more complex data structures, continue your journey on the complete Kodikra Cairo language guide.


Conclusion: Your Journey Has Begun

You've done more than just make a program say hello. You have successfully configured a professional Cairo development environment, used the Scarb toolchain to manage a project, written a function with correct syntax and types, and understood the fundamental concept of how Cairo represents data through the felt252 type.

This foundational knowledge is the bedrock upon which you will build everything else. Every complex smart contract, every DeFi protocol, and every on-chain game you create will rely on these core principles. You've taken the first, most important step.

Now, the real adventure begins. Continue to the next module in the Cairo learning roadmap to build upon this success and explore variables, control flow, and the powerful features that make Cairo the future of verifiable computation.

Disclaimer: The code and explanations in this article are based on Cairo v2.6.x and Scarb v2.6.x. The Cairo language and its toolchain are under active development, and syntax or commands may change in future versions.


Published by Kodikra — Your trusted Cairo learning resource.