lib.rs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. // Ensure we're `no_std` when compiling for Wasm.
  2. #![cfg_attr(not(feature = "std"), no_std)]
  3. use codec::{Codec, Decode, Encode};
  4. use frame_support::storage::IterableStorageMap;
  5. use frame_support::traits::{Currency, ExistenceRequirement, Get, Imbalance, WithdrawReasons};
  6. use frame_support::{decl_module, decl_storage, ensure, Parameter};
  7. use sp_arithmetic::traits::{BaseArithmetic, One, Zero};
  8. use sp_runtime::traits::{AccountIdConversion, MaybeSerialize, Member};
  9. use sp_runtime::ModuleId;
  10. use sp_std::collections::btree_map::BTreeMap;
  11. use sp_std::prelude::*;
  12. mod errors;
  13. pub use errors::*;
  14. mod macroes;
  15. mod mock;
  16. mod tests;
  17. pub type BalanceOf<T> =
  18. <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
  19. pub type NegativeImbalance<T> =
  20. <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
  21. pub trait Trait: system::Trait + Sized {
  22. /// The currency that is managed by the module
  23. type Currency: Currency<Self::AccountId>;
  24. /// ModuleId for computing deterministic AccountId for the module
  25. type StakePoolId: Get<[u8; 8]>;
  26. /// Type that will handle various staking events
  27. type StakingEventsHandler: StakingEventsHandler<Self>;
  28. /// The type used as a stake identifier.
  29. type StakeId: Parameter
  30. + Member
  31. + BaseArithmetic
  32. + Codec
  33. + Default
  34. + Copy
  35. + MaybeSerialize
  36. + PartialEq;
  37. /// The type used as slash identifier.
  38. type SlashId: Parameter
  39. + Member
  40. + BaseArithmetic
  41. + Codec
  42. + Default
  43. + Copy
  44. + MaybeSerialize
  45. + PartialEq
  46. + Ord; //required to be a key in BTreeMap
  47. }
  48. pub trait StakingEventsHandler<T: Trait> {
  49. /// Handler for unstaking event.
  50. /// The handler is informed of the amount that was unstaked, and the value removed from stake is passed as a negative imbalance.
  51. /// The handler is responsible to consume part or all of the value (for example by moving it into an account). The remainder
  52. /// of the value that is not consumed should be returned as a negative imbalance.
  53. fn unstaked(
  54. id: &T::StakeId,
  55. unstaked_amount: BalanceOf<T>,
  56. remaining_imbalance: NegativeImbalance<T>,
  57. ) -> NegativeImbalance<T>;
  58. /// Handler for slashing event.
  59. /// NB: actually_slashed can be less than amount of the slash itself if the
  60. /// claim amount on the stake cannot cover it fully.
  61. /// The SlashId is optional, as slashing may not be associated with a slashing that was initiated, but was an immediate slashing.
  62. /// For Immediate slashes, the stake may have transitioned to NotStaked so handler should not assume the state
  63. /// is still in staked status.
  64. fn slashed(
  65. id: &T::StakeId,
  66. slash_id: Option<T::SlashId>,
  67. slashed_amount: BalanceOf<T>,
  68. remaining_stake: BalanceOf<T>,
  69. remaining_imbalance: NegativeImbalance<T>,
  70. ) -> NegativeImbalance<T>;
  71. }
  72. /// Default implementation just destroys the unstaked or slashed value
  73. impl<T: Trait> StakingEventsHandler<T> for () {
  74. fn unstaked(
  75. _id: &T::StakeId,
  76. _unstaked_amount: BalanceOf<T>,
  77. _remaining_imbalance: NegativeImbalance<T>,
  78. ) -> NegativeImbalance<T> {
  79. NegativeImbalance::<T>::zero()
  80. }
  81. fn slashed(
  82. _id: &T::StakeId,
  83. _slash_id: Option<T::SlashId>,
  84. _slahed_amount: BalanceOf<T>,
  85. _remaining_stake: BalanceOf<T>,
  86. _remaining_imbalance: NegativeImbalance<T>,
  87. ) -> NegativeImbalance<T> {
  88. NegativeImbalance::<T>::zero()
  89. }
  90. }
  91. /// Helper implementation so we can chain multiple handlers by grouping handlers in tuple pairs.
  92. /// For example for three handlers, A, B and C we can set the StakingEventHandler type on the trait to:
  93. /// type StakingEventHandler = ((A, B), C)
  94. /// Individual handlers are expected consume in full or in part the negative imbalance and return any unconsumed value.
  95. /// The unconsumed value is then passed to the next handler in the chain.
  96. impl<T: Trait, X: StakingEventsHandler<T>, Y: StakingEventsHandler<T>> StakingEventsHandler<T>
  97. for (X, Y)
  98. {
  99. fn unstaked(
  100. id: &T::StakeId,
  101. unstaked_amount: BalanceOf<T>,
  102. imbalance: NegativeImbalance<T>,
  103. ) -> NegativeImbalance<T> {
  104. let unused_imbalance = X::unstaked(id, unstaked_amount, imbalance);
  105. Y::unstaked(id, unstaked_amount, unused_imbalance)
  106. }
  107. fn slashed(
  108. id: &T::StakeId,
  109. slash_id: Option<T::SlashId>,
  110. slashed_amount: BalanceOf<T>,
  111. remaining_stake: BalanceOf<T>,
  112. imbalance: NegativeImbalance<T>,
  113. ) -> NegativeImbalance<T> {
  114. let unused_imbalance = X::slashed(id, slash_id, slashed_amount, remaining_stake, imbalance);
  115. Y::slashed(
  116. id,
  117. slash_id,
  118. slashed_amount,
  119. remaining_stake,
  120. unused_imbalance,
  121. )
  122. }
  123. }
  124. #[derive(Encode, Decode, Copy, Clone, Debug, Default, Eq, PartialEq)]
  125. pub struct Slash<BlockNumber, Balance> {
  126. /// The block where slashing was initiated.
  127. pub started_at_block: BlockNumber,
  128. /// Whether slashing is in active, or conversley paused state.
  129. /// Blocks are only counted towards slashing execution delay when active.
  130. pub is_active: bool,
  131. /// The number blocks which must be finalised while in the active period before the slashing can be executed
  132. pub blocks_remaining_in_active_period_for_slashing: BlockNumber,
  133. /// Amount to slash
  134. pub slash_amount: Balance,
  135. }
  136. #[derive(Encode, Decode, Debug, Default, Eq, PartialEq)]
  137. pub struct UnstakingState<BlockNumber> {
  138. /// The block where the unstaking was initiated
  139. pub started_at_block: BlockNumber,
  140. /// Whether unstaking is in active, or conversely paused state.
  141. /// Blocks are only counted towards unstaking period when active.
  142. pub is_active: bool,
  143. /// The number blocks which must be finalised while in the active period before the unstaking is finished
  144. pub blocks_remaining_in_active_period_for_unstaking: BlockNumber,
  145. }
  146. #[derive(Encode, Decode, Debug, Eq, PartialEq)]
  147. pub enum StakedStatus<BlockNumber> {
  148. /// Baseline staking status, nothing is happening.
  149. Normal,
  150. /// Unstaking is under way.
  151. Unstaking(UnstakingState<BlockNumber>),
  152. }
  153. impl<BlockNumber> Default for StakedStatus<BlockNumber> {
  154. fn default() -> Self {
  155. StakedStatus::Normal
  156. }
  157. }
  158. #[derive(Encode, Decode, Debug, Default, Eq, PartialEq)]
  159. pub struct StakedState<BlockNumber, Balance, SlashId: Ord> {
  160. /// Total amount of funds at stake.
  161. pub staked_amount: Balance,
  162. /// Status of the staking.
  163. pub staked_status: StakedStatus<BlockNumber>,
  164. /// SlashId to use for next Slash that is initiated.
  165. /// Will be incremented by one after adding a new Slash.
  166. pub next_slash_id: SlashId,
  167. /// All ongoing slashing.
  168. pub ongoing_slashes: BTreeMap<SlashId, Slash<BlockNumber, Balance>>,
  169. }
  170. impl<BlockNumber, Balance, SlashId> StakedState<BlockNumber, Balance, SlashId>
  171. where
  172. BlockNumber: BaseArithmetic + Copy,
  173. Balance: BaseArithmetic + Copy,
  174. SlashId: Ord + Copy,
  175. {
  176. /// Iterates over all ongoing slashes and decrements blocks_remaining_in_active_period_for_slashing of active slashes (advancing the timer).
  177. /// Returns true if there was at least one slashe that was active and had its timer advanced.
  178. fn advance_slashing_timer(&mut self) -> bool {
  179. let mut did_advance_timers = false;
  180. for (_slash_id, slash) in self.ongoing_slashes.iter_mut() {
  181. if slash.is_active
  182. && slash.blocks_remaining_in_active_period_for_slashing > Zero::zero()
  183. {
  184. slash.blocks_remaining_in_active_period_for_slashing -= One::one();
  185. did_advance_timers = true;
  186. }
  187. }
  188. did_advance_timers
  189. }
  190. /// Returns pair of slash_id and slashes that should be executed
  191. fn get_slashes_to_finalize(&mut self) -> Vec<(SlashId, Slash<BlockNumber, Balance>)> {
  192. let slashes_to_finalize = self
  193. .ongoing_slashes
  194. .iter()
  195. .filter(|(_, slash)| {
  196. slash.blocks_remaining_in_active_period_for_slashing == Zero::zero()
  197. })
  198. .map(|(slash_id, _)| *slash_id)
  199. .collect::<Vec<_>>();
  200. // remove and return the slashes
  201. slashes_to_finalize
  202. .iter()
  203. .map(|slash_id| {
  204. // assert!(self.ongoing_slashes.contains_key(slash_id))
  205. (*slash_id, self.ongoing_slashes.remove(slash_id).unwrap())
  206. })
  207. .collect()
  208. }
  209. /// Executes a Slash. If remaining at stake drops below the minimum_balance, it will slash the entire staked amount.
  210. /// Returns the actual slashed amount.
  211. fn apply_slash(&mut self, slash_amount: Balance, minimum_balance: Balance) -> Balance {
  212. // calculate how much to slash
  213. let mut slash_amount = if slash_amount > self.staked_amount {
  214. self.staked_amount
  215. } else {
  216. slash_amount
  217. };
  218. // apply the slashing
  219. self.staked_amount -= slash_amount;
  220. // don't leave less than minimum_balance at stake
  221. if self.staked_amount < minimum_balance {
  222. slash_amount += self.staked_amount;
  223. self.staked_amount = Zero::zero();
  224. }
  225. slash_amount
  226. }
  227. /// For all slahes that should be executed, will apply the Slash to the staked amount, and drop it from the ongoing slashes map.
  228. /// Returns a vector of the executed slashes outcome: (SlashId, Slashed Amount, Remaining Staked Amount)
  229. fn finalize_slashes(&mut self, minimum_balance: Balance) -> Vec<(SlashId, Balance, Balance)> {
  230. let mut finalized_slashes: Vec<(SlashId, Balance, Balance)> = Vec::new();
  231. for (slash_id, slash) in self.get_slashes_to_finalize().iter() {
  232. // apply the slashing and get back actual amount slashed
  233. let slashed_amount = self.apply_slash(slash.slash_amount, minimum_balance);
  234. finalized_slashes.push((*slash_id, slashed_amount, self.staked_amount));
  235. }
  236. finalized_slashes
  237. }
  238. }
  239. #[derive(Encode, Decode, Debug, Eq, PartialEq)]
  240. pub enum StakingStatus<BlockNumber, Balance, SlashId: Ord> {
  241. NotStaked,
  242. Staked(StakedState<BlockNumber, Balance, SlashId>),
  243. }
  244. impl<BlockNumber, Balance, SlashId: Ord> Default for StakingStatus<BlockNumber, Balance, SlashId> {
  245. fn default() -> Self {
  246. StakingStatus::NotStaked
  247. }
  248. }
  249. #[derive(Encode, Decode, Default, Debug, Eq, PartialEq)]
  250. pub struct Stake<BlockNumber, Balance, SlashId: Ord> {
  251. /// When role was created
  252. pub created: BlockNumber,
  253. /// Status of any possible ongoing staking
  254. pub staking_status: StakingStatus<BlockNumber, Balance, SlashId>,
  255. }
  256. impl<BlockNumber, Balance, SlashId> Stake<BlockNumber, Balance, SlashId>
  257. where
  258. BlockNumber: Copy + BaseArithmetic + Zero,
  259. Balance: Copy + BaseArithmetic,
  260. SlashId: Copy + Ord + Zero + One,
  261. {
  262. fn new(created_at: BlockNumber) -> Self {
  263. Self {
  264. created: created_at,
  265. staking_status: StakingStatus::NotStaked,
  266. }
  267. }
  268. fn is_not_staked(&self) -> bool {
  269. self.staking_status == StakingStatus::NotStaked
  270. }
  271. /// If staking status is Staked and not currently Unstaking it will increase the staked amount by value.
  272. /// On success returns new total staked value.
  273. /// Increasing stake by zero is an error.
  274. fn increase_stake(&mut self, value: Balance) -> Result<Balance, IncreasingStakeError> {
  275. ensure!(
  276. value > Zero::zero(),
  277. IncreasingStakeError::CannotChangeStakeByZero
  278. );
  279. match self.staking_status {
  280. StakingStatus::Staked(ref mut staked_state) => match staked_state.staked_status {
  281. StakedStatus::Normal => {
  282. staked_state.staked_amount += value;
  283. Ok(staked_state.staked_amount)
  284. }
  285. _ => Err(IncreasingStakeError::CannotIncreaseStakeWhileUnstaking),
  286. },
  287. _ => Err(IncreasingStakeError::NotStaked),
  288. }
  289. }
  290. /// If staking status is Staked and not currently Unstaking, and no ongoing slashes exist, it will decrease the amount at stake
  291. /// by provided value. If remaining at stake drops below the minimum_balance it will decrease the stake to zero.
  292. /// On success returns (the actual amount of stake decreased, the remaining amount at stake).
  293. /// Decreasing stake by zero is an error.
  294. fn decrease_stake(
  295. &mut self,
  296. value: Balance,
  297. minimum_balance: Balance,
  298. ) -> Result<(Balance, Balance), DecreasingStakeError> {
  299. // maybe StakeDecrease
  300. ensure!(
  301. value > Zero::zero(),
  302. DecreasingStakeError::CannotChangeStakeByZero
  303. );
  304. match self.staking_status {
  305. StakingStatus::Staked(ref mut staked_state) => match staked_state.staked_status {
  306. StakedStatus::Normal => {
  307. // prevent decreasing stake if there are any ongoing slashes (irrespective if active or not)
  308. if !staked_state.ongoing_slashes.is_empty() {
  309. return Err(DecreasingStakeError::CannotDecreaseStakeWhileOngoingSlahes);
  310. }
  311. if value > staked_state.staked_amount {
  312. return Err(DecreasingStakeError::InsufficientStake);
  313. }
  314. let stake_to_reduce = if staked_state.staked_amount - value < minimum_balance {
  315. // If staked amount would drop below minimum balance, deduct the entire stake
  316. staked_state.staked_amount
  317. } else {
  318. value
  319. };
  320. staked_state.staked_amount -= stake_to_reduce;
  321. Ok((stake_to_reduce, staked_state.staked_amount))
  322. }
  323. _ => Err(DecreasingStakeError::CannotDecreaseStakeWhileUnstaking),
  324. },
  325. _ => Err(DecreasingStakeError::NotStaked),
  326. }
  327. }
  328. fn start_staking(
  329. &mut self,
  330. value: Balance,
  331. minimum_balance: Balance,
  332. ) -> Result<(), StakingError> {
  333. ensure!(value > Zero::zero(), StakingError::CannotStakeZero);
  334. ensure!(
  335. value >= minimum_balance,
  336. StakingError::CannotStakeLessThanMinimumBalance
  337. );
  338. if self.is_not_staked() {
  339. self.staking_status = StakingStatus::Staked(StakedState {
  340. staked_amount: value,
  341. next_slash_id: Zero::zero(),
  342. ongoing_slashes: BTreeMap::new(),
  343. staked_status: StakedStatus::Normal,
  344. });
  345. Ok(())
  346. } else {
  347. Err(StakingError::AlreadyStaked)
  348. }
  349. }
  350. fn slash_immediate(
  351. &mut self,
  352. slash_amount: Balance,
  353. minimum_balance: Balance,
  354. ) -> Result<(Balance, Balance), ImmediateSlashingError> {
  355. ensure!(
  356. slash_amount > Zero::zero(),
  357. ImmediateSlashingError::SlashAmountShouldBeGreaterThanZero
  358. );
  359. match self.staking_status {
  360. StakingStatus::Staked(ref mut staked_state) => {
  361. // irrespective of wether we are unstaking or not, slash!
  362. let actually_slashed = staked_state.apply_slash(slash_amount, minimum_balance);
  363. let remaining_stake = staked_state.staked_amount;
  364. Ok((actually_slashed, remaining_stake))
  365. }
  366. // can't slash if not staked
  367. _ => Err(ImmediateSlashingError::NotStaked),
  368. }
  369. }
  370. fn initiate_slashing(
  371. &mut self,
  372. slash_amount: Balance,
  373. slash_period: BlockNumber,
  374. now: BlockNumber,
  375. ) -> Result<SlashId, InitiateSlashingError> {
  376. ensure!(
  377. slash_period > Zero::zero(),
  378. InitiateSlashingError::SlashPeriodShouldBeGreaterThanZero
  379. );
  380. ensure!(
  381. slash_amount > Zero::zero(),
  382. InitiateSlashingError::SlashAmountShouldBeGreaterThanZero
  383. );
  384. match self.staking_status {
  385. StakingStatus::Staked(ref mut staked_state) => {
  386. let slash_id = staked_state.next_slash_id;
  387. staked_state.next_slash_id = slash_id + One::one();
  388. staked_state.ongoing_slashes.insert(
  389. slash_id,
  390. Slash {
  391. is_active: true,
  392. blocks_remaining_in_active_period_for_slashing: slash_period,
  393. slash_amount,
  394. started_at_block: now,
  395. },
  396. );
  397. // pause Unstaking if unstaking is active
  398. if let StakedStatus::Unstaking(ref mut unstaking_state) = staked_state.staked_status
  399. {
  400. unstaking_state.is_active = false;
  401. }
  402. Ok(slash_id)
  403. }
  404. _ => Err(InitiateSlashingError::NotStaked),
  405. }
  406. }
  407. fn pause_slashing(&mut self, slash_id: &SlashId) -> Result<(), PauseSlashingError> {
  408. match self.staking_status {
  409. StakingStatus::Staked(ref mut staked_state) => {
  410. match staked_state.ongoing_slashes.get_mut(slash_id) {
  411. Some(ref mut slash) => {
  412. if slash.is_active {
  413. slash.is_active = false;
  414. Ok(())
  415. } else {
  416. Err(PauseSlashingError::AlreadyPaused)
  417. }
  418. }
  419. _ => Err(PauseSlashingError::SlashNotFound),
  420. }
  421. }
  422. _ => Err(PauseSlashingError::NotStaked),
  423. }
  424. }
  425. fn resume_slashing(&mut self, slash_id: &SlashId) -> Result<(), ResumeSlashingError> {
  426. match self.staking_status {
  427. StakingStatus::Staked(ref mut staked_state) => {
  428. match staked_state.ongoing_slashes.get_mut(slash_id) {
  429. Some(ref mut slash) => {
  430. if slash.is_active {
  431. Err(ResumeSlashingError::NotPaused)
  432. } else {
  433. slash.is_active = true;
  434. Ok(())
  435. }
  436. }
  437. _ => Err(ResumeSlashingError::SlashNotFound),
  438. }
  439. }
  440. _ => Err(ResumeSlashingError::NotStaked),
  441. }
  442. }
  443. fn cancel_slashing(&mut self, slash_id: &SlashId) -> Result<(), CancelSlashingError> {
  444. match self.staking_status {
  445. StakingStatus::Staked(ref mut staked_state) => {
  446. if staked_state.ongoing_slashes.remove(slash_id).is_none() {
  447. return Err(CancelSlashingError::SlashNotFound);
  448. }
  449. // unpause unstaking on last ongoing slash cancelled
  450. if staked_state.ongoing_slashes.is_empty() {
  451. if let StakedStatus::Unstaking(ref mut unstaking_state) =
  452. staked_state.staked_status
  453. {
  454. unstaking_state.is_active = true;
  455. }
  456. }
  457. Ok(())
  458. }
  459. _ => Err(CancelSlashingError::NotStaked),
  460. }
  461. }
  462. fn unstake(&mut self) -> Result<Balance, UnstakingError> {
  463. let staked_amount = match self.staking_status {
  464. StakingStatus::Staked(ref staked_state) => {
  465. // prevent unstaking if there are any ongonig slashes (irrespective if active or not)
  466. if !staked_state.ongoing_slashes.is_empty() {
  467. return Err(UnstakingError::CannotUnstakeWhileSlashesOngoing);
  468. }
  469. if StakedStatus::Normal != staked_state.staked_status {
  470. return Err(UnstakingError::AlreadyUnstaking);
  471. }
  472. Ok(staked_state.staked_amount)
  473. }
  474. _ => Err(UnstakingError::NotStaked),
  475. }?;
  476. self.staking_status = StakingStatus::NotStaked;
  477. Ok(staked_amount)
  478. }
  479. fn initiate_unstaking(
  480. &mut self,
  481. unstaking_period: BlockNumber,
  482. now: BlockNumber,
  483. ) -> Result<(), InitiateUnstakingError> {
  484. ensure!(
  485. unstaking_period > Zero::zero(),
  486. InitiateUnstakingError::UnstakingPeriodShouldBeGreaterThanZero
  487. );
  488. match self.staking_status {
  489. StakingStatus::Staked(ref mut staked_state) => {
  490. // prevent unstaking if there are any ongonig slashes (irrespective if active or not)
  491. if !staked_state.ongoing_slashes.is_empty() {
  492. return Err(InitiateUnstakingError::UnstakingError(
  493. UnstakingError::CannotUnstakeWhileSlashesOngoing,
  494. ));
  495. }
  496. if StakedStatus::Normal != staked_state.staked_status {
  497. return Err(InitiateUnstakingError::UnstakingError(
  498. UnstakingError::AlreadyUnstaking,
  499. ));
  500. }
  501. staked_state.staked_status = StakedStatus::Unstaking(UnstakingState {
  502. started_at_block: now,
  503. is_active: true,
  504. blocks_remaining_in_active_period_for_unstaking: unstaking_period,
  505. });
  506. Ok(())
  507. }
  508. _ => Err(InitiateUnstakingError::UnstakingError(
  509. UnstakingError::NotStaked,
  510. )),
  511. }
  512. }
  513. fn pause_unstaking(&mut self) -> Result<(), PauseUnstakingError> {
  514. match self.staking_status {
  515. StakingStatus::Staked(ref mut staked_state) => match staked_state.staked_status {
  516. StakedStatus::Unstaking(ref mut unstaking_state) => {
  517. if unstaking_state.is_active {
  518. unstaking_state.is_active = false;
  519. Ok(())
  520. } else {
  521. Err(PauseUnstakingError::AlreadyPaused)
  522. }
  523. }
  524. _ => Err(PauseUnstakingError::NotUnstaking),
  525. },
  526. _ => Err(PauseUnstakingError::NotStaked),
  527. }
  528. }
  529. fn resume_unstaking(&mut self) -> Result<(), ResumeUnstakingError> {
  530. match self.staking_status {
  531. StakingStatus::Staked(ref mut staked_state) => match staked_state.staked_status {
  532. StakedStatus::Unstaking(ref mut unstaking_state) => {
  533. if !unstaking_state.is_active {
  534. unstaking_state.is_active = true;
  535. Ok(())
  536. } else {
  537. Err(ResumeUnstakingError::NotPaused)
  538. }
  539. }
  540. _ => Err(ResumeUnstakingError::NotUnstaking),
  541. },
  542. _ => Err(ResumeUnstakingError::NotStaked),
  543. }
  544. }
  545. fn finalize_slashing(
  546. &mut self,
  547. minimum_balance: Balance,
  548. ) -> (bool, Vec<(SlashId, Balance, Balance)>) {
  549. match self.staking_status {
  550. StakingStatus::Staked(ref mut staked_state) => {
  551. // tick the slashing timer
  552. let did_update = staked_state.advance_slashing_timer();
  553. // finalize and apply slashes
  554. let slashed = staked_state.finalize_slashes(minimum_balance);
  555. (did_update, slashed)
  556. }
  557. _ => (false, Vec::new()),
  558. }
  559. }
  560. fn finalize_unstaking(&mut self) -> (bool, Option<Balance>) {
  561. let (did_update, unstaked) = match self.staking_status {
  562. StakingStatus::Staked(ref mut staked_state) => match staked_state.staked_status {
  563. StakedStatus::Unstaking(ref mut unstaking_state) => {
  564. // if all slashes were processed and there are no more active slashes
  565. // resume unstaking
  566. if staked_state.ongoing_slashes.is_empty() {
  567. unstaking_state.is_active = true;
  568. }
  569. // tick the unstaking timer
  570. if unstaking_state.is_active
  571. && unstaking_state.blocks_remaining_in_active_period_for_unstaking
  572. > Zero::zero()
  573. {
  574. // tick the unstaking timer
  575. unstaking_state.blocks_remaining_in_active_period_for_unstaking -=
  576. One::one();
  577. }
  578. // finalize unstaking
  579. if unstaking_state.blocks_remaining_in_active_period_for_unstaking
  580. == Zero::zero()
  581. {
  582. (true, Some(staked_state.staked_amount))
  583. } else {
  584. (unstaking_state.is_active, None)
  585. }
  586. }
  587. _ => (false, None),
  588. },
  589. _ => (false, None),
  590. };
  591. // if unstaking was finalized transition to NotStaked state
  592. if unstaked.is_some() {
  593. self.staking_status = StakingStatus::NotStaked;
  594. }
  595. (did_update, unstaked)
  596. }
  597. fn finalize_slashing_and_unstaking(
  598. &mut self,
  599. minimum_balance: Balance,
  600. ) -> (bool, Vec<(SlashId, Balance, Balance)>, Option<Balance>) {
  601. let (did_update_slashing_timers, slashed) = self.finalize_slashing(minimum_balance);
  602. let (did_update_unstaking_timer, unstaked) = self.finalize_unstaking();
  603. (
  604. did_update_slashing_timers || did_update_unstaking_timer,
  605. slashed,
  606. unstaked,
  607. )
  608. }
  609. }
  610. #[derive(Debug, Eq, PartialEq)]
  611. pub struct SlashImmediateOutcome<Balance, NegativeImbalance> {
  612. pub caused_unstake: bool,
  613. pub actually_slashed: Balance,
  614. pub remaining_stake: Balance,
  615. pub remaining_imbalance: NegativeImbalance,
  616. }
  617. decl_storage! {
  618. trait Store for Module<T: Trait> as StakePool {
  619. /// Maps identifiers to a stake.
  620. pub Stakes get(fn stakes): map hasher(blake2_128_concat)
  621. T::StakeId => Stake<T::BlockNumber, BalanceOf<T>, T::SlashId>;
  622. /// Identifier value for next stake, and count of total stakes created (not necessarily the number of current
  623. /// stakes in the Stakes map as stakes can be removed.)
  624. pub StakesCreated get(fn stakes_created): T::StakeId;
  625. }
  626. }
  627. decl_module! {
  628. pub struct Module<T: Trait> for enum Call where origin: T::Origin {
  629. fn on_finalize(_now: T::BlockNumber) {
  630. Self::finalize_slashing_and_unstaking();
  631. }
  632. }
  633. }
  634. impl<T: Trait> Module<T> {
  635. /// The account ID of theis module which holds all the staked balance. (referred to as the stake pool)
  636. ///
  637. /// This actually does computation. If you need to keep using it, then make sure you cache the
  638. /// value and only call this once. Is it deterministic?
  639. pub fn stake_pool_account_id() -> T::AccountId {
  640. ModuleId(T::StakePoolId::get()).into_account()
  641. }
  642. pub fn stake_pool_balance() -> BalanceOf<T> {
  643. T::Currency::free_balance(&Self::stake_pool_account_id())
  644. }
  645. /// Adds a new Stake which is NotStaked, created at given block, into stakes map.
  646. pub fn create_stake() -> T::StakeId {
  647. let stake_id = Self::stakes_created();
  648. <StakesCreated<T>>::put(stake_id + One::one());
  649. <Stakes<T>>::insert(&stake_id, Stake::new(<system::Module<T>>::block_number()));
  650. stake_id
  651. }
  652. /// Given that stake with id exists in stakes and is NotStaked, remove from stakes.
  653. pub fn remove_stake(stake_id: &T::StakeId) -> Result<(), StakeActionError<StakingError>> {
  654. let stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  655. ensure!(
  656. stake.is_not_staked(),
  657. StakeActionError::Error(StakingError::AlreadyStaked)
  658. );
  659. <Stakes<T>>::remove(stake_id);
  660. Ok(())
  661. }
  662. /// Dry run to see if staking can be initiated for the specified stake id. This should
  663. /// be called before stake() to make sure staking is possible before withdrawing funds.
  664. pub fn ensure_can_stake(
  665. stake_id: &T::StakeId,
  666. value: BalanceOf<T>,
  667. ) -> Result<(), StakeActionError<StakingError>> {
  668. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  669. stake
  670. .start_staking(value, T::Currency::minimum_balance())
  671. .err()
  672. .map_or(Ok(()), |err| Err(StakeActionError::Error(err)))
  673. }
  674. /// Provided the stake exists and is in state NotStaked the value is transferred
  675. /// to the module's account, and the corresponding staked_balance is set to this amount in the new Staked state.
  676. /// On error, as the negative imbalance is not returned to the caller, it is the caller's responsibility to return the funds
  677. /// back to the source (by creating a new positive imbalance)
  678. pub fn stake(
  679. stake_id: &T::StakeId,
  680. imbalance: NegativeImbalance<T>,
  681. ) -> Result<(), StakeActionError<StakingError>> {
  682. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  683. let value = imbalance.peek();
  684. stake.start_staking(value, T::Currency::minimum_balance())?;
  685. <Stakes<T>>::insert(stake_id, stake);
  686. Self::deposit_funds_into_stake_pool(imbalance);
  687. Ok(())
  688. }
  689. pub fn stake_from_account(
  690. stake_id: &T::StakeId,
  691. source_account_id: &T::AccountId,
  692. value: BalanceOf<T>,
  693. ) -> Result<(), StakeActionError<StakingFromAccountError>> {
  694. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  695. stake.start_staking(value, T::Currency::minimum_balance())?;
  696. // Its important to only do the transfer as the last step to ensure starting staking was possible.
  697. Self::transfer_funds_from_account_into_stake_pool(source_account_id, value)?;
  698. <Stakes<T>>::insert(stake_id, stake);
  699. Ok(())
  700. }
  701. /// Moves funds from specified account into the module's account
  702. fn transfer_funds_from_account_into_stake_pool(
  703. source: &T::AccountId,
  704. value: BalanceOf<T>,
  705. ) -> Result<(), TransferFromAccountError> {
  706. // We don't use T::Currency::transfer() to prevent fees being incurred.
  707. let negative_imbalance = T::Currency::withdraw(
  708. source,
  709. value,
  710. WithdrawReasons::all(),
  711. ExistenceRequirement::AllowDeath,
  712. )
  713. .map_err(|_err| TransferFromAccountError::InsufficientBalance)?;
  714. Self::deposit_funds_into_stake_pool(negative_imbalance);
  715. Ok(())
  716. }
  717. fn deposit_funds_into_stake_pool(imbalance: NegativeImbalance<T>) {
  718. // move the negative imbalance into the stake pool
  719. T::Currency::resolve_creating(&Self::stake_pool_account_id(), imbalance);
  720. }
  721. /// Moves funds from the module's account into specified account. Should never fail if used internally.
  722. /// Will panic! if value exceeds balance in the pool.
  723. fn transfer_funds_from_pool_into_account(destination: &T::AccountId, value: BalanceOf<T>) {
  724. let imbalance = Self::withdraw_funds_from_stake_pool(value);
  725. T::Currency::resolve_creating(destination, imbalance);
  726. }
  727. /// Withdraws value from the pool and returns a NegativeImbalance.
  728. /// As long as it is only called internally when executing slashes and unstaking, it
  729. /// should never fail as the pool balance is always in sync with total amount at stake.
  730. fn withdraw_funds_from_stake_pool(value: BalanceOf<T>) -> NegativeImbalance<T> {
  731. // We don't use T::Currency::transfer() to prevent fees being incurred.
  732. T::Currency::withdraw(
  733. &Self::stake_pool_account_id(),
  734. value,
  735. WithdrawReasons::all(),
  736. ExistenceRequirement::AllowDeath,
  737. )
  738. .expect("pool had less than expected funds!")
  739. }
  740. /// Dry run to see if the state of stake allows for increasing stake. This should be called
  741. /// to make sure increasing stake is possible before withdrawing funds.
  742. pub fn ensure_can_increase_stake(
  743. stake_id: &T::StakeId,
  744. value: BalanceOf<T>,
  745. ) -> Result<(), StakeActionError<IncreasingStakeError>> {
  746. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  747. stake
  748. .increase_stake(value)
  749. .err()
  750. .map_or(Ok(()), |err| Err(StakeActionError::Error(err)))
  751. }
  752. /// Provided the stake exists and is in state Staked.Normal, then the amount is transferred to the module's account,
  753. /// and the corresponding staked_amount is increased by the value. New value of staked_amount is returned.
  754. /// Caller should call check ensure_can_increase_stake() prior to avoid getting back an error. On error, as the negative imbalance
  755. /// is not returned to the caller, it is the caller's responsibility to return the funds back to the source (by creating a new positive imbalance)
  756. pub fn increase_stake(
  757. stake_id: &T::StakeId,
  758. imbalance: NegativeImbalance<T>,
  759. ) -> Result<BalanceOf<T>, StakeActionError<IncreasingStakeError>> {
  760. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  761. let total_staked_amount = stake.increase_stake(imbalance.peek())?;
  762. <Stakes<T>>::insert(stake_id, stake);
  763. Self::deposit_funds_into_stake_pool(imbalance);
  764. Ok(total_staked_amount)
  765. }
  766. /// Provided the stake exists and is in state Staked.Normal, and the given source account covers the amount,
  767. /// then the amount is transferred to the module's account, and the corresponding staked_amount is increased
  768. /// by the amount. New value of staked_amount is returned.
  769. pub fn increase_stake_from_account(
  770. stake_id: &T::StakeId,
  771. source_account_id: &T::AccountId,
  772. value: BalanceOf<T>,
  773. ) -> Result<BalanceOf<T>, StakeActionError<IncreasingStakeFromAccountError>> {
  774. let mut stake = ensure_stake_exists!(
  775. T,
  776. stake_id,
  777. <StakeActionError<IncreasingStakeFromAccountError>>::StakeNotFound
  778. )?;
  779. let total_staked_amount = stake.increase_stake(value)?;
  780. Self::transfer_funds_from_account_into_stake_pool(&source_account_id, value)?;
  781. <Stakes<T>>::insert(stake_id, stake);
  782. Ok(total_staked_amount)
  783. }
  784. pub fn ensure_can_decrease_stake(
  785. stake_id: &T::StakeId,
  786. value: BalanceOf<T>,
  787. ) -> Result<(), StakeActionError<DecreasingStakeError>> {
  788. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  789. stake
  790. .decrease_stake(value, T::Currency::minimum_balance())
  791. .err()
  792. .map_or(Ok(()), |err| Err(StakeActionError::Error(err)))
  793. }
  794. pub fn decrease_stake(
  795. stake_id: &T::StakeId,
  796. value: BalanceOf<T>,
  797. ) -> Result<(BalanceOf<T>, NegativeImbalance<T>), StakeActionError<DecreasingStakeError>> {
  798. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  799. let (deduct_from_pool, staked_amount) =
  800. stake.decrease_stake(value, T::Currency::minimum_balance())?;
  801. <Stakes<T>>::insert(stake_id, stake);
  802. let imbalance = Self::withdraw_funds_from_stake_pool(deduct_from_pool);
  803. Ok((staked_amount, imbalance))
  804. }
  805. /// Provided the stake exists and is in state Staked.Normal, and the given stake holds at least the value,
  806. /// then the value is transferred from the module's account to the destination_account, and the corresponding
  807. /// staked_amount is decreased by the value. New value of staked_amount is returned.
  808. pub fn decrease_stake_to_account(
  809. stake_id: &T::StakeId,
  810. destination_account_id: &T::AccountId,
  811. value: BalanceOf<T>,
  812. ) -> Result<BalanceOf<T>, StakeActionError<DecreasingStakeError>> {
  813. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  814. let (deduct_from_pool, staked_amount) =
  815. stake.decrease_stake(value, T::Currency::minimum_balance())?;
  816. <Stakes<T>>::insert(stake_id, stake);
  817. Self::transfer_funds_from_pool_into_account(&destination_account_id, deduct_from_pool);
  818. Ok(staked_amount)
  819. }
  820. /// Slashes a stake with immediate effect, returns the outcome of the slashing.
  821. /// Can optionally specify if slashing can result in immediate unstaking if staked amount
  822. /// after slashing goes to zero.
  823. pub fn slash_immediate(
  824. stake_id: &T::StakeId,
  825. slash_amount: BalanceOf<T>,
  826. unstake_on_zero_staked: bool,
  827. ) -> Result<
  828. SlashImmediateOutcome<BalanceOf<T>, NegativeImbalance<T>>,
  829. StakeActionError<ImmediateSlashingError>,
  830. > {
  831. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  832. // Get amount at stake before slashing to be used in unstaked event trigger
  833. let staked_amount_before_slash = ensure_staked_amount!(
  834. stake,
  835. StakeActionError::Error(ImmediateSlashingError::NotStaked)
  836. )?;
  837. let (actually_slashed, remaining_stake) =
  838. stake.slash_immediate(slash_amount, T::Currency::minimum_balance())?;
  839. let caused_unstake = unstake_on_zero_staked && remaining_stake == BalanceOf::<T>::zero();
  840. if caused_unstake {
  841. stake.staking_status = StakingStatus::NotStaked;
  842. }
  843. // Update state before calling handlers!
  844. <Stakes<T>>::insert(stake_id, stake);
  845. // Remove the slashed amount from the pool
  846. let slashed_imbalance = Self::withdraw_funds_from_stake_pool(actually_slashed);
  847. // Notify slashing event handler before unstaked handler.
  848. let remaining_imbalance_after_slash_handler = T::StakingEventsHandler::slashed(
  849. stake_id,
  850. None,
  851. actually_slashed,
  852. remaining_stake,
  853. slashed_imbalance,
  854. );
  855. let remaining_imbalance = if caused_unstake {
  856. // Notify unstaked handler with any remaining unused imbalance
  857. // from the slashing event handler
  858. T::StakingEventsHandler::unstaked(
  859. &stake_id,
  860. staked_amount_before_slash,
  861. remaining_imbalance_after_slash_handler,
  862. )
  863. } else {
  864. remaining_imbalance_after_slash_handler
  865. };
  866. Ok(SlashImmediateOutcome {
  867. caused_unstake,
  868. actually_slashed,
  869. remaining_stake,
  870. remaining_imbalance,
  871. })
  872. }
  873. /// Initiate a new slashing of a staked stake. Slashing begins at next block.
  874. pub fn initiate_slashing(
  875. stake_id: &T::StakeId,
  876. slash_amount: BalanceOf<T>,
  877. slash_period: T::BlockNumber,
  878. ) -> Result<T::SlashId, StakeActionError<InitiateSlashingError>> {
  879. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  880. let slash_id = stake.initiate_slashing(
  881. slash_amount,
  882. slash_period,
  883. <system::Module<T>>::block_number(),
  884. )?;
  885. <Stakes<T>>::insert(stake_id, stake);
  886. Ok(slash_id)
  887. }
  888. /// Pause an ongoing slashing
  889. pub fn pause_slashing(
  890. stake_id: &T::StakeId,
  891. slash_id: &T::SlashId,
  892. ) -> Result<(), StakeActionError<PauseSlashingError>> {
  893. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  894. stake.pause_slashing(slash_id)?;
  895. <Stakes<T>>::insert(stake_id, stake);
  896. Ok(())
  897. }
  898. /// Resume a currently paused ongoing slashing.
  899. pub fn resume_slashing(
  900. stake_id: &T::StakeId,
  901. slash_id: &T::SlashId,
  902. ) -> Result<(), StakeActionError<ResumeSlashingError>> {
  903. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  904. stake.resume_slashing(slash_id)?;
  905. <Stakes<T>>::insert(stake_id, stake);
  906. Ok(())
  907. }
  908. /// Cancel an ongoing slashing (regardless of whether its active or paused).
  909. pub fn cancel_slashing(
  910. stake_id: &T::StakeId,
  911. slash_id: &T::SlashId,
  912. ) -> Result<(), StakeActionError<CancelSlashingError>> {
  913. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  914. stake.cancel_slashing(slash_id)?;
  915. <Stakes<T>>::insert(stake_id, stake);
  916. Ok(())
  917. }
  918. /// Initiate unstaking of a Staked stake.
  919. pub fn initiate_unstaking(
  920. stake_id: &T::StakeId,
  921. unstaking_period: Option<T::BlockNumber>,
  922. ) -> Result<(), StakeActionError<InitiateUnstakingError>> {
  923. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  924. if let Some(unstaking_period) = unstaking_period {
  925. stake.initiate_unstaking(unstaking_period, <system::Module<T>>::block_number())?;
  926. <Stakes<T>>::insert(stake_id, stake);
  927. } else {
  928. let staked_amount = stake.unstake()?;
  929. <Stakes<T>>::insert(stake_id, stake);
  930. let imbalance = Self::withdraw_funds_from_stake_pool(staked_amount);
  931. let _ = T::StakingEventsHandler::unstaked(stake_id, staked_amount, imbalance);
  932. }
  933. Ok(())
  934. }
  935. /// Pause an ongoing Unstaking.
  936. pub fn pause_unstaking(
  937. stake_id: &T::StakeId,
  938. ) -> Result<(), StakeActionError<PauseUnstakingError>> {
  939. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  940. stake.pause_unstaking()?;
  941. <Stakes<T>>::insert(stake_id, stake);
  942. Ok(())
  943. }
  944. /// Resume a currently paused ongoing unstaking.
  945. pub fn resume_unstaking(
  946. stake_id: &T::StakeId,
  947. ) -> Result<(), StakeActionError<ResumeUnstakingError>> {
  948. let mut stake = ensure_stake_exists!(T, stake_id, StakeActionError::StakeNotFound)?;
  949. stake.resume_unstaking()?;
  950. <Stakes<T>>::insert(stake_id, stake);
  951. Ok(())
  952. }
  953. /// Handle timers for finalizing unstaking and slashing.
  954. /// Finalised unstaking results in the staked_balance in the given stake to removed from the pool, the corresponding
  955. /// imbalance is provided to the unstaked() hook in the StakingEventsHandler.
  956. /// Finalised slashing results in the staked_balance in the given stake being correspondingly reduced, and the imbalance
  957. /// is provided to the slashed() hook in the StakingEventsHandler.
  958. fn finalize_slashing_and_unstaking() {
  959. for (stake_id, ref mut stake) in <Stakes<T>>::iter() {
  960. let (updated, slashed, unstaked) =
  961. stake.finalize_slashing_and_unstaking(T::Currency::minimum_balance());
  962. // update the state before making external calls to StakingEventsHandler
  963. if updated {
  964. <Stakes<T>>::insert(stake_id, stake)
  965. }
  966. for (slash_id, slashed_amount, staked_amount) in slashed.into_iter() {
  967. // remove the slashed amount from the pool
  968. let imbalance = Self::withdraw_funds_from_stake_pool(slashed_amount);
  969. let _ = T::StakingEventsHandler::slashed(
  970. &stake_id,
  971. Some(slash_id),
  972. slashed_amount,
  973. staked_amount,
  974. imbalance,
  975. );
  976. }
  977. if let Some(staked_amount) = unstaked {
  978. // remove the unstaked amount from the pool
  979. let imbalance = Self::withdraw_funds_from_stake_pool(staked_amount);
  980. let _ = T::StakingEventsHandler::unstaked(&stake_id, staked_amount, imbalance);
  981. }
  982. }
  983. }
  984. }