在事件类型之间转换

Converting between event types

是否有关于如何正确比较来自 frame_system::Module::events() 的事件是否等于来自当前托盘 decl_event! 的特定事件的线索?

我尝试将列表中的事件与内部 PostCreated 事件相匹配:

let events: Vec<EventRecord<<T as system::Trait>::Event, T::Hash>> = SystemModule::<T>::events();
        
events.iter().filter(|EventRecord { event, .. }| {
    matches!(event, RawEvent::PostCreated(_, _))
});

但是,出现错误:

428 |             matches!(event, RawEvent::PostCreated(_, _))
    |                      -----  ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected associated type, found enum `RawEvent`
    |                      |
    |                      this expression has type `&<T as frame_system::Trait>::Event`
    |
    = note: expected associated type `<T as frame_system::Trait>::Event`
                          found enum `RawEvent<_>`
    = help: consider constraining the associated type `<T as frame_system::Trait>::Event` to `RawEvent<_>`

此外,如果我将 .into() 添加到事件中,我会收到另一个错误:

428 |             matches!(event.into(), RawEvent::PostCreated(_, _))
    |                            ^^^^ the trait `std::convert::From<&<T as frame_system::Trait>::Event>` is not implemented for `RawEvent<_>`
    |
    = note: required because of the requirements on the impl of `std::convert::Into<RawEvent<_>>` for `&<T as frame_system::Trait>::Event`

如有任何帮助,我将不胜感激。确定这行代码确实有问题。

你的“通用”事件类型应该在你的配置特征中这样定义:

/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;

这意味着我们支持托盘中定义的 Event 枚举的 From 特性,以及 [=16] 中 Event 枚举的 Into 特性=]托盘。

所以转换可以如下:

  • 原始事件 -> 通用事件
  • 一般事件 -> 系统事件

所以:

let generic_event: <T as Trait>::Event = RawEvent::MyEvent.into();
let system_event: <T as frame_system::Trait>::Event = generic_event.into();

然后您可以将此 system_event 与您从 frame_system::Module::<T>::events() 返回的事件进行比较。