diem_types/
contract_event.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use crate::event::EventKey;
9use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
10
11use serde::{Deserialize, Serialize};
12use std::ops::Deref;
13
14/// Support versioning of the data structure.
15#[derive(
16    Hash,
17    Clone,
18    Eq,
19    PartialEq,
20    Serialize,
21    Deserialize,
22    CryptoHasher,
23    BCSCryptoHash,
24)]
25pub enum ContractEvent {
26    V0(ContractEventV0),
27}
28
29impl ContractEvent {
30    pub fn new(key: EventKey, event_data: Vec<u8>) -> Self {
31        ContractEvent::V0(ContractEventV0::new(key, event_data))
32    }
33}
34
35// Temporary hack to avoid massive changes, it won't work when new variant comes
36// and needs proper dispatch at that time.
37impl Deref for ContractEvent {
38    type Target = ContractEventV0;
39
40    fn deref(&self) -> &Self::Target {
41        match self {
42            ContractEvent::V0(event) => event,
43        }
44    }
45}
46
47/// Entry produced via a call to the `emit_event` builtin.
48#[derive(Hash, Clone, Eq, PartialEq, Serialize, Deserialize, CryptoHasher)]
49pub struct ContractEventV0 {
50    /// The unique key that the event was emitted to
51    key: EventKey,
52    /// The data payload of the event
53    #[serde(with = "serde_bytes")]
54    event_data: Vec<u8>,
55}
56
57impl ContractEventV0 {
58    pub fn new(key: EventKey, event_data: Vec<u8>) -> Self {
59        Self { key, event_data }
60    }
61
62    pub fn key(&self) -> &EventKey { &self.key }
63
64    pub fn event_data(&self) -> &[u8] { &self.event_data }
65}
66
67impl std::fmt::Debug for ContractEvent {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        write!(
70            f,
71            "ContractEvent {{ key: {:?}, event_data: {:?} }}",
72            self.key,
73            hex::encode(&self.event_data)
74        )
75    }
76}
77
78impl std::fmt::Display for ContractEvent {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "{:?}", self)
81    }
82}