Compiling the HelloStarknet
contract
Introduction
Welcome to the second installment of the "Hello, Starknet!" quickstart series, the official tutorial for starting your journey as a Starknet developer! 🚀
Before a contract can be deployed on Starknet, its compiled code needs to be submitted to the network (also known as declaring it). This installment of the series will therefore walk you though compiling Scarb’s default HelloStarknet
contract, which will be used throughout the following installments.
To learn more about Starknet smart contracts, see the Contracts section. |
Generating HelloStarknet
Scarb’s default HelloStarknet
contract can be generated by simply running:
scarb new hello_starknet
and selecting to set up the Starknet Foundry (default)
test runner.
For the purpose of this tutorial, you can ignore all files in the hello_starknet
directory other than hello_starknet/src/lib.cairo
, which holds the contract’s code:
/// Interface representing `HelloContract`.
/// This interface allows modification and retrieval of the contract balance.
#[starknet::interface]
pub trait IHelloStarknet<TContractState> {
/// Increase contract balance.
fn increase_balance(ref self: TContractState, amount: felt252);
/// Retrieve contract balance.
fn get_balance(self: @TContractState) -> felt252;
}
/// Simple contract for managing balance.
#[starknet::contract]
mod HelloStarknet {
use core::starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
balance: felt252,
}
#[abi(embed_v0)]
impl HelloStarknetImpl of super::IHelloStarknet<ContractState> {
fn increase_balance(ref self: ContractState, amount: felt252) {
assert(amount != 0, 'Amount cannot be 0');
self.balance.write(self.balance.read() + amount);
}
fn get_balance(self: @ContractState) -> felt252 {
self.balance.read()
}
}
}
As its comments read, this is a simple contract with two basic functions:
-
get_balance
, which reads the contract’s current balance from storage. -
increase_balance
, which reads the contract’s current balance from storage, increases it byamount
and writes the new balance to storage.
Compiling HelloStarknet
To compile the HelloStarknet
contract, navigate into the newly created hello_starknet
directory and run:
scarb build
The first time a project is built, some components of Scarb are compiled locally with the Rust toolchain. This process may take a few minutes, but will not happen in subsequent builds. |
The compiled contract should now be saved inside the hello_starknet/target/dev/
directory as hello_starknet_HelloStarknet.contract_class.json
.