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
use crate::ledger::Error;
use crate::treasury::Treasury;
use crate::value::{Value, ValueError};
use std::cmp;
use std::fmt::Debug;

/// Special pots of money
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Pots {
    pub(crate) fees: Value,
    pub(crate) treasury: Treasury,
    pub(crate) rewards: Value,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Entry {
    Fees(Value),
    Treasury(Value),
    Rewards(Value),
}

#[derive(Debug, Clone, Copy)]
pub enum EntryType {
    Fees,
    Treasury,
    Rewards,
}

impl Entry {
    pub fn value(&self) -> Value {
        match self {
            Entry::Fees(v) => *v,
            Entry::Treasury(v) => *v,
            Entry::Rewards(v) => *v,
        }
    }

    pub fn entry_type(&self) -> EntryType {
        match self {
            Entry::Fees(_) => EntryType::Fees,
            Entry::Treasury(_) => EntryType::Treasury,
            Entry::Rewards(_) => EntryType::Rewards,
        }
    }
}

pub enum IterState {
    Fees,
    Treasury,
    Rewards,
    Done,
}

pub struct Entries<'a> {
    pots: &'a Pots,
    it: IterState,
}

pub struct Values<'a>(Entries<'a>);

impl<'a> Iterator for Entries<'a> {
    type Item = Entry;

    fn next(&mut self) -> Option<Self::Item> {
        match self.it {
            IterState::Fees => {
                self.it = IterState::Treasury;
                Some(Entry::Fees(self.pots.fees))
            }
            IterState::Treasury => {
                self.it = IterState::Rewards;
                Some(Entry::Treasury(self.pots.treasury.value()))
            }
            IterState::Rewards => {
                self.it = IterState::Done;
                Some(Entry::Rewards(self.pots.rewards))
            }
            IterState::Done => None,
        }
    }
}

impl<'a> Iterator for Values<'a> {
    type Item = Value;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|e| e.value())
    }
}

impl Pots {
    /// Create a new empty set of pots
    pub fn zero() -> Self {
        Pots {
            fees: Value::zero(),
            treasury: Treasury::initial(Value::zero()),
            rewards: Value::zero(),
        }
    }

    pub fn entries(&self) -> Entries<'_> {
        Entries {
            pots: self,
            it: IterState::Fees,
        }
    }

    pub fn values(&self) -> Values<'_> {
        Values(self.entries())
    }

    /// Sum the total values in the pots
    pub fn total_value(&self) -> Result<Value, ValueError> {
        Value::sum(self.values())
    }

    /// Append some fees in the pots
    pub fn append_fees(&mut self, fees: Value) -> Result<(), Error> {
        self.fees = (self.fees + fees).map_err(|error| Error::PotValueInvalid { error })?;
        Ok(())
    }

    /// Draw rewards from the pot
    #[must_use]
    pub fn draw_reward(&mut self, expected_reward: Value) -> Value {
        let to_draw = cmp::min(self.rewards, expected_reward);
        self.rewards = (self.rewards - to_draw).unwrap();
        to_draw
    }

    /// Draw rewards from the pot
    #[must_use]
    pub fn draw_treasury(&mut self, expected_treasury: Value) -> Value {
        self.treasury.draw(expected_treasury)
    }

    /// Siphon all the fees
    #[must_use]
    pub fn siphon_fees(&mut self) -> Value {
        let siphoned = self.fees;
        self.fees = Value::zero();
        siphoned
    }

    /// Add to treasury
    pub fn treasury_add(&mut self, value: Value) -> Result<(), Error> {
        self.treasury.add(value)
    }

    /// Add to treasury
    pub fn rewards_add(&mut self, value: Value) -> Result<(), Error> {
        self.rewards = self
            .rewards
            .checked_add(value)
            .map_err(|error| Error::PotValueInvalid { error })?;
        Ok(())
    }

    /// Get the value in the treasury
    pub fn fees_value(&self) -> Value {
        self.fees
    }

    /// Get the value in the treasury
    pub fn treasury_value(&self) -> Value {
        self.treasury.value()
    }

    pub fn set_from_entry(&mut self, e: &Entry) {
        match e {
            Entry::Fees(v) => self.fees = *v,
            Entry::Treasury(v) => self.treasury = Treasury::initial(*v),
            Entry::Rewards(v) => self.rewards = *v,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::Value;
    use quickcheck::{Arbitrary, Gen, TestResult};
    use quickcheck_macros::quickcheck;

    impl Arbitrary for Pots {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            Pots {
                fees: Arbitrary::arbitrary(g),
                treasury: Arbitrary::arbitrary(g),
                rewards: Arbitrary::arbitrary(g),
            }
        }
    }

    #[test]
    pub fn zero_pots() {
        let pots = Pots::zero();
        assert_eq!(pots.fees, Value::zero());
        assert_eq!(pots.treasury, Treasury::initial(Value::zero()));
        assert_eq!(pots.rewards, Value::zero());
    }

    #[quickcheck]
    pub fn entries(pots: Pots) -> TestResult {
        for item in pots.entries() {
            match item {
                Entry::Fees(fees) => {
                    assert_eq!(pots.fees, fees);
                }
                Entry::Treasury(treasury) => {
                    assert_eq!(pots.treasury.value(), treasury);
                }
                Entry::Rewards(rewards) => {
                    assert_eq!(pots.rewards, rewards);
                }
            }
        }
        TestResult::passed()
    }

    #[quickcheck]
    pub fn append_fees(mut pots: Pots, value: Value) -> TestResult {
        if (value + pots.fees).is_err() {
            return TestResult::discard();
        }
        let before = pots.fees;
        pots.append_fees(value).unwrap();
        TestResult::from_bool((before + value).unwrap() == pots.fees)
    }

    #[quickcheck]
    pub fn siphon_fees(mut pots: Pots) -> TestResult {
        let before_siphon = pots.fees;
        let siphoned = pots.siphon_fees();
        if siphoned != before_siphon {
            TestResult::error(format!("{} is not equal to {}", siphoned, before_siphon));
        }
        TestResult::from_bool(pots.fees == Value::zero())
    }

    #[quickcheck]
    pub fn draw_reward(mut pots: Pots, expected_reward: Value) -> TestResult {
        if (expected_reward + pots.rewards).is_err() {
            return TestResult::discard();
        }

        let before_reward = pots.rewards;
        let to_draw = pots.draw_reward(expected_reward);
        let draw_reward = cmp::min(before_reward, expected_reward);
        if to_draw != draw_reward {
            TestResult::error(format!(
                "{} is not equal to smallest of pair({},{})",
                to_draw, before_reward, expected_reward
            ));
        }
        TestResult::from_bool(pots.rewards == (before_reward - to_draw).unwrap())
    }

    #[quickcheck]
    pub fn treasury_add(mut pots: Pots, value: Value) -> TestResult {
        if (value + pots.rewards).is_err() {
            return TestResult::discard();
        }
        let before_add = pots.treasury.value();
        pots.treasury_add(value).unwrap();
        TestResult::from_bool(pots.treasury.value() == (before_add + value).unwrap())
    }
}