简体   繁体   English

如何在NEAR智能合约中设置static字段?

[英]How to set a static field in a NEAR smart contract?

I'm working on a smart contract for escrow.我正在为托管制定智能合约。 In it there'll be the owner who'll supposed to be set once -- during deploying a contract.其中将有一个所有者,应该在部署合同期间设置一次。

How can this be implemented in NEAR, though?但是,这如何在 NEAR 中实现呢?

A simplified piece of code:一段简化的代码:

#[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 is an instance variable. self.owner_id是一个实例变量。 Therefore, it'd be different for each new client who uses the contract, and therefore would require initialization again, and again, each time?因此,每个使用合同的新客户都会有所不同,因此每次都需要一次又一次地初始化?

In the ordinary Rust code this variable would be static, const or a function. But here it has to be initialized only once and for all , and yet be identical for all the instance of Escrow.在普通的 Rust 代码中,这个变量将是 static,const 或 function。但在这里它必须一次性初始化,并且对于所有 Escrow 实例都是相同的。

How would this be implemented in NEAR?这将如何在 NEAR 中实现?


Is this owner_id = env::signer_account_id();这是owner_id = env::signer_account_id(); a correct way to refer to the address who's deploying a contract?引用部署合同地址的正确方法?

near-sdk-rs turns the contract instance ( Escrow struct) into a singleton on a blockchain, so whatever you save to self will be then stored in the key-value storage of your contract, so it is "static". near-sdk-rs将合约实例( Escrow结构)转换为区块链上的 singleton,因此无论您保存到self什么都会存储在合约的键值存储中,因此它是“静态的”。 init method should not take self as a parameter, it should construct the instance (return Self ), and it is expected to be called only once. init方法不应将self作为参数,它应该构造实例(返回Self ),并且预计只调用一次。 You initialize your contract once, and then define other methods that could update &mut self .你初始化你的合约一次,然后定义其他可以更新&mut self的方法。 near-sdk-rs documentation goes into details about that. near-sdk-rs文档对此进行了详细介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM