Writing the Simple Storage Contract
In this section, we will write a simple storage contract to demonstrate how to read from and write to storage in Arbitrum Stylus.
Create a New Project
Use the cargo-stylus
command to create a new project:
cargo stylus new simple_storage
cd simple_storage
Edit the Contract Code
Open the src/lib.rs
file and replace the content with the following code:
// Allow `cargo stylus export-abi` to generate a main function.
#![cfg_attr(not(feature = "export-abi"), no_main)]
extern crate alloc;
/// Use an efficient WASM allocator.
#[global_allocator]
static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT;
/// Import items from the SDK. The prelude contains common traits and macros.
use stylus_sdk::{alloy_primitives::U256, prelude::*};
// Define some persistent storage using the Solidity ABI.
// `Storage` will be the entrypoint.
sol_storage! {
#[entrypoint]
pub struct Storage {
uint256 value;
}
}
/// Declare that `Storage` is a contract with the following external methods.
#[external]
impl Storage {
/// Gets the value from storage.
pub fn get_value(&self) -> U256 {
self.value.get()
}
/// Sets a value in storage to a user-specified value.
pub fn set_value(&mut self, new_value: U256) {
self.value.set(new_value);
}
/// Multiplies the stored value by a user-specified value.
pub fn mul_value(&mut self, multiplier: U256) {
self.value.set(multiplier * self.value.get());
}
/// Adds a user-specified value to the stored value.
pub fn add_value(&mut self, increment: U256) {
self.value.set(increment + self.value.get());
}
/// Increments `value` and updates its value in storage.
pub fn increment(&mut self) {
let value = self.value.get();
self.set_value(value + U256::from(1));
}
}
Explanation:
Allocator:
Using
mini_alloc
for an efficient WASM allocator.
Imports:
Importing necessary items from the Stylus SDK, including
U256
fromalloy_primitives
and common traits and macros from theprelude
.
Storage Definition:
Using the
sol_storage!
macro to define theStorage
struct with a singleuint256
field.
External Methods:
get_value
: Returns the current value from storage.set_value
: Sets the storage value to a new user-specified value.mul_value
: Multiplies the current storage value by a user-specified value.add_value
: Adds a user-specified value to the current storage value.increment
: Increments the current storage value by 1.
Deploying and Testing the Contract
Check the Contract:
cargo stylus check --endpoint https://sepolia-rollup.arbitrum.io/rpc
Deploy the Contract:
Ensure you have a valid private key saved in a file (e.g.,
private_key.txt
). The file should contain only the private key without any extra characters or spaces.cargo stylus deploy --private-key-path=/path/to/private_key.txt --endpoint https://sepolia-rollup.arbitrum.io/rpc
Last updated