Fix to round-trip serialize and deserialize optional address (#2057)

* Test serde round-trip address

* Fix serde round-trip address

* fix fmt lint

Co-authored-by: Ames <git@sys.cornishes.net>
This commit is contained in:
Ames 2023-01-22 13:08:43 -08:00 committed by GitHub
parent 50ef8a78f9
commit 0116130b87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 7 deletions

View File

@ -25,12 +25,12 @@ pub async fn lookup_compiler_version(version: &Version) -> Result<Version> {
pub fn deserialize_address_opt<'de, D: Deserializer<'de>>( pub fn deserialize_address_opt<'de, D: Deserializer<'de>>(
deserializer: D, deserializer: D,
) -> std::result::Result<Option<Address>, D::Error> { ) -> std::result::Result<Option<Address>, D::Error> {
let s = String::deserialize(deserializer)?; match Option::<String>::deserialize(deserializer)? {
if s.is_empty() { None => Ok(None),
Ok(None) Some(s) => match s.is_empty() {
} else { true => Ok(None),
let addr: Address = s.parse().map_err(serde::de::Error::custom)?; _ => Ok(Some(s.parse().map_err(serde::de::Error::custom)?)),
Ok(Some(addr)) },
} }
} }
@ -104,7 +104,7 @@ mod tests {
#[test] #[test]
fn can_deserialize_address_opt() { fn can_deserialize_address_opt() {
#[derive(Deserialize)] #[derive(serde::Serialize, Deserialize)]
struct Test { struct Test {
#[serde(deserialize_with = "deserialize_address_opt")] #[serde(deserialize_with = "deserialize_address_opt")]
address: Option<Address>, address: Option<Address>,
@ -115,6 +115,11 @@ mod tests {
let de: Test = serde_json::from_str(json).unwrap(); let de: Test = serde_json::from_str(json).unwrap();
assert_eq!(de.address, None); assert_eq!(de.address, None);
// Round-trip the above
let json = serde_json::to_string(&de).unwrap();
let de: Test = serde_json::from_str(&json).unwrap();
assert_eq!(de.address, None);
// https://api.etherscan.io/api?module=contract&action=getsourcecode&address=0xDef1C0ded9bec7F1a1670819833240f027b25EfF // https://api.etherscan.io/api?module=contract&action=getsourcecode&address=0xDef1C0ded9bec7F1a1670819833240f027b25EfF
let json = r#"{"address":"0x4af649ffde640ceb34b1afaba3e0bb8e9698cb01"}"#; let json = r#"{"address":"0x4af649ffde640ceb34b1afaba3e0bb8e9698cb01"}"#;
let de: Test = serde_json::from_str(json).unwrap(); let de: Test = serde_json::from_str(json).unwrap();