Search code examples
rustsmartcontractsnearprotocol

How to set a static field in a NEAR smart contract?


I'm working on a smart contract for escrow. In it there'll be the owner who'll supposed to be set once -- during deploying a contract.

How can this be implemented in NEAR, though?

A simplified piece of code:

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Escrow {
    pub owner_id: AccountId,
    pub user1_id: AccountId,
    pub user2_id: AccountId,
    pub amount: Balance,
}

#[near_bindgen]
impl Escrow {
    #[init]
    #[private]
    pub fn init(&self, owner_id: AccountId) -> Self {
        assert!(!env::state_exists(), "Already initialized");

        self.owner_id = env::signer_account_id(); //??? instance variable ???
    }
//...........
}

self.owner_id is an instance variable. Therefore, it'd be different for each new client who uses the contract, and therefore would require initialization again, and again, each time?

In the ordinary Rust code this variable would be static, const or a function. But here it has to be initialized only once and for all, and yet be identical for all the instance of Escrow.

How would this be implemented in NEAR?


Is this owner_id = env::signer_account_id(); a correct way to refer to the address who's deploying a contract?


Solution

  • near-sdk-rs turns the contract instance (Escrow struct) into a singleton on a blockchain, so whatever you save to self will be then stored in the key-value storage of your contract, so it is "static". init method should not take self as a parameter, it should construct the instance (return Self), and it is expected to be called only once. You initialize your contract once, and then define other methods that could update &mut self. near-sdk-rs documentation goes into details about that.