ethers_abi/
error.rs

1// Copyright 2015-2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Contract error
10
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14#[cfg(not(feature = "std"))]
15use crate::no_std_prelude::*;
16use crate::{
17	decode, encode, errors,
18	signature::{long_signature, short_signature},
19	Bytes, Hash, Param, ParamType, Result, Token,
20};
21
22/// Contract error specification.
23#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
24#[derive(Debug, Clone, PartialEq)]
25pub struct Error {
26	/// Error name.
27	#[cfg_attr(feature = "serde", serde(deserialize_with = "crate::util::sanitize_name::deserialize"))]
28	pub name: String,
29	/// Error input.
30	pub inputs: Vec<Param>,
31}
32
33impl Error {
34	/// Returns types of all params.
35	fn param_types(&self) -> Vec<ParamType> {
36		self.inputs.iter().map(|p| p.kind.clone()).collect()
37	}
38
39	/// Error signature
40	pub fn signature(&self) -> Hash {
41		long_signature(&self.name, &self.param_types())
42	}
43
44	/// Prepares ABI error with given input params.
45	pub fn encode(&self, tokens: &[Token]) -> Result<Bytes> {
46		let params = self.param_types();
47
48		if !Token::types_check(tokens, &params) {
49			return Err(errors::Error::InvalidData);
50		}
51
52		let signed = short_signature(&self.name, &params).to_vec();
53		let encoded = encode(tokens);
54		Ok(signed.into_iter().chain(encoded.into_iter()).collect())
55	}
56
57	/// Parses the ABI function input to a list of tokens.
58	pub fn decode(&self, data: &[u8]) -> Result<Vec<Token>> {
59		decode(&self.param_types(), data)
60	}
61}