|
| 1 | +use std::{fmt::Debug, ops::Deref, str::FromStr}; |
| 2 | + |
| 3 | +use anyhow::{anyhow, bail, Context, Result}; |
| 4 | +use contract_transcode::Value; |
| 5 | + |
| 6 | +use crate::AccountId; |
| 7 | + |
| 8 | +/// Temporary wrapper for converting from [Value] to primitive types. |
| 9 | +/// |
| 10 | +/// ``` |
| 11 | +/// # #![feature(assert_matches)] |
| 12 | +/// # #![feature(type_ascription)] |
| 13 | +/// # use std::assert_matches::assert_matches; |
| 14 | +/// # use anyhow::{anyhow, Result}; |
| 15 | +/// # use aleph_client::{AccountId, contract::ConvertibleValue}; |
| 16 | +/// use contract_transcode::Value; |
| 17 | +/// |
| 18 | +/// assert_matches!(ConvertibleValue(Value::UInt(42)).try_into(), Ok(42u128)); |
| 19 | +/// assert_matches!(ConvertibleValue(Value::UInt(42)).try_into(), Ok(42u32)); |
| 20 | +/// assert_matches!(ConvertibleValue(Value::UInt(u128::MAX)).try_into(): Result<u32>, Err(_)); |
| 21 | +/// assert_matches!(ConvertibleValue(Value::Bool(true)).try_into(), Ok(true)); |
| 22 | +/// assert_matches!( |
| 23 | +/// ConvertibleValue(Value::Literal("5H8cjBBzCJrAvDn9LHZpzzJi2UKvEGC9VeVYzWX5TrwRyVCA".to_string())). |
| 24 | +/// try_into(): Result<AccountId>, |
| 25 | +/// Ok(_) |
| 26 | +/// ); |
| 27 | +/// assert_matches!( |
| 28 | +/// ConvertibleValue(Value::String("not a number".to_string())).try_into(): Result<u128>, |
| 29 | +/// Err(_) |
| 30 | +/// ); |
| 31 | +/// ``` |
| 32 | +#[derive(Debug, Clone)] |
| 33 | +pub struct ConvertibleValue(pub Value); |
| 34 | + |
| 35 | +impl Deref for ConvertibleValue { |
| 36 | + type Target = Value; |
| 37 | + |
| 38 | + fn deref(&self) -> &Value { |
| 39 | + &self.0 |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl TryFrom<ConvertibleValue> for bool { |
| 44 | + type Error = anyhow::Error; |
| 45 | + |
| 46 | + fn try_from(value: ConvertibleValue) -> Result<bool, Self::Error> { |
| 47 | + match value.0 { |
| 48 | + Value::Bool(value) => Ok(value), |
| 49 | + _ => bail!("Expected {:?} to be a boolean", value.0), |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl TryFrom<ConvertibleValue> for u128 { |
| 55 | + type Error = anyhow::Error; |
| 56 | + |
| 57 | + fn try_from(value: ConvertibleValue) -> Result<u128, Self::Error> { |
| 58 | + match value.0 { |
| 59 | + Value::UInt(value) => Ok(value), |
| 60 | + _ => bail!("Expected {:?} to be an integer", value.0), |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl TryFrom<ConvertibleValue> for u32 { |
| 66 | + type Error = anyhow::Error; |
| 67 | + |
| 68 | + fn try_from(value: ConvertibleValue) -> Result<u32, Self::Error> { |
| 69 | + match value.0 { |
| 70 | + Value::UInt(value) => Ok(value.try_into()?), |
| 71 | + _ => bail!("Expected {:?} to be an integer", value.0), |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +impl TryFrom<ConvertibleValue> for AccountId { |
| 77 | + type Error = anyhow::Error; |
| 78 | + |
| 79 | + fn try_from(value: ConvertibleValue) -> Result<AccountId, Self::Error> { |
| 80 | + match value.0 { |
| 81 | + Value::Literal(value) => { |
| 82 | + AccountId::from_str(&value).map_err(|_| anyhow!("Invalid account id")) |
| 83 | + } |
| 84 | + _ => bail!("Expected {:?} to be a string", value), |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl<T> TryFrom<ConvertibleValue> for Result<T> |
| 90 | +where |
| 91 | + ConvertibleValue: TryInto<T, Error = anyhow::Error>, |
| 92 | +{ |
| 93 | + type Error = anyhow::Error; |
| 94 | + |
| 95 | + fn try_from(value: ConvertibleValue) -> Result<Result<T>, Self::Error> { |
| 96 | + if let Value::Tuple(tuple) = &value.0 { |
| 97 | + match tuple.ident() { |
| 98 | + Some(x) if x == "Ok" => { |
| 99 | + if tuple.values().count() == 1 { |
| 100 | + let item = |
| 101 | + ConvertibleValue(tuple.values().next().unwrap().clone()).try_into()?; |
| 102 | + return Ok(Ok(item)); |
| 103 | + } else { |
| 104 | + bail!("Unexpected number of elements in Ok variant: {:?}", &value); |
| 105 | + } |
| 106 | + } |
| 107 | + Some(x) if x == "Err" => { |
| 108 | + if tuple.values().count() == 1 { |
| 109 | + return Ok(Err(anyhow!(value.to_string()))); |
| 110 | + } else { |
| 111 | + bail!("Unexpected number of elements in Err variant: {:?}", &value); |
| 112 | + } |
| 113 | + } |
| 114 | + _ => (), |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + bail!("Expected {:?} to be an Ok(_) or Err(_) tuple.", value); |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +impl TryFrom<ConvertibleValue> for String { |
| 123 | + type Error = anyhow::Error; |
| 124 | + |
| 125 | + fn try_from(value: ConvertibleValue) -> std::result::Result<String, Self::Error> { |
| 126 | + let seq = match value.0 { |
| 127 | + Value::Seq(seq) => seq, |
| 128 | + _ => bail!("Failed parsing `ConvertibleValue` to `String`. Expected `Seq(Value::UInt)` but instead got: {:?}", value), |
| 129 | + }; |
| 130 | + |
| 131 | + let mut bytes: Vec<u8> = Vec::with_capacity(seq.len()); |
| 132 | + for el in seq.elems() { |
| 133 | + if let Value::UInt(byte) = *el { |
| 134 | + if byte > u8::MAX as u128 { |
| 135 | + bail!("Expected number <= u8::MAX but instead got: {:?}", byte) |
| 136 | + } |
| 137 | + bytes.push(byte as u8); |
| 138 | + } else { |
| 139 | + bail!("Failed parsing `ConvertibleValue` to `String`. Expected `Value::UInt` but instead got: {:?}", el); |
| 140 | + } |
| 141 | + } |
| 142 | + String::from_utf8(bytes).context("Failed parsing bytes to UTF-8 String.") |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +auto trait NotEq {} |
| 147 | +// We're basically telling the compiler that there is no instance of NotEq for `(X,X)` tuple. |
| 148 | +// Or put differently - that you can't implement `NotEq` for `(X,X)`. |
| 149 | +impl<X> !NotEq for (X, X) {} |
| 150 | + |
| 151 | +impl<T> TryFrom<ConvertibleValue> for Option<T> |
| 152 | +where |
| 153 | + T: TryFrom<ConvertibleValue, Error = anyhow::Error> + Debug, |
| 154 | + // We will derive this impl only when `T != ConvertibleValue`. |
| 155 | + // Otherwise we will get a conflict with generic impl in the rust `core` crate. |
| 156 | + (ConvertibleValue, T): NotEq, |
| 157 | +{ |
| 158 | + type Error = anyhow::Error; |
| 159 | + |
| 160 | + fn try_from(value: ConvertibleValue) -> std::result::Result<Option<T>, Self::Error> { |
| 161 | + let tuple = match &value.0 { |
| 162 | + Value::Tuple(tuple) => tuple, |
| 163 | + _ => bail!("Expected {:?} to be a Some(_) or None Tuple.", &value), |
| 164 | + }; |
| 165 | + |
| 166 | + match tuple.ident() { |
| 167 | + Some(x) if x == "Some" => { |
| 168 | + if tuple.values().count() == 1 { |
| 169 | + let item = |
| 170 | + ConvertibleValue(tuple.values().next().unwrap().clone()).try_into()?; |
| 171 | + Ok(Some(item)) |
| 172 | + } else { |
| 173 | + bail!( |
| 174 | + "Unexpected number of elements in Some(_) variant: {:?}. Expected one.", |
| 175 | + &value |
| 176 | + ); |
| 177 | + } |
| 178 | + } |
| 179 | + Some(x) if x == "None" => { |
| 180 | + if tuple.values().count() == 0 { |
| 181 | + Ok(None) |
| 182 | + } else { |
| 183 | + bail!( |
| 184 | + "Unexpected number of elements in None variant: {:?}. Expected zero.", |
| 185 | + &value |
| 186 | + ); |
| 187 | + } |
| 188 | + } |
| 189 | + _ => bail!( |
| 190 | + "Expected `.ident()` to be `Some` or `None`, got: {:?}", |
| 191 | + &tuple |
| 192 | + ), |
| 193 | + } |
| 194 | + } |
| 195 | +} |
0 commit comments