secret_cosmwasm_std/results/system_result.rs
1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5use super::super::errors::SystemError;
6
7/// This is the outer result type returned by a querier to the contract.
8///
9/// We use a custom type here instead of Rust's Result because we want to be able to
10/// define the serialization, which is a public interface. Every language that compiles
11/// to Wasm and runs in the ComsWasm VM needs to create the same JSON representation.
12///
13/// # Examples
14///
15/// Success:
16///
17/// ```
18/// # use secret_cosmwasm_std::{to_vec, Binary, ContractResult, SystemResult};
19/// let data = Binary::from(b"hello, world");
20/// let result = SystemResult::Ok(ContractResult::Ok(data));
21/// assert_eq!(to_vec(&result).unwrap(), br#"{"Ok":{"Ok":"aGVsbG8sIHdvcmxk"}}"#);
22/// ```
23///
24/// Failure:
25///
26/// ```
27/// # use secret_cosmwasm_std::{to_vec, Binary, ContractResult, SystemResult, SystemError};
28/// let error = SystemError::Unknown {};
29/// let result: SystemResult<Binary> = SystemResult::Err(error);
30/// assert_eq!(to_vec(&result).unwrap(), br#"{"Err":{"unknown":{}}}"#);
31/// ```
32#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
33pub enum SystemResult<S> {
34 Ok(S),
35 Err(SystemError),
36}
37
38// Implementations here mimic the Result API and should be implemented via a conversion to Result
39// to ensure API consistency
40impl<S> SystemResult<S> {
41 /// Converts a `ContractResult<S>` to a `Result<S, SystemError>` as a convenient way
42 /// to access the full Result API.
43 pub fn into_result(self) -> Result<S, SystemError> {
44 Result::<S, SystemError>::from(self)
45 }
46
47 pub fn unwrap(self) -> S {
48 self.into_result().unwrap()
49 }
50}
51
52impl<S: fmt::Debug> SystemResult<S> {
53 pub fn unwrap_err(self) -> SystemError {
54 self.into_result().unwrap_err()
55 }
56}
57
58impl<S> From<Result<S, SystemError>> for SystemResult<S> {
59 fn from(original: Result<S, SystemError>) -> SystemResult<S> {
60 match original {
61 Ok(value) => SystemResult::Ok(value),
62 Err(err) => SystemResult::Err(err),
63 }
64 }
65}
66
67impl<S> From<SystemResult<S>> for Result<S, SystemError> {
68 fn from(original: SystemResult<S>) -> Result<S, SystemError> {
69 match original {
70 SystemResult::Ok(value) => Ok(value),
71 SystemResult::Err(err) => Err(err),
72 }
73 }
74}