referrerpolicy=no-referrer-when-downgrade

pallet_staking/
ledger.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! A Ledger implementation for stakers.
19//!
20//! A [`StakingLedger`] encapsulates all the state and logic related to the stake of bonded
21//! stakers, namely, it handles the following storage items:
22//! * [`Bonded`]: mutates and reads the state of the controller <> stash bond map (to be deprecated
23//! soon);
24//! * [`Ledger`]: mutates and reads the state of all the stakers. The [`Ledger`] storage item stores
25//!   instances of [`StakingLedger`] keyed by the staker's controller account and should be mutated
26//!   and read through the [`StakingLedger`] API;
27//! * [`Payee`]: mutates and reads the reward destination preferences for a bonded stash.
28//! * Staking locks: mutates the locks for staking.
29//!
30//! NOTE: All the storage operations related to the staking ledger (both reads and writes) *MUST* be
31//! performed through the methods exposed by the [`StakingLedger`] implementation in order to ensure
32//! state consistency.
33
34use frame_support::{defensive, ensure, traits::Defensive};
35use sp_runtime::DispatchResult;
36use sp_staking::{StakingAccount, StakingInterface};
37
38use crate::{
39	asset, BalanceOf, Bonded, Config, Error, Ledger, Pallet, Payee, RewardDestination,
40	StakingLedger, VirtualStakers,
41};
42
43#[cfg(any(feature = "runtime-benchmarks", test))]
44use sp_runtime::traits::Zero;
45
46impl<T: Config> StakingLedger<T> {
47	#[cfg(any(feature = "runtime-benchmarks", test))]
48	pub fn default_from(stash: T::AccountId) -> Self {
49		Self {
50			stash: stash.clone(),
51			total: Zero::zero(),
52			active: Zero::zero(),
53			unlocking: Default::default(),
54			legacy_claimed_rewards: Default::default(),
55			controller: Some(stash),
56		}
57	}
58
59	/// Returns a new instance of a staking ledger.
60	///
61	/// The [`Ledger`] storage is not mutated. In order to store, `StakingLedger::update` must be
62	/// called on the returned staking ledger.
63	///
64	/// Note: as the controller accounts are being deprecated, the stash account is the same as the
65	/// controller account.
66	pub fn new(stash: T::AccountId, stake: BalanceOf<T>) -> Self {
67		Self {
68			stash: stash.clone(),
69			active: stake,
70			total: stake,
71			unlocking: Default::default(),
72			legacy_claimed_rewards: Default::default(),
73			// controllers are deprecated and mapped 1-1 to stashes.
74			controller: Some(stash),
75		}
76	}
77
78	/// Returns the paired account, if any.
79	///
80	/// A "pair" refers to the tuple (stash, controller). If the input is a
81	/// [`StakingAccount::Stash`] variant, its pair account will be of type
82	/// [`StakingAccount::Controller`] and vice-versa.
83	///
84	/// This method is meant to abstract from the runtime development the difference between stash
85	/// and controller. This will be deprecated once the controller is fully deprecated as well.
86	pub(crate) fn paired_account(account: StakingAccount<T::AccountId>) -> Option<T::AccountId> {
87		match account {
88			StakingAccount::Stash(stash) => <Bonded<T>>::get(stash),
89			StakingAccount::Controller(controller) =>
90				<Ledger<T>>::get(&controller).map(|ledger| ledger.stash),
91		}
92	}
93
94	/// Returns whether a given account is bonded.
95	pub(crate) fn is_bonded(account: StakingAccount<T::AccountId>) -> bool {
96		match account {
97			StakingAccount::Stash(stash) => <Bonded<T>>::contains_key(stash),
98			StakingAccount::Controller(controller) => <Ledger<T>>::contains_key(controller),
99		}
100	}
101
102	/// Returns a staking ledger, if it is bonded and it exists in storage.
103	///
104	/// This getter can be called with either a controller or stash account, provided that the
105	/// account is properly wrapped in the respective [`StakingAccount`] variant. This is meant to
106	/// abstract the concept of controller/stash accounts from the caller.
107	///
108	/// Returns [`Error::BadState`] when a bond is in "bad state". A bond is in a bad state when a
109	/// stash has a controller which is bonding a ledger associated with another stash.
110	pub(crate) fn get(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
111		let (stash, controller) = match account.clone() {
112			StakingAccount::Stash(stash) =>
113				(stash.clone(), <Bonded<T>>::get(&stash).ok_or(Error::<T>::NotStash)?),
114			StakingAccount::Controller(controller) => (
115				Ledger::<T>::get(&controller)
116					.map(|l| l.stash)
117					.ok_or(Error::<T>::NotController)?,
118				controller,
119			),
120		};
121
122		let ledger = <Ledger<T>>::get(&controller)
123			.map(|mut ledger| {
124				ledger.controller = Some(controller.clone());
125				ledger
126			})
127			.ok_or(Error::<T>::NotController)?;
128
129		// if ledger bond is in a bad state, return error to prevent applying operations that may
130		// further spoil the ledger's state. A bond is in bad state when the bonded controller is
131		// associated with a different ledger (i.e. a ledger with a different stash).
132		//
133		// See <https://github.com/paritytech/polkadot-sdk/issues/3245> for more details.
134		ensure!(
135			Bonded::<T>::get(&stash) == Some(controller) && ledger.stash == stash,
136			Error::<T>::BadState
137		);
138
139		Ok(ledger)
140	}
141
142	/// Returns the reward destination of a staking ledger, stored in [`Payee`].
143	///
144	/// Note: if the stash is not bonded and/or does not have an entry in [`Payee`], it returns the
145	/// default reward destination.
146	pub(crate) fn reward_destination(
147		account: StakingAccount<T::AccountId>,
148	) -> Option<RewardDestination<T::AccountId>> {
149		let stash = match account {
150			StakingAccount::Stash(stash) => Some(stash),
151			StakingAccount::Controller(controller) =>
152				Self::paired_account(StakingAccount::Controller(controller)),
153		};
154
155		if let Some(stash) = stash {
156			<Payee<T>>::get(stash)
157		} else {
158			defensive!("fetched reward destination from unbonded stash {}", stash);
159			None
160		}
161	}
162
163	/// Returns the controller account of a staking ledger.
164	///
165	/// Note: it will fallback into querying the [`Bonded`] storage with the ledger stash if the
166	/// controller is not set in `self`, which most likely means that self was fetched directly from
167	/// [`Ledger`] instead of through the methods exposed in [`StakingLedger`]. If the ledger does
168	/// not exist in storage, it returns `None`.
169	pub fn controller(&self) -> Option<T::AccountId> {
170		self.controller.clone().or_else(|| {
171			defensive!("fetched a controller on a ledger instance without it.");
172			Self::paired_account(StakingAccount::Stash(self.stash.clone()))
173		})
174	}
175
176	/// Inserts/updates a staking ledger account.
177	///
178	/// Bonds the ledger if it is not bonded yet, signalling that this is a new ledger. The staking
179	/// locks of the stash account are updated accordingly.
180	///
181	/// Note: To ensure lock consistency, all the [`Ledger`] storage updates should be made through
182	/// this helper function.
183	pub(crate) fn update(self) -> Result<(), Error<T>> {
184		if !<Bonded<T>>::contains_key(&self.stash) {
185			return Err(Error::<T>::NotStash)
186		}
187
188		// We skip locking virtual stakers.
189		if !Pallet::<T>::is_virtual_staker(&self.stash) {
190			// for direct stakers, update lock on stash based on ledger.
191			asset::update_stake::<T>(&self.stash, self.total)
192				.map_err(|_| Error::<T>::NotEnoughFunds)?;
193		}
194
195		Ledger::<T>::insert(
196			&self.controller().ok_or_else(|| {
197				defensive!("update called on a ledger that is not bonded.");
198				Error::<T>::NotController
199			})?,
200			&self,
201		);
202
203		Ok(())
204	}
205
206	/// Bonds a ledger.
207	///
208	/// It sets the reward preferences for the bonded stash.
209	pub(crate) fn bond(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
210		if <Bonded<T>>::contains_key(&self.stash) {
211			return Err(Error::<T>::AlreadyBonded)
212		}
213
214		<Payee<T>>::insert(&self.stash, payee);
215		<Bonded<T>>::insert(&self.stash, &self.stash);
216		self.update()
217	}
218
219	/// Sets the ledger Payee.
220	pub(crate) fn set_payee(self, payee: RewardDestination<T::AccountId>) -> Result<(), Error<T>> {
221		if !<Bonded<T>>::contains_key(&self.stash) {
222			return Err(Error::<T>::NotStash)
223		}
224
225		<Payee<T>>::insert(&self.stash, payee);
226		Ok(())
227	}
228
229	/// Sets the ledger controller to its stash.
230	pub(crate) fn set_controller_to_stash(self) -> Result<(), Error<T>> {
231		let controller = self.controller.as_ref()
232            .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.")
233            .ok_or(Error::<T>::NotController)?;
234
235		ensure!(self.stash != *controller, Error::<T>::AlreadyPaired);
236
237		// check if the ledger's stash is a controller of another ledger.
238		if let Some(bonded_ledger) = Ledger::<T>::get(&self.stash) {
239			// there is a ledger bonded by the stash. In this case, the stash of the bonded ledger
240			// should be the same as the ledger's stash. Otherwise fail to prevent data
241			// inconsistencies. See <https://github.com/paritytech/polkadot-sdk/pull/3639> for more
242			// details.
243			ensure!(bonded_ledger.stash == self.stash, Error::<T>::BadState);
244		}
245
246		<Ledger<T>>::remove(&controller);
247		<Ledger<T>>::insert(&self.stash, &self);
248		<Bonded<T>>::insert(&self.stash, &self.stash);
249
250		Ok(())
251	}
252
253	/// Clears all data related to a staking ledger and its bond in both [`Ledger`] and [`Bonded`]
254	/// storage items and updates the stash staking lock.
255	pub(crate) fn kill(stash: &T::AccountId) -> DispatchResult {
256		let controller = <Bonded<T>>::get(stash).ok_or(Error::<T>::NotStash)?;
257
258		<Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController).map(|ledger| {
259			Ledger::<T>::remove(controller);
260			<Bonded<T>>::remove(&stash);
261			<Payee<T>>::remove(&stash);
262
263			// kill virtual staker if it exists.
264			if <VirtualStakers<T>>::take(&ledger.stash).is_none() {
265				// if not virtual staker, clear locks.
266				asset::kill_stake::<T>(&ledger.stash)?;
267			}
268
269			Ok(())
270		})?
271	}
272}
273
274#[cfg(test)]
275use {
276	crate::UnlockChunk,
277	codec::{Decode, Encode, MaxEncodedLen},
278	scale_info::TypeInfo,
279};
280
281// This structs makes it easy to write tests to compare staking ledgers fetched from storage. This
282// is required because the controller field is not stored in storage and it is private.
283#[cfg(test)]
284#[derive(frame_support::DebugNoBound, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)]
285pub struct StakingLedgerInspect<T: Config> {
286	pub stash: T::AccountId,
287	#[codec(compact)]
288	pub total: BalanceOf<T>,
289	#[codec(compact)]
290	pub active: BalanceOf<T>,
291	pub unlocking: frame_support::BoundedVec<UnlockChunk<BalanceOf<T>>, T::MaxUnlockingChunks>,
292	pub legacy_claimed_rewards: frame_support::BoundedVec<sp_staking::EraIndex, T::HistoryDepth>,
293}
294
295#[cfg(test)]
296impl<T: Config> PartialEq<StakingLedgerInspect<T>> for StakingLedger<T> {
297	fn eq(&self, other: &StakingLedgerInspect<T>) -> bool {
298		self.stash == other.stash &&
299			self.total == other.total &&
300			self.active == other.active &&
301			self.unlocking == other.unlocking &&
302			self.legacy_claimed_rewards == other.legacy_claimed_rewards
303	}
304}
305
306#[cfg(test)]
307impl<T: Config> codec::EncodeLike<StakingLedger<T>> for StakingLedgerInspect<T> {}