Constructor and persistent storage
Focus: one persistent counter initialized by a constructor and updated through entries.
counter_storage.slx
const COUNT_KEY: string = "count"
hook constructor() -> u64 {
let storage: Storage = Storage::new()
storage.store(COUNT_KEY, 0)
return 0
}
entry increment(by: u64) -> u64 {
require(by > 0, "zero increment")
let storage: Storage = Storage::new()
let count: u64 = storage.load(COUNT_KEY).unwrap_or(0)
let next: u64 = count + by
storage.store(COUNT_KEY, next)
return next
}
entry read_count() -> u64 {
let storage: Storage = Storage::new()
return storage.load(COUNT_KEY).unwrap_or(0)
}
entry reset() {
let storage: Storage = Storage::new()
storage.store(COUNT_KEY, 0)
return 0
}How it works
COUNT_KEYis the stable storage key used by every entry.hook constructor()runs once at deployment and stores the initial count.increment(by)reads the count, validates the input, stores the new value, and returns it as a typed exit value.read_count()loads the current value without changing it and returns it as a typed exit value.reset()stores zero and returns the default success exit code.
Read the stored count with daemon RPC get_contract_data using key "count".
Last updated on