Suppose I have this simple code in a smart contract:
#[near_bindgen]
pub struct A {
pub var1: AccountId,
pub var2: Balance,
pub my_map: TreeMap<String, (u128, u128, u128)>,
}
#[near_bindgen]
impl A {
#[init]
pub fn init() -> Self {
let _my_map: TreeMap<String, (u128, u128, u128)> = TreeMap::new(b"t");
Self {
//...other fields
my_map: _my_map
}
}
//!!!
// will this work properly for each client at all?
//
pub fn my_method1(&mut self) {
// !! instance variable !!
if !self.my_map.contains_key("some_key") {
self.my_map.insert(&"aaa", &(1, 2, 3));
} else {
// already exists, error!
}
}
}
In the ordinary environment this Rust code would everyone to have his own instance of A
and with its unique values of the fields. Correct?
Do I understand correctly, that in NEAR everyone -- client -- would have the same instance of A
?
Namely, the instance variable A.my_map
would contain the same data for every client of a smart contract where this code may be used?
How about A.var1
and A.var2
then?
A smart contract persists state between invocations. In your example, my_map
and other variables will be the same every time anyone calls my_method1
in your contract.
This state is persistent within the network your smart contract is deployed, meaning - for testnet
and mainnet
it’ll be separate.
If you wish, for example, to manage separate state for different callers, check out this example: https://github.com/near-examples/rust-status-message/blob/master/src/lib.rs It uses a mapping between caller’s account ID and data related to it.