"The collection is an inconsistent state." 嵌套 NEAR 集合

"The collection is an inconsistent state." with nested NEAR collection

我 运行 遇到了嵌套 NEAR 集合(在本例中 TreeMap)可能会出现此错误的问题:

The collection is an inconsistent state. Did previous smart contract execution terminate unexpectedly?

我使用的结构如下所示:

pub struct CollectionIssues {
    nested_treemap: TreeMap<AccountId, TreeMap<u128, String>>,
}

然后我们:

  1. 向内部和外部 TreeMap 添加条目。
  2. 删除 TreeMap 的键(这里是 AccountId
  3. 尝试重新添加相同的条目。
  4. 收到上述错误。

我在这里提供了一个演示存储库:

https://github.com/mikedotexe/near-collections-issue

复制、克隆和运行./test.sh

问题是如何创建 TreeMap。初始化集合时,需要指定唯一前缀。默认情况下,它使用全局 auto-increment。当集合保存到状态时,它的前缀也保存到状态,但全局 auto-increment 计数器不会持久化。因此,当您重新插入新地图时,它会使用不唯一的 auto-increment 前缀值并与现有集合发生冲突。

避免它的最好方法是为使用 TreeMap::new(unique_prefix) 创建的每个 TreeMap 提供一个唯一的前缀。您的案例中的唯一前缀可以是 env::sha256(account_id) 第一个集合中的键。

FungibleToken 实现中的示例:https://github.com/near/near-sdk-rs/blob/ac8c849fba6b912a5ef46d156662b3e1f6b56894/examples/fungible-token/src/lib.rs#L43

请注意如何为给定帐户初始化配额图。