Skip to main content

Crate serde_helpers

Crate serde_helpers 

Expand description

§alloy-serde

Serde helpers for Ethereum JSON-RPC formats that differ from Serde’s defaults.

  • quantity encodes primitive integers as canonical RPC quantities such as "0x2a". Its opt, vec, hashmap, and btreemap modules cover common containers.
  • ttd handles geth’s mixed number/string representation of terminal total difficulty.
  • storage handles storage keys and zero-padding cropped storage values.
  • WithOtherFields preserves unknown object fields for forwarding or round-tripping RPC payloads.
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Request {
    #[serde(with = "alloy_serde::quantity")]
    block: u64,
    // `default` is required if an omitted field should become `None`.
    #[serde(default, with = "alloy_serde::quantity::opt")]
    limit: Option<u64>,
}

let request: Request = serde_json::from_str(r#"{"block":"0x2a"}"#)?;
assert_eq!(request, Request { block: 42, limit: None });
assert_eq!(
    serde_json::to_string(&Request { block: 42, limit: Some(16) })?,
    r#"{"block":"0x2a","limit":"0x10"}"#,
);

For deserialization-only helpers such as null_as_default, use deserialize_with and pair it with #[serde(default)] when missing fields should also use the default. The no-prefix hex helpers are serialization-only and therefore use serialize_with.

Modules§

checksum
Serde functions for (de)serializing EIP-55 checksummed addresses.
displayfromstr
Serde functions for (de)serializing using FromStr and Display
quantity
Serde functions for encoding primitive numbers using the Ethereum JSON-RPC “quantity” format.
storage
Storage related helpers.
ttd
Serde functions for encoding terminal total difficulty (TTD) using a geth-compatible format.

Structs§

OtherFields
Generic type for capturing additional fields when deserializing structs.
WithOtherFields
An extension to a struct that allows to capture additional fields when deserializing.

Enums§

JsonStorageKey
A storage key that accepts hex strings up to 32 bytes for eth_getStorageAt and eth_getProof.

Functions§

deserialize
Deserializes an optional TTD using the formats described in the module documentation.
deserialize_json_ttd_opt
Compatibility alias for deserialize.
null_as_default
Deserializes an explicit null as Default::default and any other value as T.
reject_if_some
Deserializes an explicit null as None and rejects a non-null value.
serialize
Serializes an optional TTD using the format described in the module documentation.
serialize_b256_hex_string_no_prefix
Serialize a B256 as a hex string without the “0x” prefix.
serialize_hex_string_no_prefix
Serialize bytes as a hex string without the “0x” prefix.