Sergey Zhelonkin
Sergey Zhelonkin

Reputation: 21

Failed to call view method of NEAR contract

Deployed simple contract

#[near_bindgen]
impl Contract {
    pub fn hello() -> String {
        String::from("hello")
    }

    pub fn num() -> u8 {
        8
    }
}

trying to call view method by

near view crossword.hilonom.testnet num

and have error

View call: crossword.hilonom.testnet.num()
An error occured
Error: Querying [object Object] failed: wasm execution failed with error: FunctionCallError(HostError(ProhibitedInView { method_name: "attached_deposit" })).
{
  "error": "wasm execution failed with error: FunctionCallError(HostError(ProhibitedInView { method_name: \"attached_deposit\" }))",
  "logs": [],
  "block_height": 74645352,
  "block_hash": "2eoywDD9s62T3swiJCNuXGwwxjhGFdFJuxTiMZ29JFxY"
}

how can i avoid this error?

Upvotes: 2

Views: 479

Answers (2)

GrvTyagi
GrvTyagi

Reputation: 4497

Method that can modify state will be prohibited in view.

The reason behind this is

    /// Note, the parameter is `&self` (without being mutable) meaning it doesn't 
    /// modify state.
    /// In the frontend (/src/main.js) this is added to the "viewMethods" array
    /// using near-cli we can call this by:
    ///
    /// ```bash
    /// near view counter.YOU.testnet get_num
    /// ```

I have also faced this issue I look into the https://docs.near.org/docs/roles/integrator/errors/error-implementation#hosterror enum as suggested

/// `method_name` is not allowed in view calls
    ProhibitedInView { method_name: String },

Upvotes: 0

quantranse
quantranse

Reputation: 41

You're using Struct here, after deploying your contract, you might need to initialize it first.

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
  pub struct Contract {
  name: String,
  value: u8
}

#[near_bindgen]
impl Contract {
  #[init]
  pub fn new() -> Self {
    Self {
        name: String::from("Default name"),
        value: 0u8
    }
}

pub fn hello(&self) -> String {
    // of course you can just return a string here without the need of using name
    self.name.clone()
}

pub fn num(&self) -> u8 {
    self.value.clone()
}
}

This is to init your contract: near call $CONTRACT new --account_id $ CONTRACT where CONTRACT is your dev account - something like this: dev-1639289708038-48668463394280

near view $CONTRACT hello

View call: dev-1639289708038-48668463394280.hello() 'Default name'

Hopefully this can help.

Upvotes: 1

Related Questions