2

部署简单合约

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

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

试图通过调用视图方法

near view crossword.hilonom.testnet num

并且有错误

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"
}

我怎样才能避免这个错误?

4

2 回答 2

1

你在这里使用 Struct,在部署你的合约之后,你可能需要先初始化它。

#[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()
}
}

这是为了启动您的合同: near call $CONTRACT new --account_id $ CONTRACT其中 CONTRACT 是您的开发帐户 - 类似于:dev-1639289708038-48668463394280

near view $CONTRACT hello

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

希望这可以提供帮助。

于 2021-12-12T06:25:30.303 回答
0

可以修改状态的方法将被禁止查看。

这背后的原因是

    /// 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
    /// ```

我也遇到了这个问题,我按照建议查看了https://docs.near.org/docs/roles/integrator/errors/error-implementation#hosterror枚举

/// `method_name` is not allowed in view calls
    ProhibitedInView { method_name: String },
于 2022-02-28T05:30:30.170 回答