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