[英]How to set a static field in a NEAR smart contract?
我正在为托管制定智能合约。 其中将有一个所有者,应该在部署合同期间设置一次。
但是,这如何在 NEAR 中实现呢?
一段简化的代码:
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Escrow {
pub owner_id: AccountId,
pub user1_id: AccountId,
pub user2_id: AccountId,
pub amount: Balance,
}
#[near_bindgen]
impl Escrow {
#[init]
#[private]
pub fn init(&self, owner_id: AccountId) -> Self {
assert!(!env::state_exists(), "Already initialized");
self.owner_id = env::signer_account_id(); //??? instance variable ???
}
//...........
}
self.owner_id
是一个实例变量。 因此,每个使用合同的新客户都会有所不同,因此每次都需要一次又一次地初始化?
在普通的 Rust 代码中,这个变量将是 static,const 或 function。但在这里它必须一次性初始化,并且对于所有 Escrow 实例都是相同的。
这将如何在 NEAR 中实现?
这是owner_id = env::signer_account_id();
引用部署合同地址的正确方法?
near-sdk-rs
将合约实例( Escrow
结构)转换为区块链上的 singleton,因此无论您保存到self
什么都会存储在合约的键值存储中,因此它是“静态的”。 init
方法不应将self
作为参数,它应该构造实例(返回Self
),并且预计只调用一次。 你初始化你的合约一次,然后定义其他可以更新&mut self
的方法。 near-sdk-rs
文档对此进行了详细介绍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.