使用未声明的类型或模块 near_blockchain

Use of undeclared type or module near_blockchain

我在尝试编译 NEAR 智能合约时遇到以下错误,但仅在编译为 wasm 目标时出现

   Compiling nep9000 v0.1.0 (/Users/mikkoohtamaa/code/advanced-fungible-token/contract)
error[E0433]: failed to resolve: use of undeclared type or module `near_blockchain`
   --> src/token.rs:144:1
    |
144 | #[near_bindgen]
    | ^^^^^^^^^^^^^^^ use of undeclared type or module `near_blockchain```

正常cargo build即可。

看来您需要在合同的 structimpl 上声明 #[near_bindgen],仅 impl 是不够的。

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Token {
   ...
}


#[near_bindgen]
impl Token {

   ...
}

如果您在将 Rust 智能合约分解为单独的文件时遇到此错误,请使用 use crate::*; 而不是您的 IDE 可能建议的内容。

例如,假设我们的项目中有这样的文件结构:

.
├── Cargo.lock
├── Cargo.toml
├── src
│  ├── my_mod.rs.     ⟵ here is the module file
│  └── lib.rs
└── build-and-test.sh

添加新文件时,例如 my_mod.rs,您需要确保 lib.rs 具有:

mod my_mod;

my_mod.rs 中,您的 IDE 可能会建议:

use crate::Contract;

应替换为:

use crate::*;