casper-types 0.1.0

Types used to allow creation of Wasm contracts and tests for use on the Casper network.
Documentation
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Contains implementation of a Auction contract functionality.
mod bid;
mod constants;
mod detail;
mod providers;
mod seigniorage_recipient;
mod types;
mod unbonding_purse;

use alloc::{collections::BTreeMap, vec::Vec};

use num_rational::Ratio;

use crate::{
    account::AccountHash,
    system_contract_errors::auction::{Error, Result},
    Key, PublicKey, URef, U512,
};

pub use bid::Bid;
pub use constants::*;
pub use providers::{MintProvider, RuntimeProvider, StorageProvider, SystemProvider};
pub use seigniorage_recipient::SeigniorageRecipient;
pub use types::*;
pub use unbonding_purse::UnbondingPurse;

/// Bonding auction contract interface
pub trait Auction:
    StorageProvider + SystemProvider + RuntimeProvider + MintProvider + Sized
{
    /// Returns era_validators.
    ///
    /// Publicly accessible, but intended for periodic use by the PoS contract to update its own
    /// internal data structures recording current and past winners.
    fn get_era_validators(&mut self) -> Result<EraValidators> {
        let era_validators = detail::get_era_validators(self)?;
        Ok(era_validators)
    }

    /// Returns validators in era_validators, mapped to their bids or founding stakes, delegation
    /// rates and lists of delegators together with their delegated quantities from delegators.
    /// This function is publicly accessible, but intended for system use by the PoS contract,
    /// because this data is necessary for distributing seigniorage.
    fn read_seigniorage_recipients(&mut self) -> Result<SeigniorageRecipients> {
        // `era_validators` are assumed to be computed already by calling "run_auction" entrypoint.
        let era_index = detail::get_era_id(self)?;
        let mut seigniorage_recipients_snapshot =
            detail::get_seigniorage_recipients_snapshot(self)?;
        let seigniorage_recipients = seigniorage_recipients_snapshot
            .remove(&era_index)
            .unwrap_or_else(|| panic!("No seigniorage_recipients for era {}", era_index));
        Ok(seigniorage_recipients)
    }

    /// For a non-founder validator, this adds, or modifies, an entry in the `bids` collection and
    /// calls `bond` in the Mint contract to create (or top off) a bid purse. It also adjusts the
    /// delegation rate.
    fn add_bid(
        &mut self,
        public_key: PublicKey,
        source: URef,
        delegation_rate: DelegationRate,
        amount: U512,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        // Creates new purse with desired amount taken from `source_purse`
        // Bonds whole amount from the newly created purse
        let (bonding_purse, _total_amount) = detail::bond(self, public_key, source, amount)?;

        // Update bids or stakes
        let mut validators = detail::get_bids(self)?;

        let bid = validators
            .entry(public_key)
            .and_modify(|bid| {
                // Update `bids` map since `account_hash` belongs to a validator.
                bid.bonding_purse = bonding_purse;
                bid.delegation_rate = delegation_rate;
                bid.staked_amount += amount;

                // bid.staked_amount
            })
            .or_insert_with(|| {
                // Create new entry.
                Bid {
                    bonding_purse,
                    staked_amount: amount,
                    delegation_rate,
                    funds_locked: None,
                }
            });
        let new_amount = bid.staked_amount;
        detail::set_bids(self, validators)?;

        Ok(new_amount)
    }

    /// For a non-founder validator, implements essentially the same logic as add_bid, but reducing
    /// the number of tokens and calling unbond in lieu of bond.
    ///
    /// For a founding validator, this function first checks whether they are released, and fails
    /// if they are not.
    ///
    /// The function returns a the new amount of motes remaining in the bid. If the target bid
    /// does not exist, the function call returns an error.
    fn withdraw_bid(
        &mut self,
        public_key: PublicKey,
        amount: U512,
        unbond_purse: URef,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        // Update bids or stakes
        let mut bids = detail::get_bids(self)?;

        let bid = bids.get_mut(&public_key).ok_or(Error::ValidatorNotFound)?;

        let new_amount = if bid.can_withdraw_funds() {
            // Carefully decrease bonded funds
            let new_amount = bid
                .staked_amount
                .checked_sub(amount)
                .ok_or(Error::InvalidAmount)?;
            bid.staked_amount = new_amount;
            new_amount
        } else {
            // If validator is still locked-up (or with an autowin status), no withdrawals
            // are allowed.
            return Err(Error::ValidatorFundsLocked);
        };

        if new_amount.is_zero() {
            bids.remove(&public_key).unwrap();
        }

        detail::set_bids(self, bids)?;

        let _total_amount = detail::unbond(self, public_key, amount, unbond_purse)?;

        Ok(new_amount)
    }

    /// Adds a new delegator to delegators, or tops off a current one. If the target validator is
    /// not in founders, the function call returns an error and does nothing.
    ///
    /// The function calls bond in the Mint contract to transfer motes to the validator's purse and
    /// returns a tuple of that purse and the amount of motes contained in it after the transfer.
    fn delegate(
        &mut self,
        delegator_public_key: PublicKey,
        source: URef,
        validator_public_key: PublicKey,
        amount: U512,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(delegator_public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        let bids = detail::get_bids(self)?;
        if !bids.contains_key(&validator_public_key) {
            // Return early if target validator is not in `bids`
            return Err(Error::ValidatorNotFound);
        }

        let (_bonding_purse, _total_amount) =
            detail::bond(self, delegator_public_key, source, amount)?;

        let new_delegation_amount =
            detail::update_delegators(self, validator_public_key, delegator_public_key, amount)?;

        // Initialize delegator_reward_pool_map entry if it doesn't exist.
        {
            let mut delegator_reward_map = detail::get_delegator_reward_map(self)?;
            delegator_reward_map
                .entry(validator_public_key)
                .or_default()
                .entry(delegator_public_key)
                .or_insert_with(U512::zero);
            detail::set_delegator_reward_map(self, delegator_reward_map)?;
        }

        Ok(new_delegation_amount)
    }

    /// Removes an amount of motes (or the entry altogether, if the remaining amount is 0) from
    /// the entry in delegators and calls unbond in the Mint contract to create a new unbonding
    /// purse.
    ///
    /// The arguments are the delegator’s key, the validator key and quantity of motes and
    /// returns a tuple of the unbonding purse along with the remaining bid amount.
    fn undelegate(
        &mut self,
        delegator_public_key: PublicKey,
        validator_public_key: PublicKey,
        amount: U512,
        unbonding_purse: URef,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(delegator_public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        let bids = detail::get_bids(self)?;

        // Return early if target validator is not in `bids`
        if !bids.contains_key(&validator_public_key) {
            return Err(Error::ValidatorNotFound);
        }

        let _unbonding_purse_balance =
            detail::unbond(self, delegator_public_key, amount, unbonding_purse)?;

        let mut delegators = detail::get_delegators(self)?;
        let delegators_map = delegators
            .get_mut(&validator_public_key)
            .ok_or(Error::ValidatorNotFound)?;

        let new_amount = {
            let delegators_amount = delegators_map
                .get_mut(&delegator_public_key)
                .ok_or(Error::DelegatorNotFound)?;

            let new_amount = delegators_amount
                .checked_sub(amount)
                .ok_or(Error::InvalidAmount)?;

            *delegators_amount = new_amount;
            new_amount
        };

        debug_assert!(_unbonding_purse_balance > new_amount);

        if new_amount.is_zero() {
            let _value = delegators_map
                .remove(&delegator_public_key)
                .ok_or(Error::DelegatorNotFound)?;
            debug_assert!(_value.is_zero());

            let mut outer = detail::get_delegator_reward_map(self)?;
            let mut inner = outer
                .remove(&validator_public_key)
                .ok_or(Error::ValidatorNotFound)?;
            inner
                .remove(&delegator_public_key)
                .ok_or(Error::DelegatorNotFound)?;
            if !inner.is_empty() {
                outer.insert(validator_public_key, inner);
            };
            detail::set_delegator_reward_map(self, outer)?;
        }

        detail::set_delegators(self, delegators)?;

        Ok(new_amount)
    }

    /// Slashes each validator.
    ///
    /// This can be only invoked through a system call.
    fn slash(&mut self, validator_public_keys: Vec<PublicKey>) -> Result<()> {
        if self.get_caller() != SYSTEM_ACCOUNT {
            return Err(Error::InvalidCaller);
        }

        detail::quash_bid(self, &validator_public_keys)?;

        let bid_purses_uref = self
            .get_key(BID_PURSES_KEY)
            .and_then(Key::into_uref)
            .ok_or(Error::MissingKey)?;

        let mut bid_purses: BidPurses = self.read(bid_purses_uref)?.ok_or(Error::Storage)?;

        let unbonding_purses_uref = self
            .get_key(UNBONDING_PURSES_KEY)
            .and_then(Key::into_uref)
            .ok_or(Error::MissingKey)?;
        let mut unbonding_purses: UnbondingPurses =
            self.read(unbonding_purses_uref)?.ok_or(Error::Storage)?;

        let mut bid_purses_modified = false;
        let mut unbonding_purses_modified = false;
        for validator_account_hash in validator_public_keys {
            if let Some(_bid_purse) = bid_purses.remove(&validator_account_hash) {
                bid_purses_modified = true;
            }

            if let Some(unbonding_list) = unbonding_purses.get_mut(&validator_account_hash) {
                let size_before = unbonding_list.len();

                unbonding_list.retain(|element| element.origin != validator_account_hash);

                unbonding_purses_modified = size_before != unbonding_list.len();
            }
        }

        if bid_purses_modified {
            self.write(bid_purses_uref, bid_purses)?;
        }

        if unbonding_purses_modified {
            self.write(unbonding_purses_uref, unbonding_purses)?;
        }

        Ok(())
    }

    /// Takes active_bids and delegators to construct a list of validators' total bids (their own
    /// added to their delegators') ordered by size from largest to smallest, then takes the top N
    /// (number of auction slots) bidders and replaces era_validators with these.
    ///
    /// Accessed by: node
    fn run_auction(&mut self) -> Result<()> {
        if self.get_caller() != SYSTEM_ACCOUNT {
            return Err(Error::InvalidCaller);
        }

        detail::process_unbond_requests(self)?;

        // get allowed validator slots total
        let validator_slots = detail::get_validator_slots(self)?;

        let auction_delay = detail::get_auction_delay(self)?;
        let snapshot_size = auction_delay as usize + 1;

        let mut era_id = detail::get_era_id(self)?;

        let mut bids = detail::get_bids(self)?;
        //
        // Process locked bids
        //
        let mut bids_modified = false;
        for bid in bids.values_mut() {
            if let Some(locked_until) = bid.funds_locked {
                if era_id >= locked_until {
                    bid.funds_locked = None;
                    bids_modified = true;
                }
            }
        }

        //
        // Compute next auction slots
        //

        // Take winning validators and add them to validator_weights right away.
        let mut bid_weights: ValidatorWeights = {
            bids.iter()
                .filter(|(_validator_account_hash, founding_validator)| {
                    founding_validator.funds_locked.is_some()
                })
                .map(|(validator_account_hash, amount)| {
                    (*validator_account_hash, amount.staked_amount)
                })
                .collect()
        };

        // Non-winning validators are taken care of later
        let bid_scores = bids
            .iter()
            .filter(|(_validator_account_hash, founding_validator)| {
                founding_validator.funds_locked.is_none()
            })
            .map(|(validator_account_hash, amount)| {
                (*validator_account_hash, amount.staked_amount)
            });

        // Validator's entries from both maps as a single iterable.
        // let all_scores = founders_scores.chain(validators_scores);

        // All the scores are then grouped by the account hash to calculate a sum of each
        // consecutive scores for each validator.
        let mut scores = BTreeMap::new();
        for (account_hash, score) in bid_scores {
            scores
                .entry(account_hash)
                .and_modify(|acc| *acc += score)
                .or_insert_with(|| score);
        }

        // Compute new winning validators.
        let mut scores: Vec<_> = scores.into_iter().collect();
        // Sort the results in descending order
        scores.sort_by(|(_, lhs), (_, rhs)| rhs.cmp(lhs));

        // Fill in remaining validators
        let remaining_auction_slots = validator_slots.saturating_sub(bid_weights.len());
        bid_weights.extend(scores.into_iter().take(remaining_auction_slots));

        let mut era_validators = detail::get_era_validators(self)?;

        // Era index is assumed to be equal to era id on the consensus side.
        era_id += 1;

        let next_era_id = era_id + auction_delay;

        //
        // Compute seiginiorage recipients for current era
        //
        let mut delegators = detail::get_delegators(self)?;
        let mut seigniorage_recipients_snapshot =
            detail::get_seigniorage_recipients_snapshot(self)?;
        let mut seigniorage_recipients = SeigniorageRecipients::new();

        // for each validator...
        for era_validator in bid_weights.keys() {
            let mut seigniorage_recipient = SeigniorageRecipient::default();
            // ... mapped to their bids
            if let Some(founding_validator) = bids.get(era_validator) {
                seigniorage_recipient.stake = founding_validator.staked_amount;
                seigniorage_recipient.delegation_rate = founding_validator.delegation_rate;
            }

            if let Some(delegator_map) = delegators.remove(era_validator) {
                seigniorage_recipient.delegators = delegator_map;
            }

            seigniorage_recipients.insert(*era_validator, seigniorage_recipient);
        }
        let previous_seigniorage_recipients =
            seigniorage_recipients_snapshot.insert(next_era_id, seigniorage_recipients);
        assert!(previous_seigniorage_recipients.is_none());

        let seigniorage_recipients_snapshot = seigniorage_recipients_snapshot
            .into_iter()
            .rev()
            .take(snapshot_size)
            .collect();
        detail::set_seigniorage_recipients_snapshot(self, seigniorage_recipients_snapshot)?;

        // Index for next set of validators: `era_id + AUCTION_DELAY`
        let previous_era_validators = era_validators.insert(era_id + auction_delay, bid_weights);
        assert!(previous_era_validators.is_none());

        detail::set_era_id(self, era_id)?;
        // Keep maximum of `AUCTION_DELAY + 1` elements
        let era_validators = era_validators
            .into_iter()
            .rev()
            .take(snapshot_size)
            .collect();

        detail::set_era_validators(self, era_validators)?;

        if bids_modified {
            detail::set_bids(self, bids)?;
        }

        Ok(())
    }

    /// Mint and distribute seigniorage rewards to validators and their delegators,
    /// according to `reward_factors` returned by the consensus component.
    fn distribute(&mut self, reward_factors: BTreeMap<PublicKey, u64>) -> Result<()> {
        if self.get_caller() != SYSTEM_ACCOUNT {
            return Err(Error::InvalidCaller);
        }

        let seigniorage_recipients = self.read_seigniorage_recipients()?;
        let base_round_reward = self.read_base_round_reward()?;

        if reward_factors.keys().ne(seigniorage_recipients.keys()) {
            return Err(Error::MismatchedEraValidators);
        }

        for (public_key, reward_factor) in reward_factors {
            let recipient = seigniorage_recipients
                .get(&public_key)
                .ok_or(Error::ValidatorNotFound)?;

            let total_stake = recipient.total_stake();
            if total_stake.is_zero() {
                // TODO: error?
                continue;
            }

            let total_reward: Ratio<U512> = {
                let reward_rate = Ratio::new(U512::from(reward_factor), U512::from(BLOCK_REWARD));
                reward_rate * base_round_reward
            };

            let delegator_total_stake: U512 = recipient.delegator_total_stake();

            let delegators_part: Ratio<U512> = {
                let commission_rate = Ratio::new(
                    U512::from(recipient.delegation_rate),
                    U512::from(DELEGATION_RATE_DENOMINATOR),
                );
                let reward_multiplier: Ratio<U512> = Ratio::new(delegator_total_stake, total_stake);
                let delegator_reward: Ratio<U512> = total_reward * reward_multiplier;
                let commission: Ratio<U512> = delegator_reward * commission_rate;
                delegator_reward - commission
            };

            let delegator_rewards =
                recipient
                    .delegators
                    .iter()
                    .map(|(delegator_key, delegator_stake)| {
                        let reward_multiplier = Ratio::new(*delegator_stake, delegator_total_stake);
                        let reward = delegators_part * reward_multiplier;
                        (*delegator_key, reward)
                    });
            let total_delegator_payout: U512 =
                detail::update_delegator_rewards(self, public_key, delegator_rewards)?;

            let validators_part: Ratio<U512> = total_reward - Ratio::from(total_delegator_payout);
            let validator_reward = validators_part.to_integer();
            detail::update_validator_reward(self, public_key, validator_reward)?;

            // TODO: add "mint into existing purse" facility
            let validator_reward_purse = self
                .get_key(VALIDATOR_REWARD_PURSE_KEY)
                .ok_or(Error::MissingKey)?
                .into_uref()
                .ok_or(Error::InvalidKeyVariant)?;
            let tmp_validator_reward_purse =
                self.mint(validator_reward).map_err(|_| Error::MintReward)?;
            self.transfer_purse_to_purse(
                tmp_validator_reward_purse,
                validator_reward_purse,
                validator_reward,
            )
            .map_err(|_| Error::Transfer)?;

            // TODO: add "mint into existing purse" facility
            let delegator_reward_purse = self
                .get_key(DELEGATOR_REWARD_PURSE_KEY)
                .ok_or(Error::MissingKey)?
                .into_uref()
                .ok_or(Error::InvalidKeyVariant)?;
            let tmp_delegator_reward_purse = self
                .mint(total_delegator_payout)
                .map_err(|_| Error::MintReward)?;
            self.transfer_purse_to_purse(
                tmp_delegator_reward_purse,
                delegator_reward_purse,
                total_delegator_payout,
            )
            .map_err(|_| Error::Transfer)?;
        }
        Ok(())
    }

    /// Allows delegators to withdraw the seigniorage rewards they have earned.
    /// Pays out the entire accumulated amount to the destination purse.
    fn withdraw_delegator_reward(
        &mut self,
        validator_public_key: PublicKey,
        delegator_public_key: PublicKey,
        target_purse: URef,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(delegator_public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        let mut outer: DelegatorRewardMap = detail::get_delegator_reward_map(self)?;
        let mut inner = outer
            .remove(&validator_public_key)
            .ok_or(Error::ValidatorNotFound)?;

        let reward_amount: &mut U512 = inner
            .get_mut(&delegator_public_key)
            .ok_or(Error::DelegatorNotFound)?;

        let ret = *reward_amount;

        if !ret.is_zero() {
            let source_purse = self
                .get_key(DELEGATOR_REWARD_PURSE_KEY)
                .ok_or(Error::MissingKey)?
                .into_uref()
                .ok_or(Error::InvalidKeyVariant)?;

            self.transfer_purse_to_purse(source_purse, target_purse, *reward_amount)
                .map_err(|_| Error::Transfer)?;

            *reward_amount = U512::zero();
        }

        outer.insert(validator_public_key, inner);
        detail::set_delegator_reward_map(self, outer)?;
        Ok(ret)
    }

    /// Allows validators to withdraw the seigniorage rewards they have earned.
    /// Pays out the entire accumulated amount to the destination purse.
    fn withdraw_validator_reward(
        &mut self,
        validator_public_key: PublicKey,
        target_purse: URef,
    ) -> Result<U512> {
        let account_hash = AccountHash::from_public_key(validator_public_key, |x| self.blake2b(x));
        if self.get_caller() != account_hash {
            return Err(Error::InvalidPublicKey);
        }

        let mut validator_reward_map = detail::get_validator_reward_map(self)?;

        let reward_amount: &mut U512 = validator_reward_map
            .get_mut(&validator_public_key)
            .ok_or(Error::ValidatorNotFound)?;

        let ret = *reward_amount;

        if !ret.is_zero() {
            let source_purse = self
                .get_key(VALIDATOR_REWARD_PURSE_KEY)
                .ok_or(Error::MissingKey)?
                .into_uref()
                .ok_or(Error::InvalidKeyVariant)?;

            self.transfer_purse_to_purse(source_purse, target_purse, *reward_amount)
                .map_err(|_| Error::Transfer)?;

            *reward_amount = U512::zero();
        }

        detail::set_validator_reward_map(self, validator_reward_map)?;
        Ok(ret)
    }

    /// Reads current era id.
    fn read_era_id(&mut self) -> Result<EraId> {
        detail::get_era_id(self)
    }
}