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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Types to represent timestamps and durations.
use crate::error::{ErrorDomain, ErrorId, PerpError};
use crate::prelude::*;
use anyhow::Result;
#[cfg(feature = "chrono")]
use chrono::{DateTime, TimeZone, Utc};
use cosmwasm_std::{Decimal256, Timestamp as CWTimestamp};
use cw_storage_plus::{KeyDeserialize, Prefixer, PrimaryKey};
use schemars::JsonSchema;
use serde::de::Visitor;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::ops::{Add, Div, Mul, Sub};

/// Essentially a newtype wrapper for [Timestamp] providing additional impls.
///
/// Internal representation in nanoseconds since the epoch. We keep a [u64]
/// directly (instead of a [Timestamp] or [cosmwasm_std::Uint64]) to make it
/// easier to derive some impls. The result is that we need to explicitly
/// implement [Serialize] and [Deserialize] to keep the stringy representation.
#[derive(Debug, Clone, Default, Copy, Eq, PartialEq, Ord, PartialOrd, JsonSchema, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Timestamp(#[schemars(with = "String")] u64);

impl Display for Timestamp {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let whole = self.0 / 1_000_000_000;
        let fractional = self.0 % 1_000_000_000;
        write!(f, "{}.{:09}", whole, fractional)
    }
}

impl Serialize for Timestamp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for Timestamp {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(NanoVisitor)
    }
}

struct NanoVisitor;

impl<'de> Visitor<'de> for NanoVisitor {
    type Value = Timestamp;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("nanoseconds since epoch, string-encoded")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        match v.parse::<u64>() {
            Ok(v) => Ok(Timestamp(v)),
            Err(e) => Err(E::custom(format!("invalid Nano '{v}' - {e}"))),
        }
    }
}

impl Timestamp {
    /// Construct a new value from the given number of nanoseconds since the
    /// epoch
    pub fn from_nanos(nanos: u64) -> Self {
        Timestamp(nanos)
    }

    /// Construct a new value from the given number of seconds since the
    /// epoch
    pub fn from_seconds(seconds: u64) -> Self {
        Timestamp(seconds * 1_000_000_000)
    }

    /// Construct a new value from the given number of millisecond since the epoch.
    pub fn from_millis(millis: u64) -> Self {
        Timestamp(millis * 1_000_000)
    }

    /// Add the given number of seconds to the given timestamp
    pub fn plus_seconds(self, secs: u64) -> Self {
        self + Duration::from_seconds(secs)
    }

    /// Subtract two timestamps to get the duration between them.
    ///
    /// Will fail if the right hand side is greater than the left hand side.
    pub fn checked_sub(self, rhs: Self, desc: &str) -> Result<Duration> {
        #[derive(serde::Serialize)]
        struct Data {
            lhs: Timestamp,
            rhs: Timestamp,
            desc: String,
        }
        let data = Data {
            lhs: self,
            rhs,
            desc: desc.to_owned(),
        };
        match self.0.checked_sub(rhs.0) {
            Some(x) => Ok(Duration(x)),
            None => Err(anyhow!(PerpError {
                id: ErrorId::TimestampSubtractUnderflow,
                domain: ErrorDomain::Default,
                description: format!(
                    "Invalid timestamp subtraction during. Action: {desc}. Values: {} - {}",
                    data.lhs, data.rhs
                ),
                data: Some(data),
            })),
        }
    }

    #[cfg(feature = "chrono")]
    /// Convert into a chrono [`DateTime<Utc>`]
    pub fn try_into_chrono_datetime(self) -> Result<DateTime<Utc>> {
        let secs = self.0 / 1_000_000_000;
        let nanos = self.0 % 1_000_000_000;

        Utc.timestamp_opt(secs.try_into()?, nanos.try_into()?)
            .single()
            .with_context(|| format!("Could not convert {self} into DateTime<Utc>"))
    }
}

// Lossless conversions. In the future, we may want to focus on using this type
// throughout the codebase instead of Timestamp, in which case removing these
// impls and instead having explicit helper functions may help identify stray
// conversions still occurring.
impl From<Timestamp> for CWTimestamp {
    fn from(Timestamp(nanos): Timestamp) -> Self {
        CWTimestamp::from_nanos(nanos)
    }
}

