mazzaroth_rs/contract/
mod.rs

1use std::fmt;
2use xdr_rs_serialize::error::Error;
3
4/// This trait defines the execute function that can be called on a contract.
5/// The implementation is generated by the derive macro but this trait must
6/// be included by the contract implementation.
7pub trait ContractInterface {
8    fn execute(&mut self, payload: &[u8]) -> Result<Vec<u8>, ContractError>;
9}
10
11#[derive(Debug)]
12pub enum ContractErrorKinds {
13    DeserializeError(Error),
14    InvalidArguments,
15    InvalidFunctionName,
16}
17
18#[derive(Debug)]
19pub struct ContractError {
20    kind: ContractErrorKinds,
21}
22
23impl ContractError {
24    fn from_kind(kind: ContractErrorKinds) -> Self {
25        ContractError { kind }
26    }
27
28    fn kind(&self) -> &ContractErrorKinds {
29        &self.kind
30    }
31
32    pub fn invalid_arguments() -> Self {
33        ContractError {
34            kind: ContractErrorKinds::InvalidArguments,
35        }
36    }
37
38    pub fn invalid_function() -> Self {
39        ContractError {
40            kind: ContractErrorKinds::InvalidFunctionName,
41        }
42    }
43}
44
45impl std::fmt::Display for ContractError {
46    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47        match self.kind() {
48            ContractErrorKinds::DeserializeError(err) => {
49                write!(f, "Error deserializing arguments: {}", err)
50            }
51            ContractErrorKinds::InvalidArguments => {
52                write!(f, "Failed to parse arguments for function.")
53            }
54            ContractErrorKinds::InvalidFunctionName => {
55                write!(f, "Could not find function with given name.")
56            }
57        }
58    }
59}
60
61impl From<Error> for ContractError {
62    fn from(deserialize_err: Error) -> Self {
63        ContractError::from_kind(ContractErrorKinds::DeserializeError(deserialize_err))
64    }
65}