pallet_rewards/
lib.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
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
// Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Pallet for issuing rewards to block producers.

#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms)]
#![feature(array_windows, try_blocks)]

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
pub mod weights;

use frame_support::pallet_prelude::*;
use frame_support::traits::Currency;
use frame_system::pallet_prelude::*;
use log::warn;
pub use pallet::*;
use serde::{Deserialize, Serialize};
use sp_core::U256;
use sp_runtime::traits::{CheckedSub, Zero};
use sp_runtime::Saturating;
use subspace_runtime_primitives::{BlockNumber, FindBlockRewardAddress, FindVotingRewardAddresses};

type BalanceOf<T> =
    <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;

/// Hooks to notify when there are any rewards for specific account.
pub trait OnReward<AccountId, Balance> {
    fn on_reward(account: AccountId, reward: Balance);
}

impl<AccountId, Balance> OnReward<AccountId, Balance> for () {
    fn on_reward(_account: AccountId, _reward: Balance) {}
}

#[derive(
    Debug,
    Default,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Encode,
    Decode,
    MaxEncodedLen,
    TypeInfo,
    Serialize,
    Deserialize,
)]
pub struct RewardPoint<BlockNumber, Balance> {
    pub block: BlockNumber,
    pub subsidy: Balance,
}

#[frame_support::pallet]
mod pallet {
    use crate::weights::WeightInfo;
    use crate::{BalanceOf, OnReward, RewardPoint};
    use frame_support::pallet_prelude::*;
    use frame_support::traits::Currency;
    use frame_system::pallet_prelude::*;
    use subspace_runtime_primitives::{FindBlockRewardAddress, FindVotingRewardAddresses};

    /// Pallet rewards for issuing rewards to block producers.
    #[pallet::pallet]
    pub struct Pallet<T>(_);

    #[pallet::config]
    pub trait Config: frame_system::Config {
        /// `pallet-rewards` events
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        type Currency: Currency<Self::AccountId>;

        /// Number of blocks over which to compute average blockspace usage
        #[pallet::constant]
        type AvgBlockspaceUsageNumBlocks: Get<u32>;

        /// Cost of one byte of blockspace
        #[pallet::constant]
        type TransactionByteFee: Get<BalanceOf<Self>>;

        /// Max number of reward points
        #[pallet::constant]
        type MaxRewardPoints: Get<u32>;

        /// Tax of the proposer on vote rewards
        #[pallet::constant]
        type ProposerTaxOnVotes: Get<(u32, u32)>;

        /// Determine whether rewards are enabled or not
        type RewardsEnabled: subspace_runtime_primitives::RewardsEnabled;

        /// Reward address of block producer
        type FindBlockRewardAddress: FindBlockRewardAddress<Self::AccountId>;

        /// Reward addresses of all receivers of voting rewards
        type FindVotingRewardAddresses: FindVotingRewardAddresses<Self::AccountId>;

        type WeightInfo: WeightInfo;

        type OnReward: OnReward<Self::AccountId, BalanceOf<Self>>;
    }

    #[pallet::genesis_config]
    #[derive(Debug)]
    pub struct GenesisConfig<T>
    where
        T: Config,
    {
        /// Tokens left to issue to farmers at any given time
        pub remaining_issuance: BalanceOf<T>,
        /// Block proposer subsidy parameters
        pub proposer_subsidy_points:
            BoundedVec<RewardPoint<BlockNumberFor<T>, BalanceOf<T>>, T::MaxRewardPoints>,
        /// Voter subsidy parameters
        pub voter_subsidy_points:
            BoundedVec<RewardPoint<BlockNumberFor<T>, BalanceOf<T>>, T::MaxRewardPoints>,
    }

    impl<T> Default for GenesisConfig<T>
    where
        T: Config,
    {
        #[inline]
        fn default() -> Self {
            Self {
                remaining_issuance: Default::default(),
                proposer_subsidy_points: Default::default(),
                voter_subsidy_points: Default::default(),
            }
        }
    }

    #[pallet::genesis_build]
    impl<T> BuildGenesisConfig for GenesisConfig<T>
    where
        T: Config,
    {
        fn build(&self) {
            RemainingIssuance::<T>::put(self.remaining_issuance);
            if !self.proposer_subsidy_points.is_empty() {
                ProposerSubsidyPoints::<T>::put(self.proposer_subsidy_points.clone());
            }
            if !self.voter_subsidy_points.is_empty() {
                VoterSubsidyPoints::<T>::put(self.voter_subsidy_points.clone());
            }
        }
    }

    /// Utilization of blockspace (in bytes) by the normal extrinsics used to adjust issuance
    #[pallet::storage]
    pub(crate) type AvgBlockspaceUsage<T> = StorageValue<_, u32, ValueQuery>;

