casper_types/
gas.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! The `gas` module is used for working with Gas including converting to and from Motes.

use alloc::vec::Vec;
use core::fmt;

#[cfg(feature = "datasize")]
use datasize::DataSize;
#[cfg(any(feature = "testing", test))]
use rand::Rng;
#[cfg(feature = "json-schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[cfg(any(feature = "testing", test))]
use crate::testing::TestRng;
use crate::{
    bytesrepr::{self, FromBytes, ToBytes},
    Motes, U512,
};

/// The `Gas` struct represents a `U512` amount of gas.
#[derive(
    Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
#[cfg_attr(feature = "datasize", derive(DataSize))]
#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
pub struct Gas(U512);

impl Gas {
    /// The maximum value of `Gas`.
    pub const MAX: Gas = Gas(U512::MAX);

    /// Constructs a new `Gas`.
    pub fn new<T: Into<U512>>(value: T) -> Self {
        Gas(value.into())
    }

    /// Constructs a new `Gas` with value `0`.
    pub const fn zero() -> Self {
        Gas(U512::zero())
    }

    /// Returns the inner `U512` value.
    pub fn value(&self) -> U512 {
        self.0
    }

    /// Converts the given `motes` to `Gas` by dividing them by `conv_rate`.
    ///
    /// Returns `None` if `motes_per_unit_of_gas == 0`.
    pub fn from_motes(motes: Motes, motes_per_unit_of_gas: u8) -> Option<Self> {
        motes
            .value()
            .checked_div(U512::from(motes_per_unit_of_gas))
            .map(Self::new)
    }

    /// Converts the given `U512` to `Gas` by dividing it by `gas_price`.
    ///
    /// Returns `None` if `gas_price == 0`.
    pub fn from_price(base_amount: U512, gas_price: u8) -> Option<Self> {
        base_amount
            .checked_div(U512::from(gas_price))
            .map(Self::new)
    }

    /// Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred.
    pub fn checked_add(&self, rhs: Self) -> Option<Self> {
        self.0.checked_add(rhs.value()).map(Self::new)
    }

    /// Saturating integer addition. Computes `self + rhs`, returning max if overflow occurred.
    pub fn saturating_add(self, rhs: Self) -> Self {
        Gas(self.0.saturating_add(rhs.value()))
    }

    /// Saturating integer subtraction. Computes `self + rhs`, returning min if overflow occurred.
    pub fn saturating_sub(self, rhs: Self) -> Self {
        Gas(self.0.saturating_sub(rhs.value()))
    }

    /// Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred.
    pub fn checked_sub(&self, rhs: Self) -> Option<Self> {
        self.0.checked_sub(rhs.value()).map(Self::new)
    }

    /// Checked integer subtraction. Computes `self * rhs`, returning `None` if overflow occurred.
    pub fn checked_mul(&self, rhs: Self) -> Option<Self> {
        self.0.checked_mul(rhs.value()).map(Self::new)
    }

    /// Checked integer division. Computes `self / rhs`, returning `None` if overflow occurred.
    pub fn checked_div(&self, rhs: Self) -> Option<Self> {
        self.0.checked_div(rhs.value()).map(Self::new)
    }

    /// Returns a random `Gas`.
    #[cfg(any(feature = "testing", test))]
    pub fn random(rng: &mut TestRng) -> Self {
        Self(rng.gen::<u128>().into())
    }
}

impl ToBytes for Gas {
    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
        self.0.to_bytes()
    }

    fn serialized_length(&self) -> usize {
        self.0.serialized_length()
    }

    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
        self.0.write_bytes(writer)
    }
}

impl FromBytes for Gas {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
        let (value, remainder) = U512::from_bytes(bytes)?;
        Ok((Gas(value), remainder))
    }
}

impl fmt::Display for Gas {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

impl From<u32> for Gas {
    fn from(gas: u32) -> Self {
        let gas_u512: U512 = gas.into();
        Gas::new(gas_u512)
    }
}

impl From<u64> for Gas {
    fn from(gas: u64) -> Self {
        let gas_u512: U512 = gas.into();
        Gas::new(gas_u512)
    }
}

#[cfg(test)]
mod tests {
    use crate::U512;

    use crate::{Gas, Motes};

    #[test]
    fn should_be_able_to_get_instance_of_gas() {
        let initial_value = 1;
        let gas = Gas::new(U512::from(initial_value));
        assert_eq!(
            initial_value,
            gas.value().as_u64(),
            "should have equal value"
        )
    }

    #[test]
    fn should_be_able_to_compare_two_instances_of_gas() {
        let left_gas = Gas::new(U512::from(1));
        let right_gas = Gas::new(U512::from(1));
        assert_eq!(left_gas, right_gas, "should be equal");
        let right_gas = Gas::new(U512::from(2));
        assert_ne!(left_gas, right_gas, "should not be equal")
    }

    #[test]
    fn should_be_able_to_add_two_instances_of_gas() {
        let left_gas = Gas::new(U512::from(1));
        let right_gas = Gas::new(U512::from(1));
        let expected_gas = Gas::new(U512::from(2));
        assert_eq!(
            left_gas.checked_add(right_gas),
            Some(expected_gas),
            "should be equal"
        )
    }

    #[test]
    fn should_be_able_to_subtract_two_instances_of_gas() {
        let left_gas = Gas::new(U512::from(1));
        let right_gas = Gas::new(U512::from(1));
        let expected_gas = Gas::new(U512::from(0));
        assert_eq!(
            left_gas.checked_sub(right_gas),
            Some(expected_gas),
            "should be equal"
        )
    }

    #[test]
    fn should_be_able_to_multiply_two_instances_of_gas() {
        let left_gas = Gas::new(U512::from(100));
        let right_gas = Gas::new(U512::from(10));
        let expected_gas = Gas::new(U512::from(1000));
        assert_eq!(
            left_gas.checked_mul(right_gas),
            Some(expected_gas),
            "should be equal"
        )
    }

    #[test]
    fn should_be_able_to_divide_two_instances_of_gas() {
        let left_gas = Gas::new(U512::from(1000));
        let right_gas = Gas::new(U512::from(100));
        let expected_gas = Gas::new(U512::from(10));
        assert_eq!(
            left_gas.checked_div(right_gas),
            Some(expected_gas),
            "should be equal"
        )
    }

    #[test]
    fn should_be_able_to_convert_from_mote() {
        let mote = Motes::new(U512::from(100));
        let gas = Gas::from_motes(mote, 10).expect("should have gas");
        let expected_gas = Gas::new(U512::from(10));
        assert_eq!(gas, expected_gas, "should be equal")
    }

    #[test]
    fn should_be_able_to_default() {
        let gas = Gas::default();
        let expected_gas = Gas::zero();
        assert_eq!(gas, expected_gas, "should be equal")
    }

    #[test]
    fn should_be_able_to_compare_relative_value() {
        let left_gas = Gas::new(U512::from(100));
        let right_gas = Gas::new(U512::from(10));
        assert!(left_gas > right_gas, "should be gt");
        let right_gas = Gas::new(U512::from(100));
        assert!(left_gas >= right_gas, "should be gte");
        assert!(left_gas <= right_gas, "should be lte");
        let left_gas = Gas::new(U512::from(10));
        assert!(left_gas < right_gas, "should be lt");
    }

    #[test]
    fn should_support_checked_div_from_motes() {
        let motes = Motes::zero();
        let conv_rate = 0;
        let maybe = Gas::from_motes(motes, conv_rate);
        assert!(maybe.is_none(), "should be none due to divide by zero");
    }
}