Skip to main content

superposition_assets/
lib.rs

1#![cfg_attr(not(any(feature = "proptest", feature = "arbitrary")), no_std)]
2
3#[repr(u8)]
4#[derive(Clone, PartialEq, Eq, Debug)]
5#[cfg_attr(
6    feature = "borsh",
7    derive(borsh::BorshDeserialize, borsh::BorshSerialize),
8    borsh(use_discriminant = true)
9)]
10#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
11#[cfg_attr(feature = "proptest", derive(proptest_derive::Arbitrary))]
12#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
13pub enum Asset {
14    USDC = 0,
15    ARB = 1,
16    WETH = 2,
17}
18
19const fn decode(x: &[u8]) -> [u8; 20] {
20    match const_hex::const_decode_to_array::<20>(x) {
21        Ok(r) => r,
22        Err(_) => panic!(),
23    }
24}
25
26impl Asset {
27    fn addr(&self) -> [u8; 20] {
28        match self {
29            Asset::USDC => decode(b"af88d065e77c8cC2239327C5EDb3A432268e5831"),
30            Asset::ARB => decode(b"912ce59144191c1204e64559fe8253a0e49e6548"),
31            Asset::WETH => decode(b"82af49447d8a07e3bd95bd0d56f35241523fbab1"),
32        }
33    }
34}
35
36impl From<Asset> for [u8; 20] {
37    fn from(x: Asset) -> Self {
38        x.addr()
39    }
40}
41
42impl From<&Asset> for [u8; 20] {
43    fn from(x: &Asset) -> Self {
44        x.addr()
45    }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct InvalidAsset;
50
51impl TryFrom<u8> for Asset {
52    type Error = InvalidAsset;
53
54    fn try_from(x: u8) -> Result<Self, Self::Error> {
55        match x {
56            0 => Ok(Asset::USDC),
57            1 => Ok(Asset::ARB),
58            2 => Ok(Asset::WETH),
59            _ => Err(InvalidAsset),
60        }
61    }
62}
63
64macro_rules! impl_asset_int {
65    ($($ty:ty),* $(,)?) => {
66        $(
67            impl TryFrom<$ty> for Asset {
68                type Error = InvalidAsset;
69
70                fn try_from(x: $ty) -> Result<Self, Self::Error> {
71                    let x = u8::try_from(x).map_err(|_| InvalidAsset)?;
72                    Asset::try_from(x)
73                }
74            }
75
76            impl From<Asset> for $ty {
77                fn from(x: Asset) -> Self {
78                    x as u8 as $ty
79                }
80            }
81        )*
82    };
83}
84
85impl_asset_int!(u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);