stylus_hello_world/
lib.rs

1//!
2//! Stylus Hello World
3//!
4//! The following contract implements the Counter example from Foundry.
5//!
6//! ```
7//! contract Counter {
8//!     uint256 public number;
9//!     function setNumber(uint256 newNumber) public {
10//!         number = newNumber;
11//!     }
12//!     function increment() public {
13//!         number++;
14//!     }
15//! }
16//! ```
17//!
18//! The program is ABI-equivalent with Solidity, which means you can call it from both Solidity and Rust.
19//! To do this, run `cargo stylus export-abi`.
20//!
21//! Note: this code is a template-only and has not been audited.
22//!
23
24// Allow `cargo stylus export-abi` to generate a main function.
25#![cfg_attr(not(feature = "export-abi"), no_main)]
26extern crate alloc;
27
28/// Use an efficient WASM allocator.
29#[global_allocator]
30static ALLOC: mini_alloc::MiniAlloc = mini_alloc::MiniAlloc::INIT;
31
32/// Import items from the SDK. The prelude contains common traits and macros.
33use stylus_sdk::{alloy_primitives::U256, prelude::*};
34
35// Define some persistent storage using the Solidity ABI.
36// `Counter` will be the entrypoint.
37sol_storage! {
38    #[entrypoint]
39    pub struct Counter {
40        uint256 number;
41    }
42}
43
44/// Declare that `Counter` is a contract with the following external methods.
45#[external]
46impl Counter {
47    /// Gets the number from storage.
48    pub fn number(&self) -> U256 {
49        self.number.get()
50    }
51
52    /// Sets a number in storage to a user-specified value.
53    pub fn set_number(&mut self, new_number: U256) {
54        self.number.set(new_number);
55    }
56
57    /// Sets a number in storage to a user-specified value.
58    pub fn mul_number(&mut self, new_number: U256) {
59        self.number.set(new_number * self.number.get());
60    }
61
62    /// Sets a number in storage to a user-specified value.
63    pub fn sub_number(&mut self, new_number: U256) {
64        self.number.set(new_number + self.number.get());
65    }
66
67    /// Increments `number` and updates its value in storage.
68    pub fn increment(&mut self) {
69        let number = self.number.get();
70        self.set_number(number + U256::from(1));
71    }
72}