referrerpolicy=no-referrer-when-downgrade

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
98impl<Hash> TransactionEvent<Hash> {
99	/// Returns true if this is the last event emitted by the RPC subscription.
100	pub fn is_final(&self) -> bool {
101		matches!(
102			&self,
103			TransactionEvent::Finalized(_) |
104				TransactionEvent::Error(_) |
105				TransactionEvent::Invalid(_) |
106				TransactionEvent::Dropped(_)
107		)
108	}
109}
110
111/// Intermediate representation (IR) for the transaction events
112/// that handles block events only.
113///
114/// The block events require a JSON compatible interpretation similar to:
115///
116/// ```json
117/// { event: "EVENT", block: { hash: "0xFF", index: 0 } }
118/// ```
119///
120/// This IR is introduced to circumvent that the block events need to
121/// be serialized/deserialized with "tag" and "content", while other
122/// events only require "tag".
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125#[serde(tag = "event", content = "block")]
126enum TransactionEventBlockIR<Hash> {
127	/// The transaction was included in the best block of the chain.
128	BestChainBlockIncluded(Option<TransactionBlock<Hash>>),
129	/// The transaction was included in a finalized block of the chain.
130	Finalized(TransactionBlock<Hash>),
131}
132
133/// Intermediate representation (IR) for the transaction events
134/// that handles non-block events only.
135///
136/// The non-block events require a JSON compatible interpretation similar to:
137///
138/// ```json
139/// { event: "EVENT", num_peers: 0 }
140/// ```
141///
142/// This IR is introduced to circumvent that the block events need to
143/// be serialized/deserialized with "tag" and "content", while other
144/// events only require "tag".
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146#[serde(rename_all = "camelCase")]
147#[serde(tag = "event")]
148enum TransactionEventNonBlockIR {
149	Validated,
150	Error(TransactionError),
151	Invalid(TransactionError),
152	Dropped(TransactionDropped),
153}
154
155/// Intermediate representation (IR) used for serialization/deserialization of the
156/// [`TransactionEvent`] in a JSON compatible format.
157///
158/// Serde cannot mix `#[serde(tag = "event")]` with `#[serde(tag = "event", content = "block")]`
159/// for specific enum variants. Therefore, this IR is introduced to circumvent this
160/// restriction, while exposing a simplified [`TransactionEvent`] for users of the
161/// rust ecosystem.
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[serde(bound(serialize = "Hash: Serialize", deserialize = "Hash: Deserialize<'de>"))]
164#[serde(rename_all = "camelCase")]
165#[serde(untagged)]
166enum TransactionEventIR<Hash> {
167	Block(TransactionEventBlockIR<Hash>),
168	NonBlock(TransactionEventNonBlockIR),
169}
170
171impl<Hash> From<TransactionEvent<Hash>> for TransactionEventIR<Hash> {
172	fn from(value: TransactionEvent<Hash>) -> Self {
173		match value {
174			TransactionEvent::Validated =>
175				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Validated),
176			TransactionEvent::BestChainBlockIncluded(event) =>
177				TransactionEventIR::Block(TransactionEventBlockIR::BestChainBlockIncluded(event)),
178			TransactionEvent::Finalized(event) =>
179				TransactionEventIR::Block(TransactionEventBlockIR::Finalized(event)),
180			TransactionEvent::Error(event) =>
181				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Error(event)),
182			TransactionEvent::Invalid(event) =>
183				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Invalid(event)),
184			TransactionEvent::Dropped(event) =>
185				TransactionEventIR::NonBlock(TransactionEventNonBlockIR::Dropped(event)),
186		}
187	}
188}
189
190impl<Hash> From<TransactionEventIR<Hash>> for TransactionEvent<Hash> {
191	fn from(value: TransactionEventIR<Hash>) -> Self {
192		match value {
193			TransactionEventIR::NonBlock(status) => match status {
194				TransactionEventNonBlockIR::Validated => TransactionEvent::Validated,
195				TransactionEventNonBlockIR::Error(event) => TransactionEvent::Error(event),
196				TransactionEventNonBlockIR::Invalid(event) => TransactionEvent::Invalid(event),
197				TransactionEventNonBlockIR::Dropped(event) => TransactionEvent::Dropped(event),
198			},
199			TransactionEventIR::Block(block) => match block {
200				TransactionEventBlockIR::Finalized(event) => TransactionEvent::Finalized(event),
201				TransactionEventBlockIR::BestChainBlockIncluded(event) =>
202					TransactionEvent::BestChainBlockIncluded(event),
203			},
204		}
205	}
206}
207
208#[cfg(test)]
209mod tests {
210	use super::*;
211	use sp_core::H256;
212
213	#[test]
214	fn validated_event() {
215		let event: TransactionEvent<()> = TransactionEvent::Validated;
216		let ser = serde_json::to_string(&event).unwrap();
217
218		let exp = r#"{"event":"validated"}"#;
219		assert_eq!(ser, exp);
220
221		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
222		assert_eq!(event_dec, event);
223	}
224
225	#[test]
226	fn best_chain_event() {
227		let event: TransactionEvent<()> = TransactionEvent::BestChainBlockIncluded(None);
228		let ser = serde_json::to_string(&event).unwrap();
229
230		let exp = r#"{"event":"bestChainBlockIncluded","block":null}"#;
231		assert_eq!(ser, exp);
232
233		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
234		assert_eq!(event_dec, event);
235
236		let event: TransactionEvent<H256> =
237			TransactionEvent::BestChainBlockIncluded(Some(TransactionBlock {
238				hash: H256::from_low_u64_be(1),
239				index: 2,
240			}));
241		let ser = serde_json::to_string(&event).unwrap();
242
243		let exp = r#"{"event":"bestChainBlockIncluded","block":{"hash":"0x0000000000000000000000000000000000000000000000000000000000000001","index":2}}"#;
244		assert_eq!(ser, exp);
245
246		let event_dec: TransactionEvent<H256> = serde_json::from_str(exp).unwrap();
247		assert_eq!(event_dec, event);
248	}
249
250	#[test]
251	fn finalized_event() {
252		let event: TransactionEvent<H256> = TransactionEvent::Finalized(TransactionBlock {
253			hash: H256::from_low_u64_be(1),
254			index: 10,
255		});
256		let ser = serde_json::to_string(&event).unwrap();
257
258		let exp = r#"{"event":"finalized","block":{"hash":"0x0000000000000000000000000000000000000000000000000000000000000001","index":10}}"#;
259		assert_eq!(ser, exp);
260
261		let event_dec: TransactionEvent<H256> = serde_json::from_str(exp).unwrap();
262		assert_eq!(event_dec, event);
263	}
264
265	#[test]
266	fn error_event() {
267		let event: TransactionEvent<()> =
268			TransactionEvent::Error(TransactionError { error: "abc".to_string() });
269		let ser = serde_json::to_string(&event).unwrap();
270
271		let exp = r#"{"event":"error","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 invalid_event() {
280		let event: TransactionEvent<()> =
281			TransactionEvent::Invalid(TransactionError { error: "abc".to_string() });
282		let ser = serde_json::to_string(&event).unwrap();
283
284		let exp = r#"{"event":"invalid","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
291	#[test]
292	fn dropped_event() {
293		let event: TransactionEvent<()> =
294			TransactionEvent::Dropped(TransactionDropped { error: "abc".to_string() });
295		let ser = serde_json::to_string(&event).unwrap();
296
297		let exp = r#"{"event":"dropped","error":"abc"}"#;
298		assert_eq!(ser, exp);
299
300		let event_dec: TransactionEvent<()> = serde_json::from_str(exp).unwrap();
301		assert_eq!(event_dec, event);
302	}
303}