NEAR Protocol - What happens when Rust contract method args are declared as (&mut self, ...) vs. (&self, ...)?

191 views Asked by At

Recently I copy pasted a bunch of method signatures and attempted to create a view method for a NEAR smart contract:

pub fn get_credits(&mut self, account_id: AccountId) -> u128 {
    self.credits.get(&account_id).unwrap_or(0)
}

When calling this contract using near-api-js it will throw an error saying that the method is not allowed env::attached_deposit().

Do you see the problem?

1

There are 1 answers

5
mattdlockyer On

When a method in Rust is declared with args (&mut self, ...) you are indicating to the compiler that you wish to mutate the state of the contract, the "self".

You will receive an error if you try to call this method as a viewMethod from near-api-js.

The fix is to declare view methods with args like this (&self, ...) indicating that you will NOT be altering the state of the contract by calling this function.

A subtle nuance of Rust and near-sdk-rs, but important!