我有一个结构,并在映射中使用它。
struct Cotton{
uint256 balance;
string form;
address producer;
string certificate;
}
mapping(address=>Cotton) public cotton;
我可以访问棉花的最后值。然而,一旦有许多事务,我也需要访问它以前的状态。我尝试过发出一个事件,但它不接受结构作为输入参数。有没有办法检索棉花上的所有更改?
首先,事件不支持structs,因为对于当前最新版本的solidity(0.8.6(,您需要将特定的值类型变量(address、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);
...
}