referrerpolicy=no-referrer-when-downgrade

sc_rpc_spec_v2/archive/
types.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
19use serde::{Deserialize, Serialize};
20
21/// The result of an RPC method.
22#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
23#[serde(untagged)]
24pub enum MethodResult {
25	/// Method generated a result.
26	Ok(MethodResultOk),
27	/// Method encountered an error.
28	Err(MethodResultErr),
29}
30
31impl MethodResult {
32	/// Constructs a successful result.
33	pub fn ok(result: impl Into<String>) -> MethodResult {
34		MethodResult::Ok(MethodResultOk { success: true, value: result.into() })
35	}
36
37	/// Constructs an error result.
38	pub fn err(error: impl Into<String>) -> MethodResult {
39		MethodResult::Err(MethodResultErr { success: false, error: error.into() })
40	}
41}
42
43/// The successful result of an RPC method.
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct MethodResultOk {
47	/// Method was successful.
48	pub success: bool,
49	/// The result of the method.
50	pub value: String,
51}
52
53/// The error result of an RPC method.
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55#[serde(rename_all = "camelCase")]
56pub struct MethodResultErr {
57	/// Method encountered an error.
58	pub success: bool,
59	/// The error of the method.
60	pub error: String,
61}
62
63#[cfg(test)]
64mod tests {
65	use super::*;
66
67	#[test]
68	fn method_result_ok() {
69		let ok = MethodResult::ok("hello");
70
71		let ser = serde_json::to_string(&ok).unwrap();
72		let exp = r#"{"success":true,"value":"hello"}"#;
73		assert_eq!(ser, exp);
74
75		let ok_dec: MethodResult = serde_json::from_str(exp).unwrap();
76		assert_eq!(ok_dec, ok);
77	}
78
79	#[test]
80	fn method_result_error() {
81		let ok = MethodResult::err("hello");
82
83		let ser = serde_json::to_string(&ok).unwrap();
84		let exp = r#"{"success":false,"error":"hello"}"#;
85		assert_eq!(ser, exp);
86
87		let ok_dec: MethodResult = serde_json::from_str(exp).unwrap();
88		assert_eq!(ok_dec, ok);
89	}
90}