微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

记录和跟踪映射结构的更改

如何解决记录和跟踪映射结构的更改

我有一个结构体并在映射中使用它。

struct Cotton{
    uint256 balance;
    string form;
    address producer;
    string certificate;
}
mapping(address=>Cotton) public cotton;

我能够访问 cotton 的最后一个值。但是,一旦有很多交易,我也需要访问它的先前状态。 我尝试发出一个事件,但它不接受结构作为输入参数。 有没有办法检索 cotton 上的所有更改?

解决方法

首先,对于当前最新版本的solidity(0.8.6),事件不支持结构,您需要将特定的值类型变量(地址、uint等)传递到事件中。

...

// Event for cotton
event oracleCotton(uint256 balance,string form,address producer,string certificate);

...

// Emit event.
emit oracleCotton(cotton.balance,cotton.form,cotton.producer,cotton.certificate);

...

此外,无法访问以前的数据状态,因为当您将新的 Cotton 分配给地址时,它会覆盖前一个。

针对您的问题的解决方案类似于以下内容:

...

struct Cotton{
    uint256 balance;
    string form;
    address producer;
    string certificate;
}

struct CottonWrapper{
    uint256 counter;
    Cotton[] cottonHistory;     
}

mapping(address => CottonWrapper) public cotton;

...

然后……

// Logic to iterate over each cotton of an address.
for (uint i = cotton[address].counter; i > 0; i--) {
  Cotton memory c = cotton[address].cottonHistory[i];
  
  // Now here you can do whatever you want with that cotton.
  emit oracleCotton(c.balance,c.form,c.producer,c.certificate);
  
  ...

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。