    /// Whether rewards are enabled
    #[pallet::storage]
    pub type RewardsEnabled<T> = StorageValue<_, bool, ValueQuery>;

    /// Tokens left to issue to farmers at any given time
    #[pallet::storage]
    pub type RemainingIssuance<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;

    /// Block proposer subsidy parameters
    #[pallet::storage]
    pub type ProposerSubsidyPoints<T: Config> = StorageValue<
        _,
        BoundedVec<RewardPoint<BlockNumberFor<T>, BalanceOf<T>>, T::MaxRewardPoints>,
        ValueQuery,
    >;

    /// Voter subsidy parameters
    #[pallet::storage]
    pub type VoterSubsidyPoints<T: Config> = StorageValue<
        _,
        BoundedVec<RewardPoint<BlockNumberFor<T>, BalanceOf<T>>, T::MaxRewardPoints>,
        ValueQuery,
    >;

    /// `pallet-rewards` events
    #[pallet::event]
    #[pallet::generate_deposit(pub (super) fn deposit_event)]
    pub enum Event<T: Config> {
        /// Issued reward for the block author
        BlockReward {
            block_author: T::AccountId,
            reward: BalanceOf<T>,
        },
        /// Issued reward for the voter
        VoteReward {
            voter: T::AccountId,
            reward: BalanceOf<T>,
        },
    }

    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
        fn on_finalize(now: BlockNumberFor<T>) {
            Self::do_finalize(now);
        }
    }

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Update dynamic issuance parameters
        #[pallet::call_index(0)]
        #[pallet::weight(T::WeightInfo::update_issuance_params(proposer_subsidy_points.len() as u32, voter_subsidy_points.len() as u32))]
        pub fn update_issuance_params(
            origin: OriginFor<T>,
            proposer_subsidy_points: BoundedVec<
                RewardPoint<BlockNumberFor<T>, BalanceOf<T>>,
                T::MaxRewardPoints,
            >,
            voter_subsidy_points: BoundedVec<
                RewardPoint<BlockNumberFor<T>, BalanceOf<T>>,
                T::MaxRewardPoints,
            >,
        ) -> DispatchResult {
            ensure_root(origin)?;

            ProposerSubsidyPoints::<T>::put(proposer_subsidy_points);
            VoterSubsidyPoints::<T>::put(voter_subsidy_points);

            Ok(())
        }
    }
}

impl<T: Config> Pallet<T> {
    fn do_finalize(block_number: BlockNumberFor<T>) {
        if !<T::RewardsEnabled as subspace_runtime_primitives::RewardsEnabled>::rewards_enabled() {
            return;
        }

        if !RewardsEnabled::<T>::get() {
            RewardsEnabled::<T>::put(true);

            // When rewards are enabled for the first time, adjust points to start with current
            // block number
            ProposerSubsidyPoints::<T>::mutate(|reward_points| {
                reward_points.iter_mut().for_each(|point| {
                    point.block += block_number;
                });
            });
            VoterSubsidyPoints::<T>::mutate(|reward_points| {
                reward_points.iter_mut().for_each(|point| {
                    point.block += block_number;
                });
            });
        }

        let avg_blockspace_usage = Self::update_avg_blockspace_usage(
            frame_system::Pallet::<T>::all_extrinsics_len(),
            AvgBlockspaceUsage::<T>::get(),
            T::AvgBlockspaceUsageNumBlocks::get(),
            frame_system::Pallet::<T>::block_number(),
        );
        AvgBlockspaceUsage::<T>::put(avg_blockspace_usage);

        let old_remaining_issuance = RemainingIssuance::<T>::get();
        let mut new_remaining_issuance = old_remaining_issuance;
        let mut block_reward = Zero::zero();

        // Block author may equivocate, in which case they'll not be present here
        let maybe_block_author = T::FindBlockRewardAddress::find_block_reward_address();
        if maybe_block_author.is_some() {
            // Can't exceed remaining issuance
            block_reward = Self::block_reward(
                &ProposerSubsidyPoints::<T>::get(),
                block_number,
                avg_blockspace_usage,
            )
            .min(new_remaining_issuance);
            new_remaining_issuance -= block_reward;

            // Issue reward later once all voters were taxed
        }

        let voters = T::FindVotingRewardAddresses::find_voting_reward_addresses();
        if !voters.is_empty() {
            let vote_reward = Self::vote_reward(&VoterSubsidyPoints::<T>::get(), block_number);
            // Tax voter
            let proposer_tax = vote_reward / T::ProposerTaxOnVotes::get().1.into()
                * T::ProposerTaxOnVotes::get().0.into();
            // Subtract tax from vote reward
            let vote_reward = vote_reward - proposer_tax;

            for voter in voters {
                // Can't exceed remaining issuance
                let mut reward = vote_reward.min(new_remaining_issuance);
                new_remaining_issuance -= reward;
                // Can't exceed remaining issuance
                let proposer_reward = proposer_tax.min(new_remaining_issuance);
                new_remaining_issuance -= proposer_reward;
                // In case block author equivocated, give full reward to voter
                if maybe_block_author.is_some() {
                    block_reward += proposer_reward;
                } else {
                    reward += proposer_reward;
                }

                if !reward.is_zero() {
                    let _imbalance = T::Currency::deposit_creating(&voter, reward);
                    T::OnReward::on_reward(voter.clone(), reward);

                    Self::deposit_event(Event::VoteReward { voter, reward });
                }
            }
        }

        if let Some(block_author) = maybe_block_author {
            if !block_reward.is_zero() {
                let _imbalance = T::Currency::deposit_creating(&block_author, block_reward);
                T::OnReward::on_reward(block_author.clone(), block_reward);

                Self::deposit_event(Event::BlockReward {
                    block_author,
                    reward: block_reward,
                });
            }
        }

        if old_remaining_issuance != new_remaining_issuance {
            RemainingIssuance::<T>::put(new_remaining_issuance);
        }
    }

