pub trait DecodeDispatch: Decode {
    // Required method
    fn decode_dispatch<I: Input>(input: &mut I) -> Result<Self, DispatchError>;
}
Expand description

Decodes an ink! dispatch input into a known selector and its expected parameters.

§Note

This trait is automatically implemented for ink! message and constructor decoders.

§Errors

Returns an error if any of the decode steps failed:

  • InvalidSelector: The first four bytes could not properly decoded into the selector.
  • UnknownSelector: The decoded selector did not match any of the expected ones.
  • InvalidParameters: Failed to decoded the parameters for the selected dispatchable.

The other dispatch errors are handled by other structures usually.

§Usage


#[ink::contract]
pub mod contract {
    #[ink(storage)]
    pub struct Contract {}

    impl Contract {
        #[ink(constructor)]
        pub fn constructor() -> Self { Self {} }

        #[ink(message)]
        pub fn message(&self, input_1: bool, input_2: i32) {}
    }
}

use contract::Contract;

fn main() {
    // Valid call to `message`:
    {
        let mut input_bytes = Vec::new();
        input_bytes.extend(selector_bytes!("message"));
        input_bytes.extend(true.encode());
        input_bytes.extend(42i32.encode());
        assert!(
            <<Contract as ContractMessageDecoder>::Type as DecodeDispatch>::decode_dispatch(
                &mut &input_bytes[..]).is_ok()
        );
    }
    // Invalid call with invalid selector (or empty input).
    {
        let mut input_bytes = Vec::new();
        assert_eq!(
            <<Contract as ContractMessageDecoder>::Type
                as DecodeDispatch>::decode_dispatch(&mut &input_bytes[..])
                .unwrap_err(),
            DispatchError::InvalidSelector,
        );
    }
    // Invalid call to `message` with unknown selector.
    {
        let mut input_bytes = Vec::new();
        input_bytes.extend(selector_bytes!("unknown_selector"));
        assert_eq!(
            <<Contract as ContractMessageDecoder>::Type
                as DecodeDispatch>::decode_dispatch(&mut &input_bytes[..])
                .unwrap_err(),
            DispatchError::UnknownSelector,
        );
    }
    // Invalid call to `message` with invalid (or missing) parameters.
    {
        let mut input_bytes = Vec::new();
        input_bytes.extend(selector_bytes!("message"));
        assert_eq!(
            <<Contract as ContractMessageDecoder>::Type
                as DecodeDispatch>::decode_dispatch(&mut &input_bytes[..])
                .unwrap_err(),
            DispatchError::InvalidParameters,
        );
    }
}

Required Methods§

Object Safety§

This trait is not object safe.

Implementors§