Starknet ERC-20 Testnet Deployment Tutorial

Starknet is a Layer2 network over Ethereum for unlimited scale for its computation.Contracts are written in Cairo, a programming language for writing provable programs.

In this tutorial, we write a standard ERC-20 contacts and deploy to goerli Starknet.Compared to ERC-20 written with solidity, our implement are also based on OpenZeppelin's Cairo Library.

Setting up the environment

We create a python virtual environment.And then install packages and dependencies inside the environment.

python -m venv ~/cairo_venv
source ~/cairo_venv/bin/activate

You should see(cairo_venv) in the command line like the following screenshot.

cairo_venv
cairo_venv

Install gmp.

On Ubuntu

sudo apt install -y libgmp3-dev

On mac, you can use brew:

Install the cairo-lang python packages using:

pip install cairo-lang

For this project, like we mentioned above, we will install OpenZapplin Contracts Library.And Nile, a development environment for Cairo.

pip install cairo-nile openzeppelin-cairo-contracts

Finally, run nil init to initial cairo environment which includes a local network, a testing framework, and some sample codes.

mkdir my-proj
cd my-proj
nile init

Import the library

we'll create an ERC20 token contract base on OpenZeppline's Library with few lines. Create a MyToken.cairo file:

%lang starknet
from openzeppelin.token.erc20.ERC20 import constructor

This is a full functional ERC20 token implement with implemented Library.All basic logic are set in the library.

Deploy to the testnet

Firstly we compile the code.

nile compile

and then we can deploy to the testnet

nile deploy MyToken <name> <symbol> <decimals> <initial_supply> <recipient> --alias my_token

Alternatively, some params should be passed as felt type, so we use nile's python api instead.

# scripts/deploy.py
def run(nre):
    print("Compiling contract…")
    nre.compile(["contracts/MyToken.cairo"]) # we compile our contract first
    print("Deploying contract…")
    name = str(str_to_felt("MyToken"))
    symbol = str(str_to_felt("MTK"))
    decimals = "18"
    recipient = "0x057e792bbff407d7a128e61a722721bcc5ca8cf0488d4fe2d72fadd577e1c194"
    params = [name, symbol, decimals, "100", "0", recipient]
    address, abi = nre.deploy("MyToken", params, alias="my_token")
    print(f"ABI: {abi},\nContract address: {address}")
# Auxiliary functions
def str_to_felt(text):
    b_text = bytes(text, "ascii")
    return int.from_bytes(b_text, "big")
def uint(a):
    return(a, 0)

Execute it with nile run:

nile run scripts/deploy.py

Interacting with the token

We can call functions:

nile call my_token totalSupply

100 0

and we can check the contract at voyager's testnet explorer.

post image

Conclusion

As above, we had written few lines and deployed contracts to testnet. With the help of OpenZeppline’s library, developing a ERC20 contract is quite easy for beginners.Hope this tutorial can open the door for you to the Starknet’s zk world!