-2

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?

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44

1 Answers1

2

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!

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44
  • 4
    Haven't used near-sdk-rs, but mutable references and related restrictions are one of rust's main selling points, not a subtle nuance :) – Sergio Tulentsev Sep 26 '20 at 20:22
  • No offence intended, but what does this pair of question/answer clarifies more than [this very common source of documentation](https://doc.rust-lang.org/stable/rust-by-example/fn/methods.html)? Is there something specific to a particular API? (`mut` enables mutability...) – prog-fh Sep 26 '20 at 20:23
  • I've edited the question to highlight this situation is specifically referring to the NEAR blockchain near-sdk-rs and related JavaScript SDKs. I understand the Rust community is very passionate, but these downvotes and comments seem egregious. – mattdlockyer Sep 27 '20 at 23:02
  • You can seem my comment on the edits... Consider removing the downvotes since there are other communities using Rust in different contexts and they may benefit from the specificity of this example. – mattdlockyer Sep 27 '20 at 23:04
  • Also removed Rust tag so Rust community can ignore this question now. – mattdlockyer Sep 27 '20 at 23:07