Counter
The following example implements a counter which is able to:
- Increment the count by 1
- Decrement the count by 1
- Retrieve the value of the counter
ABI
To create a counter we must define an ABI
which exposes methods that manipulate the count and retrieve its value. Since we are handling storage
we must provide storage annotations
on the functions.
abi Counter {
#[storage(read, write)]
fn increment();
#[storage(read, write)]
fn decrement();
#[storage(read)]
fn count() -> u64;
}
Implementation
We initialize a count in storage
with the value of zero and implement methods to increment & decrement the count by one and return the value.
storage {
counter: u64 = 0,
}
impl Counter for Contract {
#[storage(read, write)]
fn increment() {
storage.counter.write(storage.counter.read() + 1);
}
#[storage(read, write)]
fn decrement() {
storage.counter.write(storage.counter.read() - 1);
}
#[storage(read)]
fn count() -> u64 {
storage.counter.read()
}
}