impl From<CWTimestamp> for Timestamp {
    fn from(timestamp: CWTimestamp) -> Self {
        Timestamp(timestamp.nanos())
    }
}

impl<'a> PrimaryKey<'a> for Timestamp {
    type Prefix = ();
    type SubPrefix = ();
    type Suffix = Timestamp;
    type SuperSuffix = Timestamp;

    fn key(&self) -> Vec<cw_storage_plus::Key> {
        self.0.key()
    }
}

impl KeyDeserialize for Timestamp {
    type Output = Timestamp;

    const KEY_ELEMS: u16 = 1;

    fn from_vec(value: Vec<u8>) -> cosmwasm_std::StdResult<Self::Output> {
        u64::from_vec(value).map(Timestamp)
    }
}

impl<'a> Prefixer<'a> for Timestamp {
    fn prefix(&self) -> Vec<cw_storage_plus::Key> {
        self.0.prefix()
    }
}

/// A duration of time measured in nanoseconds
#[derive(
    Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, JsonSchema,
)]
pub struct Duration(u64);

impl Duration {
    /// Construct a [Duration] from a given number of nanoseconds.
    pub(crate) fn from_nanos(nanos: u64) -> Self {
        Duration(nanos)
    }

    /// Returns the underlying nanos value as a u64
    pub fn as_nanos(&self) -> u64 {
        self.0
    }

    /// Convert to milliseconds and represent as a [Number].
    ///
    /// This is intended for performing calculations. Remember that this is a lossy conversion!
    pub fn as_ms_number_lossy(&self) -> Number {
        Number::from(self.0 / 1_000_000)
    }

    /// Convert to milliseconds and represent as a [Decimal256].
    ///
    /// This is intended for performing calculations. Remember that this is a lossy conversion!
    pub fn as_ms_decimal_lossy(&self) -> Decimal256 {
        Decimal256::from_atomics(self.0, 6)
            .expect("as_ms_decimal_lossy failed, but range won't allow that to happen")
    }

    /// Convert a number of seconds into a [Duration].
    pub const fn from_seconds(seconds: u64) -> Self {
        Duration(seconds * 1_000_000_000)
    }
}

// Arithmetic operators. Consider removing these impls in favor of checked
// versions in the future to avoid panicking. Leaving for now to ease
// conversion.

impl Add<Duration> for Timestamp {
    type Output = Timestamp;

    fn add(self, rhs: Duration) -> Self::Output {
        Timestamp(self.0 + rhs.0)
    }
}

impl Sub<Duration> for Duration {
    type Output = Duration;

    fn sub(self, rhs: Duration) -> Self::Output {
        Duration(self.0 - rhs.0)
    }
}

impl Add<Duration> for Duration {
    type Output = Duration;

    fn add(self, rhs: Duration) -> Self::Output {
        Duration(self.0 + rhs.0)
    }
}

impl Mul<u64> for Duration {
    type Output = Duration;

    fn mul(self, rhs: u64) -> Self::Output {
        Duration(self.0 * rhs)
    }
}

impl Div<u64> for Duration {
    type Output = Duration;

    fn div(self, rhs: u64) -> Self::Output {
        Duration(self.0 / rhs)
    }
}

// Used for questions like "how many epochs do I need to fill up the given duration?"
impl Div<Duration> for Duration {
    type Output = u64;

    fn div(self, rhs: Self) -> Self::Output {
        self.0 / rhs.0
    }
}

impl FromStr for Timestamp {
    type Err = PerpError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let err = |msg: &str| -> PerpError {
            PerpError::new(
                ErrorId::Conversion,
                ErrorDomain::Default,
                format!("error converting {} to Timestamp, {}", s, msg),
            )
        };

        let (seconds, nanos) = s
            .split_once('.')
            .ok_or_else(|| err("missing decimal point"))?;
        let seconds = seconds.parse().map_err(|_| err("unable to parse second"))?;
        let nanos = nanos.parse().map_err(|_| err("unable to parse nanos"))?;

        let timestamp = Timestamp::from_seconds(seconds) + Duration::from_nanos(nanos);

        Ok(timestamp)
    }
}