alloy-rs / core

High-performance, well-tested & documented core libraries for Ethereum, in Rust
https://alloy.rs
Apache License 2.0
758 stars 131 forks source link

[Bug] Incompatible with `serde_json::from_reader` #667

Closed wtdcode closed 2 months ago

wtdcode commented 2 months ago

Component

json-abi, primitives

What version of Alloy are you on?

0.7.5

Operating System

Linux

Describe the bug

See reproduction below:

use std::io::Write;
use alloy_json_abi::Function;

fn main() {
        let s = r#"{"type":"function","name":"increaseAllowance","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"addedAmount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"}"#;
        let f: Function = serde_json::from_str(s).unwrap(); // works

        let mut fp = std::fs::OpenOptions::new().write(true).create(true).truncate(true).open("/tmp/f.json").unwrap();
        fp.write_all(s.as_bytes()).unwrap();

        let mut fp = std::fs::OpenOptions::new().read(true).open("/tmp/f.json").unwrap();

        let f: Function = serde_json::from_reader(fp).unwrap(); // not working
}

The root cause is alloy trying to firstly deserialize the content into a borrowed type here, which is generally not compatible with serde_json::from_reader.

The possible solution is to use Cow<'a, str> to replace &'a str as mentioned in https://github.com/serde-rs/serde/issues/914 , https://github.com/rust-analyzer/smol_str/issues/14 and https://github.com/serde-rs/serde/issues/914 . However, I ran into lifetime issues, so I leave an issue here first.