【问题标题】:Logging and tracing changes of mapping a struct记录和跟踪映射结构的变化
【发布时间】:2021-09-04 13:37:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: ethereum solidity smartcontracts web3


    【解决方案1】:

    首先,事件不支持结构,因为当前最新版本的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);
      
      ...
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 2016-10-29
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多