In this video, we begin building a smart contract called Exam, which serves as a practical example to demonstrate core functionalities of smart contracts on the Internet Computer Protocol (ICP). We’ll cover everything from setting up the project and importing libraries to struct creation and memory management.
We start by cleaning out the existing files in our backend src directory to begin with a fresh workspace. Then, we include several necessary imports:
Next, we update the Cargo.toml file by adding the ic-stable-structures dependency:
[dependencies]
ic-stable-structures = "0.5.4"
This resolves any import errors and prepares the environment for smart contract development.
ICP uses a different state management approach compared to traditional smart contracts. One key concept is stable memory, which ensures the contract's state persists even after redeployments.
This is crucial—without it, data would reset on each update, disrupting application logic and testing. Our contract will use stable structures to maintain consistent state.
We define a new struct called Exam:
struct Exam {
out_of: u8,
course_name: String,
curve: u8,
}
This struct contains:
We annotate the struct with macros to make it compatible with ICP's Candid and serialization requirements:
#[derive(CandidType, Serialize, Deserialize)]
These macros allow the frontend to recognize the struct and facilitate seamless data conversion between memory and UI.
To work with stable memory, we implement the following traits for our struct:
Enables converting the struct to and from bytes:
Specifies:
These definitions ensure efficient and predictable memory usage when interacting with ICP’s stable memory.
We also define a type Memory alias to simplify references to virtual memory:
type Memory = VirtualMemory<DefaultMemoryImpl>;
const MAX_VALUE_SIZE: u32 = 100;
This approach avoids repetitive long type definitions and improves code readability.
These steps represent the foundational structure for many smart contracts on the Internet Computer. Once understood, the process becomes much more intuitive and repeatable for different projects.
Swap insights and ask questions about “Build on Internet Computer with ICP Rust CDK”.
Ask a question or share your thoughts about this lesson.