api3_common/abi/
types.rs

1#![allow(clippy::assign_op_pattern)]
2#![allow(clippy::ptr_offset_with_cast)]
3
4use crate::{Bytes, Bytes32};
5use borsh::{BorshDeserialize, BorshSerialize};
6use std::io;
7use uint::construct_uint;
8
9pub type Address = [u8; 20];
10pub type FixedBytes = Vec<u8>;
11pub type Uint = U256;
12pub type Word = [u8; 32];
13pub type Int = Uint;
14
15construct_uint! {
16    pub struct U256(4);
17}
18
19impl BorshDeserialize for U256 {
20    fn deserialize(bytes: &mut &[u8]) -> Result<Self, io::Error> {
21        let values: [u8; 32] = BorshDeserialize::deserialize(bytes)?;
22        Ok(U256::from_big_endian(&values))
23    }
24}
25
26impl BorshSerialize for U256 {
27    fn serialize<W>(&self, writer: &mut W) -> Result<(), io::Error>
28    where
29        W: io::Write,
30    {
31        let mut v = [0u8; 32];
32        self.to_big_endian(&mut v);
33        BorshSerialize::serialize(&v, writer)
34    }
35}
36
37impl From<&U256> for Bytes32 {
38    fn from(u: &U256) -> Self {
39        let mut v = Bytes32::default();
40        u.to_big_endian(&mut v);
41        v
42    }
43}
44
45#[derive(Debug, PartialEq, Clone)]
46pub enum Token {
47    /// Address.
48    ///
49    /// solidity name: address
50    /// Encoded to left padded [0u8; 32].
51    Address(Address),
52    /// Vector of bytes with known size.
53    ///
54    /// solidity name eg.: bytes8, bytes32, bytes64, bytes1024
55    /// Encoded to right padded [0u8; ((N + 31) / 32) * 32].
56    FixedBytes(FixedBytes),
57    /// Vector of bytes of unknown size.
58    ///
59    /// solidity name: bytes
60    /// Encoded in two parts.
61    /// Init part: offset of 'closing part`.
62    /// Closing part: encoded length followed by encoded right padded bytes.
63    Bytes(Bytes),
64    /// Unsigned integer.
65    ///
66    /// solidity name: uint
67    Uint(Uint),
68    /// Signed integer.
69    ///
70    /// solidity name: int
71    Int(Int),
72    /// String.
73    ///
74    /// solidity name: string
75    /// Encoded in the same way as bytes. Must be utf8 compliant.
76    String(String),
77}
78
79/// Function and event param types.
80#[derive(PartialEq)]
81pub enum ParamType {
82    /// Address
83    Address,
84    /// Bytes
85    Bytes,
86    /// Unsigned integer
87    Uint(usize),
88    /// Signed integer
89    Int(usize),
90    /// String
91    String,
92    /// Vector of bytes with fixed size
93    FixedBytes(usize),
94}
95
96impl ParamType {
97    /// returns whether a zero length byte slice (`0x`) is
98    /// a valid encoded form of this param type
99    pub fn is_empty_bytes_valid_encoding(&self) -> bool {
100        match self {
101            ParamType::FixedBytes(len) => *len == 0,
102            _ => false,
103        }
104    }
105}