feat(codec): add hex encode and decode functions (#1059)
This commit is contained in:
parent
c9ef5769e2
commit
dd4893a752
|
@ -9,12 +9,28 @@ use crate::{
|
||||||
pub trait AbiEncode {
|
pub trait AbiEncode {
|
||||||
/// ABI encode the type
|
/// ABI encode the type
|
||||||
fn encode(self) -> Vec<u8>;
|
fn encode(self) -> Vec<u8>;
|
||||||
|
|
||||||
|
/// Returns the encoded value as hex string, _with_ a `0x` prefix
|
||||||
|
fn encode_hex(self) -> String
|
||||||
|
where
|
||||||
|
Self: Sized,
|
||||||
|
{
|
||||||
|
format!("0x{}", hex::encode(self.encode()))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Trait for ABI decoding
|
/// Trait for ABI decoding
|
||||||
pub trait AbiDecode: Sized {
|
pub trait AbiDecode: Sized {
|
||||||
/// Decodes the ABI encoded data
|
/// Decodes the ABI encoded data
|
||||||
fn decode(bytes: impl AsRef<[u8]>) -> Result<Self, AbiError>;
|
fn decode(bytes: impl AsRef<[u8]>) -> Result<Self, AbiError>;
|
||||||
|
|
||||||
|
/// Decode hex encoded ABI encoded data
|
||||||
|
///
|
||||||
|
/// Expects a hex encoded string, with optional `0x` prefix
|
||||||
|
fn decode_hex(data: impl AsRef<str>) -> Result<Self, AbiError> {
|
||||||
|
let bytes: Bytes = data.as_ref().parse()?;
|
||||||
|
Self::decode(bytes)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! impl_abi_codec {
|
macro_rules! impl_abi_codec {
|
||||||
|
|
|
@ -24,6 +24,7 @@ pub(crate) use _format_err as format_err;
|
||||||
macro_rules! _bail {
|
macro_rules! _bail {
|
||||||
($($tt:tt)*) => { return Err($crate::abi::error::format_err!($($tt)*)) };
|
($($tt:tt)*) => { return Err($crate::abi::error::format_err!($($tt)*)) };
|
||||||
}
|
}
|
||||||
|
use crate::types::ParseBytesError;
|
||||||
pub(crate) use _bail as bail;
|
pub(crate) use _bail as bail;
|
||||||
|
|
||||||
/// ABI codec related errors
|
/// ABI codec related errors
|
||||||
|
@ -39,4 +40,7 @@ pub enum AbiError {
|
||||||
|
|
||||||
#[error("missing or wrong function selector")]
|
#[error("missing or wrong function selector")]
|
||||||
WrongSelector,
|
WrongSelector,
|
||||||
|
|
||||||
|
#[error(transparent)]
|
||||||
|
ParseBytesError(#[from] ParseBytesError),
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,7 +25,7 @@ mod i256;
|
||||||
pub use i256::{Sign, I256};
|
pub use i256::{Sign, I256};
|
||||||
|
|
||||||
mod bytes;
|
mod bytes;
|
||||||
pub use self::bytes::Bytes;
|
pub use self::bytes::{Bytes, ParseBytesError};
|
||||||
|
|
||||||
mod block;
|
mod block;
|
||||||
pub use block::{Block, BlockId, BlockNumber};
|
pub use block::{Block, BlockId, BlockNumber};
|
||||||
|
|
Loading…
Reference in New Issue