Skip to content

Commit

Permalink
Add StdAck
Browse files Browse the repository at this point in the history
  • Loading branch information
webmaster128 committed Mar 15, 2023
1 parent 50079b4 commit f0b95cf
Show file tree
Hide file tree
Showing 2 changed files with 138 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod query;
mod results;
mod sections;
mod serde;
mod stdack;
mod storage;
mod timestamp;
mod traits;
Expand Down Expand Up @@ -80,6 +81,7 @@ pub use crate::results::{DistributionMsg, StakingMsg};
#[cfg(feature = "stargate")]
pub use crate::results::{GovMsg, VoteOption};
pub use crate::serde::{from_binary, from_slice, to_binary, to_vec};
pub use crate::stdack::StdAck;
pub use crate::storage::MemoryStorage;
pub use crate::timestamp::Timestamp;
pub use crate::traits::{Api, Querier, QuerierResult, QuerierWrapper, Storage};
Expand Down
136 changes: 136 additions & 0 deletions packages/std/src/stdack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::binary::Binary;
use crate::{from_slice, to_binary, StdResult};

/// This is a standard IBC acknowledgement type. IBC application are free
/// to use any acknowledgement format they want. However, for compatibility
/// purposes it is recommended to use this.
///
/// The original proto definition can be found at <https://github.com/cosmos/cosmos-sdk/blob/v0.42.0/proto/ibc/core/channel/v1/channel.proto#L141-L147>
/// and <https://github.com/cosmos/ibc/tree/ed849c7bac/spec/core/ics-004-channel-and-packet-semantics#acknowledgement-envelope>.
///
/// In contrast to the original idea, [ICS-20](https://github.com/cosmos/ibc/tree/ed849c7bacf16204e9509f0f0df325391f3ce25c/spec/app/ics-020-fungible-token-transfer#technical-specification) and CosmWasm IBC protocols
/// use JSON instead of a protobuf serialization.
///
/// If ibc_receive_packet returns Err(), then x/wasm runtime will rollback the state and return an error message in this format.
///
/// ## Examples
///
/// For your convenience, there are success and error constructors.
///
/// ```
/// use cosmwasm_std::StdAck;
///
/// let ack1 = StdAck::success(b"\x01"); // 0x01 is a FungibleTokenPacketSuccess from ICS-20.
/// assert!(ack1.is_success());
///
/// let ack2 = StdAck::error("kaputt"); // Some free text error message
/// assert!(ack2.is_error());
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub enum StdAck {
Result(Binary),
Error(String),
}

impl StdAck {
/// Creates a success ack by serializing the data with JSON.
pub fn success(data: impl Into<Binary>) -> Self {
StdAck::Result(data.into())
}

/// Creates an error ack
pub fn error(err: impl Into<String>) -> Self {
StdAck::Error(err.into())
}

#[must_use = "if you intended to assert that this is a success, consider `.unwrap()` instead"]
#[inline]
pub const fn is_success(&self) -> bool {
matches!(*self, StdAck::Result(_))
}

#[must_use = "if you intended to assert that this is an error, consider `.unwrap_err()` instead"]
#[inline]
pub const fn is_error(&self) -> bool {
!self.is_success()
}

/// Creates a success ack by serializing the input with JSON.
///
/// This is probably what you want when creating your own IBC protocols
/// for CosmWasm. However other protocols like ICS-20 don't use JSON inside
/// of the success data.
///
/// Acks that are serialized with this can be deserialized with [`unwrap_json`].
pub fn success_json(input: &impl Serialize) -> StdResult<Self> {
let serialized = to_binary(input)?;
Ok(StdAck::Result(serialized))
}

pub fn unwrap(self) -> Binary {
match self {
StdAck::Result(data) => data,
StdAck::Error(err) => panic!("{}", err),
}
}

pub fn unwrap_err(self) -> String {
match self {
StdAck::Result(_) => panic!("not an error"),
StdAck::Error(err) => err,
}
}

pub fn unwrap_json<T: DeserializeOwned>(&self) -> T {
match self {
StdAck::Result(data) => from_slice(data).unwrap(),
StdAck::Error(err) => panic!("{}", err),
}
}
}

impl From<StdAck> for Binary {
fn from(original: StdAck) -> Binary {
// pretty sure this cannot fail
to_binary(&original).unwrap()
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn stdack_success_works() {
let success = StdAck::success(b"foo");
match success {
StdAck::Result(data) => assert_eq!(data, b"foo"),
StdAck::Error(_err) => panic!("must not be an error"),
}
}

#[test]
fn stdack_error_works() {
let err = StdAck::error("bar");
match err {
StdAck::Result(_data) => panic!("must not be a success"),
StdAck::Error(err) => assert_eq!(err, "bar"),
}
}

#[test]
fn stdack_is_success_is_error_work() {
let success = StdAck::success(b"foo");
let err = StdAck::error("bar");
// is_success
assert!(success.is_success());
assert!(!err.is_success());
// is_eror
assert!(!success.is_error());
assert!(err.is_error());
}
}

0 comments on commit f0b95cf

Please sign in to comment.