Skip to main content

snarkvm_ledger_block/transaction/fee/
serialize.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> Serialize for Fee<N> {
19    /// Serializes the fee into string or bytes.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => {
23                let mut fee = serializer.serialize_struct("Fee", 2 + self.proof.is_some() as usize)?;
24                fee.serialize_field("transition", &self.transition)?;
25                fee.serialize_field("global_state_root", &self.global_state_root)?;
26                if let Some(proof) = &self.proof {
27                    fee.serialize_field("proof", proof)?;
28                }
29                fee.end()
30            }
31            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
32        }
33    }
34}
35
36impl<'de, N: Network> Deserialize<'de> for Fee<N> {
37    /// Deserializes the fee from a string or bytes.
38    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
39        match deserializer.is_human_readable() {
40            true => {
41                // Parse the fee from a string into a value.
42                let mut fee = serde_json::Value::deserialize(deserializer)?;
43                // Retrieve the transitions.
44                let transition = DeserializeExt::take_from_value::<D>(&mut fee, "transition")?;
45                // Retrieve the global state root.
46                let global_state_root = DeserializeExt::take_from_value::<D>(&mut fee, "global_state_root")?;
47                // Retrieve the proof.
48                let proof = serde_json::from_value(fee.get_mut("proof").unwrap_or(&mut serde_json::Value::Null).take())
49                    .map_err(de::Error::custom)?;
50                // Recover the fee.
51                Self::from(transition, global_state_root, proof).map_err(de::Error::custom)
52            }
53            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "fee"),
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn test_serde_json() -> Result<()> {
64        let rng = &mut TestRng::default();
65
66        // Sample the private fee.
67        let expected = crate::transaction::fee::test_helpers::sample_fee_private_hardcoded(rng);
68
69        // Serialize
70        let expected_string = &expected.to_string();
71        let candidate_string = serde_json::to_string(&expected)?;
72        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
73
74        // Deserialize
75        assert_eq!(expected, Fee::from_str(expected_string)?);
76        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
77
78        // Sample the public fee.
79        let expected = crate::transaction::fee::test_helpers::sample_fee_public_hardcoded(rng);
80
81        // Serialize
82        let expected_string = &expected.to_string();
83        let candidate_string = serde_json::to_string(&expected)?;
84        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
85
86        // Deserialize
87        assert_eq!(expected, Fee::from_str(expected_string)?);
88        assert_eq!(expected, serde_json::from_str(&candidate_string)?);
89
90        Ok(())
91    }
92
93    #[test]
94    fn test_bincode() -> Result<()> {
95        let rng = &mut TestRng::default();
96
97        // Sample the private fee.
98        let expected = crate::transaction::fee::test_helpers::sample_fee_private_hardcoded(rng);
99
100        // Serialize
101        let expected_bytes = expected.to_bytes_le()?;
102        let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
103        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
104
105        // Deserialize
106        assert_eq!(expected, Fee::read_le(&expected_bytes[..])?);
107        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
108
109        // Sample the public fee.
110        let expected = crate::transaction::fee::test_helpers::sample_fee_public_hardcoded(rng);
111
112        // Serialize
113        let expected_bytes = expected.to_bytes_le()?;
114        let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
115        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
116
117        // Deserialize
118        assert_eq!(expected, Fee::read_le(&expected_bytes[..])?);
119        assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
120
121        Ok(())
122    }
123}