sc_rpc_spec_v2/transaction/
event.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! The transaction's event returned as json compatible object.
20
21use serde::{Deserialize, Serialize};
22
23/// The transaction was included in a block of the chain.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26pub struct TransactionBlock<Hash> {
27	/// The hash of the block the transaction was included into.
28	pub hash: Hash,
29	/// The index (zero-based) of the transaction within the body of the block.
30	pub index: usize,
31}
32
33/// The transaction could not be processed due to an error.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct TransactionError {
37	/// Reason of the error.
38	pub error: String,
39}
40
41/// The transaction was dropped because of exceeding limits.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct TransactionDropped {
45	/// Reason of the event.
46	pub error: String,
47}
48
49/// Possible transaction status events.
50///
51/// The status events can be grouped based on their kinds as:
52///
53/// 1. Runtime validated the transaction and it entered the pool:
54/// 		- `Validated`
55///
56/// 2. Leaving the pool:
57/// 		- `BestChainBlockIncluded`
58/// 		- `Invalid`
59///
60/// 3. Block finalized:
61/// 		- `Finalized`
62///
63/// 4. At any time:
64/// 		- `Dropped`
65/// 		- `Error`
66///
67/// The subscription's stream is considered finished whenever the following events are
68/// received: `Finalized`, `Error`, `Invalid` or `Dropped`. However, the user is allowed
69/// to unsubscribe at any moment.
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
71// We need to manually specify the trait bounds for the `Hash` trait to ensure `into` and
72// `from` still work.
73#[serde(bound(
74	serialize = "Hash: Serialize + Clone",
75	deserialize = "Hash: Deserialize<'de> + Clone"
76))]
77#[serde(into = "TransactionEventIR<Hash>", from = "TransactionEventIR<Hash>")]
78pub enum TransactionEvent<Hash> {
79	/// The transaction was validated by the runtime.
80	Validated,
81	/// The transaction was included in a best block of the chain.
82	///
83	/// # Note
84	///
85	/// This may contain `None` if the block is no longer a best
86	/// block of the chain.
87	BestChainBlockIncluded(Option<TransactionBlock<Hash>>),
88	/// The transaction was included in a finalized block.
89	Finalized(TransactionBlock<Hash>),
90	/// The transaction could not be processed due to an error.
91	Error(TransactionError),
92	/// The transaction is marked as invalid.
93	Invalid(TransactionError),
94	/// The client was not capable of keeping track of this transaction.
95	Dropped(TransactionDropped),
96}
97
98/// Intermediate representation (IR) for the transaction events
99/// that handles block events only.
100///
101/// The block events require a JSON compatible interpretation similar to:
102///
103/// ```json
104/// { event: "EVENT", block: { hash: "0xFF", index: 0 } }
105/// ```
106///
107/// This IR is introduced to circumvent that the block events need to
108/// be serialized/deserialized with "tag" and "content", while other
109/// events only require "tag".
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111#[serde(rename_all = "camelCase")]
112#[serde(tag = "event", content = "block")]
113enum TransactionEventBlockIR<Hash> {
114	/// The transaction was included in the best block of the chain.
115	BestChainBlockIncluded(Option<TransactionBlock<Hash>>),
116	/// The transaction was included in a finalized block of the chain.
117	Finalized(TransactionBlock<Hash>),
118}
119
120/// Intermediate representation (IR) for the transaction events
121/// that handles non-block events only.
122///
123/// The non-block events require a JSON compatible interpretation similar to:
124///
125/// ```json
126/// { event: "EVENT", num_peers: 0 }
127/// ```
128///
129/// This IR is introduced to circumvent that the block events need to
130/// be serialized/deserialized with "tag" and "content", while other
131/// events only require "tag".
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
133#[serde(rename_all = "camelCase")]
134#[serde(tag = "event")]
135enum TransactionEventNonBlockIR {
136	Validated,
137	Error(TransactionError),
138	Invalid(TransactionError),
139	Dropped(TransactionDropped),
140}
141
142/// Intermediate representation (IR) used for serialization/deserialization of the
143/// [`TransactionEvent`] in a JSON compatible format.
144///
145/// Serde cannot mix `#[serde(tag = "event")]` with `#[serde(tag = "event", content = "block")]`
146/// for specific enum variants. Therefore, this IR is introduced to circumvent this
147/// restriction, while exposing a simplified [`TransactionEvent`] for users of the
148/// rust ecosystem.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150#[serde(bound(serialize = "Hash: Serialize", deserialize = "Hash: Deserialize<'de>"))]
151#[serde(rename_all = "camelCase")]
152#[serde(untagged)]
153enum TransactionEventIR<Hash> {
154	Block(TransactionEventBlockIR<Hash>),
155	NonBlock(TransactionEventNonBlockIR),
156}
157
158impl<Hash> From<TransactionEvent<Hash>> for TransactionEventIR<Hash> {
159	fn from(value: TransactionEvent<Hash>) -> Self {
160		match value {
161			TransactionEvent::Validated =>
162				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Validated),
163			TransactionEvent::BestChainBlockIncluded(event) =>
164				TransactionEventIR::Block(TransactionEventBlockIR::BestChainBlockIncluded(event)),
165			TransactionEvent::Finalized(event) =>
166				TransactionEventIR::Block(TransactionEventBlockIR::Finalized(event)),
167			TransactionEvent::Error(event) =>
168				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Error(event)),
169			TransactionEvent::Invalid(event) =>
170				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Invalid(event)),
171			TransactionEvent::Dropped(event) =>
172				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Dropped(event)),
173		}
174	}
175}
176
177impl<Hash> From<TransactionEventIR<Hash>> for TransactionEvent<Hash> {
178	fn from(value: TransactionEventIR<Hash>) -> Self {
179		match value {
180			TransactionEventIR::NonBlock(status) => match status {
181				TransactionEventNonBlockIR::Validated => TransactionEvent::Validated,
182				TransactionEventNonBlockIR::Error(event) => TransactionEvent::Error(event),
183				TransactionEventNonBlockIR::Invalid(event) => TransactionEvent::Invalid(event),
184				TransactionEventNonBlockIR::Dropped(event) => TransactionEvent::Dropped(event),
185			},
186			TransactionEventIR::Block(block) => match block {
187				TransactionEventBlockIR::Finalized(event) => TransactionEvent::Finalized(event),
188				TransactionEventBlockIR::BestChainBlockIncluded(event) =>
189					TransactionEvent::BestChainBlockIncluded(event),
190			},
191		}
192	}
193}
194
195#[cfg(test)]
196mod tests {
197	use super::*;
198	use sp_core::H256;
199
200	#[test]
201	fn validated_event() {
202		let event: TransactionEvent<()> = TransactionEvent::Validated;
203		let ser = serde_json::to_string(&event).unwrap();
204
205		let exp = r#"{"event":"validated"}"#;
206		assert_eq!(ser, exp);
207
208		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
209		assert_eq!(event_dec, event);
210	}
211
212	#[test]
213	fn best_chain_event() {
214		let event: TransactionEvent<()> = TransactionEvent::BestChainBlockIncluded(None);
215		let ser = serde_json::to_string(&event).unwrap();
216
217		let exp = r#"{"event":"bestChainBlockIncluded","block":null}"#;
218		assert_eq!(ser, exp);
219
220		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
221		assert_eq!(event_dec, event);
222
223		let event: TransactionEvent<H256> =
224			TransactionEvent::BestChainBlockIncluded(Some(TransactionBlock {
225				hash: H256::from_low_u64_be(1),
226				index: 2,
227			}));
228		let ser = serde_json::to_string(&event).unwrap();
229
230		let exp = r#"{"event":"bestChainBlockIncluded","block":{"hash":"0x0000000000000000000000000000000000000000000000000000000000000001","index":2}}"#;
231		assert_eq!(ser, exp);
232
233		let event_dec: TransactionEvent<H256> = serde_json::from_str(exp).unwrap();
234		assert_eq!(event_dec, event);
235	}
236
237	#[test]
238	fn finalized_event() {
239		let event: TransactionEvent<H256> = TransactionEvent::Finalized(TransactionBlock {
240			hash: H256::from_low_u64_be(1),
241			index: 10,
242		});
243		let ser = serde_json::to_string(&event).unwrap();
244
245		let exp = r#"{"event":"finalized","block":{"hash":"0x0000000000000000000000000000000000000000000000000000000000000001","index":10}}"#;
246		assert_eq!(ser, exp);
247
248		let event_dec: TransactionEvent<H256> = serde_json::from_str(exp).unwrap();
249		assert_eq!(event_dec, event);
250	}
251
252	#[test]
253	fn error_event() {
254		let event: TransactionEvent<()> =
255			TransactionEvent::Error(TransactionError { error: "abc".to_string() });
256		let ser = serde_json::to_string(&event).unwrap();
257
258		let exp = r#"{"event":"error","error":"abc"}"#;
259		assert_eq!(ser, exp);
260
261		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
262		assert_eq!(event_dec, event);
263	}
264
265	#[test]
266	fn invalid_event() {
267		let event: TransactionEvent<()> =
268			TransactionEvent::Invalid(TransactionError { error: "abc".to_string() });
269		let ser = serde_json::to_string(&event).unwrap();
270
271		let exp = r#"{"event":"invalid","error":"abc"}"#;
272		assert_eq!(ser, exp);
273
274		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
275		assert_eq!(event_dec, event);
276	}
277
278	#[test]
279	fn dropped_event() {
280		let event: TransactionEvent<()> =
281			TransactionEvent::Dropped(TransactionDropped { error: "abc".to_string() });
282		let ser = serde_json::to_string(&event).unwrap();
283
284		let exp = r#"{"event":"dropped","error":"abc"}"#;
285		assert_eq!(ser, exp);
286
287		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
288		assert_eq!(event_dec, event);
289	}
290}