    /// Returns new updated average blockspace usage based on given parameters
    fn update_avg_blockspace_usage(
        used_blockspace: u32,
        old_avg_blockspace_usage: u32,
        avg_blockspace_usage_num_blocks: u32,
        block_height: BlockNumberFor<T>,
    ) -> u32 {
        if avg_blockspace_usage_num_blocks == 0 {
            used_blockspace
        } else if block_height <= avg_blockspace_usage_num_blocks.into() {
            (old_avg_blockspace_usage + used_blockspace) / 2
        } else {
            // Multiplier is `a / b` stored as `(a, b)`
            let multiplier = (2, u64::from(avg_blockspace_usage_num_blocks) + 1);

            // Equivalent to `multiplier * used_blockspace + (1 - multiplier) * old_avg_blockspace_usage`
            // using integer math
            let a = multiplier.0 * u64::from(used_blockspace);
            let b = (multiplier.1 - multiplier.0) * u64::from(old_avg_blockspace_usage);

            u32::try_from((a + b) / multiplier.1).expect(
                "Average of blockspace usage can't overflow if individual components do not \
                overflow; qed",
            )
        }
    }

    fn block_reward(
        proposer_subsidy_points: &[RewardPoint<BlockNumberFor<T>, BalanceOf<T>>],
        block_height: BlockNumberFor<T>,
        avg_blockspace_usage: u32,
    ) -> BalanceOf<T> {
        let reference_subsidy =
            Self::reference_subsidy_for_block(proposer_subsidy_points, block_height);
        let max_normal_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);
        let max_block_fee = BalanceOf::<T>::from(max_normal_block_length)
            .saturating_mul(T::TransactionByteFee::get());
        // Reward decrease based on chain utilization
        let reward_decrease = Self::block_number_to_balance(avg_blockspace_usage)
            * reference_subsidy.min(max_block_fee)
            / Self::block_number_to_balance(max_normal_block_length);
        reference_subsidy.saturating_sub(reward_decrease)
    }

    fn vote_reward(
        voter_subsidy_points: &[RewardPoint<BlockNumberFor<T>, BalanceOf<T>>],
        block_height: BlockNumberFor<T>,
    ) -> BalanceOf<T> {
        Self::reference_subsidy_for_block(voter_subsidy_points, block_height)
    }

    fn reference_subsidy_for_block(
        points: &[RewardPoint<BlockNumberFor<T>, BalanceOf<T>>],
        block_height: BlockNumberFor<T>,
    ) -> BalanceOf<T> {
        points
            // Find two points between which current block lies
            .array_windows::<2>()
            .find(|&[from, to]| block_height >= from.block && block_height < to.block)
            .map(|&[from, to]| {
                // Calculate reference subsidy
                Some(
                    from.subsidy
                        - from.subsidy.checked_sub(&to.subsidy)?
                            / Self::block_number_to_balance(to.block - from.block)
                            * Self::block_number_to_balance(block_height - from.block),
                )
            })
            .unwrap_or_else(|| {
                // If no matching points are found and current block number is beyond last block,
                // use last point's subsidy
                points
                    .last()
                    .and_then(|point| (block_height >= point.block).then_some(point.subsidy))
            })
            .unwrap_or_default()
    }

    fn block_number_to_balance<N>(n: N) -> BalanceOf<T>
    where
        N: Into<BlockNumberFor<T>>,
    {
        let n = Into::<BlockNumberFor<T>>::into(n);
        BalanceOf::<T>::from(
            BlockNumber::try_from(Into::<U256>::into(n))
                .expect("Block number fits into block number; qed"),
        )
    }
}