The easiest way to setup a cairo dev environment
Cairo is the native language of StarkNet. When I wanted to start playing with it a few months ago I had a lot of trouble setting up my development environment. My laptop was under nixos and my desktop PC under macos (ARM version) which didn’t make things easy. I finally found a solution that works for me and I thought that it could save you time if I share it here.
Let’s use NIX.
Nix is a cross-platform package manager that utilizes a purely functional deployment model where software is installed into unique directories generated through cryptographic hashes. In particular, it allows you to create separate environments from the rest of your computer described from a simple file. Nixos is a linux distribution that uses NIX for everything, but you can install NIX it in one command on any unix system.
Linux
sh <(curl -L https://nixos.org/nix/install) — daemon
Macos
sh <(curl -L https://nixos.org/nix/install)
Ensure these commands didn't change here: https://nixos.org/download.html
When nix is installed, you should have access to new commands like nix-shell (you may have to restart your terminal). We are going to use nix-shell to open a shell separate from the rest of your computer containing all the tools you will need for your project.
Let’s define the environment
According to the quickstart of cairo-lang.org, we need to define a python environment and to use a library: gmp. That's nice because it’s really easy to do with nix (and you can easily change the script to add your own libraries and python packages if you wish).
You will need two files : shell.nix which will list the binaries to use (python and the gmp library) and requirements.txt: the file that python will use to know which packages to install.
Get the shell.nix code here.
The part you may want to change is this:
buildInputs = [
pythonPackages.python
pythonPackages.venvShellHook
gmp
];
For example if you want to add a different lib or use a specific version of python. You can find the available nix packages here.
For the requirements.txt, this is what you currently need but make sure to check the quickstart of cairo-lang.org in case anything changed:
ecdsa
fastecdsa
sympy
cairo-lang
If you want to develop contracts for starknet and not just pure cairo, you probably want to add cairo-nile to this list.
This is what your folder should look like:
To launch the environment you can simply type nix-shell in a terminal open in the folder containing this shell.nix. This will automatically create am env folder (make sure to add it to your gitignore if you are using git).
You can now run your first cairo code!
- Create a file called test.cairo and copy paste this code.
- Compile it:
cairo-compile test.cairo --output test_compiled.json
- Run it:
cairo-run --program=test_compiled.json --print_output --print_info --relocate_prints
Tada!
To exit the shell just type exit.