【问题标题】:How can I serialize a near-sdk-rs LookUpMap that uses a String as a key, or is there a better way?如何序列化使用字符串作为键的 near-sdk-rs LookUpMap,还是有更好的方法?
【发布时间】:2021-11-04 19:27:54
【问题描述】:

我正在向 Sputnik DAO v2 Near 合约添加一项功能,以将代币映射到投票数。

这是我的构造函数:


#[ext_contract(ext_self)]
pub trait Contract {
    fn exchange_callback_post_withdraw(&mut self, sender_id: AccountId, token_id: String, amount: U128);
}

#[near_bindgen]
impl Contract {
    #[init]
    pub fn new(
        owner_id: AccountId,
        token_ids: UnorderedSet<String>,
        unstake_period: U64,
        token_vote_weights: LookupMap<String, U128>,
    ) -> Self {
        Self {
            owner_id: owner_id.into(),
            vote_token_ids: token_ids,
            users: LookupMap::new(StorageKeys::Users),
            total_amount: UnorderedMap::new(StorageKeys::ValidNFTs),
            unstake_period: unstake_period.0,
            token_vote_weights,
        }
    }

发件人:https://github.com/roshkins/sputnik-dao-contract/blob/nft-tokensv4/sputnik-nft-staking/src/lib.rs#L59

我收到此错误:

error[E0277]: the trait bound `LookupMap<std::string::String, near_sdk::json_types::U128>: Serialize` is not satisfied
   --> sputnik-nft-staking/src/lib.rs:67:1
    |
67  | #[near_bindgen]
    | ^^^^^^^^^^^^^^^ the trait `Serialize` is not implemented for `LookupMap<std::string::String, near_sdk::json_types::U128>`
    | 
   ::: /home/rashi/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.64/src/value/mod.rs:965:8
    |
965 |     T: Serialize,
    |        --------- required by this bound in `to_value`
    |
    = note: required because of the requirements on the impl of `Serialize` for `&LookupMap<std::string::String, near_sdk::json_types::U128>`

我如何序列化字符串,或者是否有代码更改可以更好地帮助实现将投票权重与令牌相关联的目标?

【问题讨论】:

    标签: rust near-sdk-rs


    【解决方案1】:

    所以关于为什么不能序列化有两个要点(假设你期望它被序列化为地图):

    1. LookupMap 不会将所有键存储在存储中,因此它不可迭代并且不知道它包含什么。如果你想要一个可迭代的地图,你可以使用 SDK 中的UnorderedMap 或TreeMap。

    2. 即使它是可迭代的,就像上面提到的数据结构的情况一样,如果数据结构变大,加载所有元素的成本也非常高。默认情况下不会执行此序列化实现,因为通常应该避免它。

    如果您想以 JSON 格式返回整个合约状态,则必须手动实现序列化或将值放入可序列化的结构中。如果您确实想从存储中加载存储值以从函数返回,请考虑限制值的最大数量或进行某种分页。

    可以限制做这样的事情。不仅限于此,只是一种选择:

    let map: HashMap<K, V> = storage_map
                               .iter()
                               .skip(<skip first x elements for pagination>)
                               .take(<Max amount of elements to iterate>)
                               .collect();
    

    【讨论】:

    • 我把类型改成Hash,还是不行。我注意到它在错误中寻找Serde序列化,它不应该使用Borsh吗?
    • 我假设您想要为此进行 serde 序列化。你可以做borsh,但你选择哪一个并不重要。我指出的代码是用于当您需要为包含要序列化的内容的结构手动实现 serde::Serialize 时。我刚刚注意到您正在尝试将这些存储结构作为参数传递,您可能不想这样做,但我将在下面的答案中解决它。
    【解决方案2】:

    解决方案是覆盖序列化默认值,因为序列化是为 Borsh 实现的,而不是 JSON/serde:https://www.near-sdk.io/contract-interface/serialization-interface#overriding-serialization-protocol-default

    
    #[near_bindgen]
    impl Contract {
        #[init]
        pub fn new(
            #[serializer(borsh)] owner_id: AccountId,
            #[serializer(borsh)] token_ids: UnorderedSet<String>,
            #[serializer(borsh)] unstake_period: U64,
            #[serializer(borsh)] token_vote_weights: LookupMap<String, U128>,
        ) -> Self {
            Self {
                owner_id: owner_id.into(),
                vote_token_ids: token_ids,
                users: LookupMap::new(StorageKeys::Users),
                total_amount: UnorderedMap::new(StorageKeys::ValidNFTs),
                unstake_period: unstake_period.0,
                token_vote_weights,
            }
        }
    
        /// Total number of tokens staked in this contract.
        pub fn nft_total_supply(&self) -> U128 {
            let sum = 0;
            for i in self.total_amount.iter() {
                sum += i.1;
            }
            U128(sum)
        }
    

    【讨论】:

    • 所以我想我可能误解了你的问题。这些存储结构不应该作为参数传递,因为它们只会反序列化结构的元数据(在这种情况下,前缀应该始终是常量)。取而代之的是,您只需要使用std 结构以您想要的格式反序列化数据,然后在构造状态之前填充存储结构。我会写一个带有建议的新答案。
    • 修改代码比较容易,这里是提交:github.com/austinabell/sputnik-dao-contract/commit/…
    猜你喜欢
    • 1970-01-01
    • 2015-06-11
    • 2012-07-08
    • 2021-03-10
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多