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>>(
deserializer: D,
) -> std::result::Result<Option<Address>, D::Error> {
let s = String::deserialize(deserializer)?;
if s.is_empty() {
Ok(None)
} else {
let addr: Address = s.parse().map_err(serde::de::Error::custom)?;
Ok(Some(addr))
match Option::<String>::deserialize(deserializer)? {
None => Ok(None),
Some(s) => match s.is_empty() {
true => Ok(None),
_ => Ok(Some(s.parse().map_err(serde::de::Error::custom)?)),
},
}
}
@ -104,7 +104,7 @@ mod tests {
#[test]
fn can_deserialize_address_opt() {
#[derive(Deserialize)]
#[derive(serde::Serialize, Deserialize)]
struct Test {
#[serde(deserialize_with = "deserialize_address_opt")]
address: Option<Address>,
@ -115,6 +115,11 @@ mod tests {
let de: Test = serde_json::from_str(json).unwrap();
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
let json = r#"{"address":"0x4af649ffde640ceb34b1afaba3e0bb8e9698cb01"}"#;
let de: Test = serde_json::from_str(json).unwrap();