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_json_string, Binary, ContractResult, SystemResult};
20/// let data = Binary::from(b"hello, world");
21/// let result = SystemResult::Ok(ContractResult::Ok(data));
22/// assert_eq!(to_json_string(&result).unwrap(), r#"{"ok":{"ok":"aGVsbG8sIHdvcmxk"}}"#);
23/// ```
24///
25/// Failure:
26///
27/// ```
28/// # use cosmwasm_std::{to_json_string, Binary, ContractResult, SystemResult, SystemError};
29/// let error = SystemError::Unknown {};
30/// let result: SystemResult<Binary> = SystemResult::Err(error);
31/// assert_eq!(to_json_string(&result).unwrap(), r#"{"error":{"unknown":{}}}"#);
32/// ```
33#[derive(
34 Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, cw_schema::Schemaifier,
35)]
36#[serde(rename_all = "snake_case")]
37pub enum SystemResult<S> {
38 Ok(S),
39 #[serde(rename = "error")]
40 Err(SystemError),
41}
42
43// Implementations here mimic the Result API and should be implemented via a conversion to Result
44// to ensure API consistency
45impl<S> SystemResult<S> {
46 /// Converts a `ContractResult<S>` to a `Result<S, SystemError>` as a convenient way
47 /// to access the full Result API.
48 pub fn into_result(self) -> Result<S, SystemError> {
49 Result::<S, SystemError>::from(self)
50 }
51
52 pub fn unwrap(self) -> S {
53 self.into_result().unwrap()
54 }
55}
56
57impl<S: fmt::Debug> SystemResult<S> {
58 pub fn unwrap_err(self) -> SystemError {
59 self.into_result().unwrap_err()
60 }
61}
62
63impl<S> From<Result<S, SystemError>> for SystemResult<S> {
64 fn from(original: Result<S, SystemError>) -> SystemResult<S> {
65 match original {
66 Ok(value) => SystemResult::Ok(value),
67 Err(err) => SystemResult::Err(err),
68 }
69 }
70}
71
72impl<S> From<SystemResult<S>> for Result<S, SystemError> {
73 fn from(original: SystemResult<S>) -> Result<S, SystemError> {
74 match original {
75 SystemResult::Ok(value) => Ok(value),
76 SystemResult::Err(err) => Err(err),
77 }
78 }
79}