1use super::*;
20use frame_support::traits::{
21 tokens::{
22 Fortitude,
23 Preservation::{self, Preserve, Protect},
24 Provenance::{self, Minted},
25 },
26 AccountTouch,
27};
28
29impl<T: Config<I>, I: 'static> fungible::Inspect<T::AccountId> for Pallet<T, I> {
30 type Balance = T::Balance;
31
32 fn total_issuance() -> Self::Balance {
33 TotalIssuance::<T, I>::get()
34 }
35 fn active_issuance() -> Self::Balance {
36 TotalIssuance::<T, I>::get().saturating_sub(InactiveIssuance::<T, I>::get())
37 }
38 fn minimum_balance() -> Self::Balance {
39 T::ExistentialDeposit::get()
40 }
41 fn total_balance(who: &T::AccountId) -> Self::Balance {
42 Self::account(who).total()
43 }
44 fn balance(who: &T::AccountId) -> Self::Balance {
45 Self::account(who).free
46 }
47 fn reducible_balance(
48 who: &T::AccountId,
49 preservation: Preservation,
50 force: Fortitude,
51 ) -> Self::Balance {
52 let a = Self::account(who);
53 let mut untouchable = Zero::zero();
54 if force == Polite {
55 untouchable = a.frozen.saturating_sub(a.reserved);
58 }
59 if preservation == Preserve
61 || preservation == Protect && !a.free.is_zero() &&
63 frame_system::Pallet::<T>::providers(who) == 1
64 || preservation == Expendable && !a.free.is_zero() &&
66 !frame_system::Pallet::<T>::can_dec_provider(who)
67 {
68 untouchable = untouchable.max(T::ExistentialDeposit::get());
70 }
71 a.free.saturating_sub(untouchable)
73 }
74 fn can_deposit(
75 who: &T::AccountId,
76 amount: Self::Balance,
77 provenance: Provenance,
78 ) -> DepositConsequence {
79 if amount.is_zero() {
80 return DepositConsequence::Success
81 }
82
83 if provenance == Minted && TotalIssuance::<T, I>::get().checked_add(&amount).is_none() {
84 return DepositConsequence::Overflow
85 }
86
87 let account = Self::account(who);
88 let new_free = match account.free.checked_add(&amount) {
89 None => return DepositConsequence::Overflow,
90 Some(x) if x < T::ExistentialDeposit::get() => return DepositConsequence::BelowMinimum,
91 Some(x) => x,
92 };
93
94 match account.reserved.checked_add(&new_free) {
95 Some(_) => {},
96 None => return DepositConsequence::Overflow,
97 };
98
99 DepositConsequence::Success
103 }
104 fn can_withdraw(
105 who: &T::AccountId,
106 amount: Self::Balance,
107 ) -> WithdrawConsequence<Self::Balance> {
108 if amount.is_zero() {
109 return WithdrawConsequence::Success
110 }
111
112 if TotalIssuance::<T, I>::get().checked_sub(&amount).is_none() {
113 return WithdrawConsequence::Underflow
114 }
115
116 let account = Self::account(who);
117 let new_free_balance = match account.free.checked_sub(&amount) {
118 Some(x) => x,
119 None => return WithdrawConsequence::BalanceLow,
120 };
121
122 let liquid = Self::reducible_balance(who, Expendable, Polite);
123 if amount > liquid {
124 return WithdrawConsequence::Frozen
125 }
126
127 let ed = T::ExistentialDeposit::get();
132 let success = if new_free_balance < ed {
133 if frame_system::Pallet::<T>::can_dec_provider(who) {
134 WithdrawConsequence::ReducedToZero(new_free_balance)
135 } else {
136 return WithdrawConsequence::WouldDie
137 }
138 } else {
139 WithdrawConsequence::Success
140 };
141
142 let new_total_balance = new_free_balance.saturating_add(account.reserved);
143
144 if new_total_balance < account.frozen {
146 return WithdrawConsequence::Frozen
147 }
148
149 success
150 }
151}
152
153impl<T: Config<I>, I: 'static> fungible::Unbalanced<T::AccountId> for Pallet<T, I> {
154 fn handle_dust(dust: fungible::Dust<T::AccountId, Self>) {
155 T::DustRemoval::on_unbalanced(dust.into_credit());
156 }
157 fn write_balance(
158 who: &T::AccountId,
159 amount: Self::Balance,
160 ) -> Result<Option<Self::Balance>, DispatchError> {
161 let max_reduction =
162 <Self as fungible::Inspect<_>>::reducible_balance(who, Expendable, Force);
163 let (result, maybe_dust) = Self::mutate_account(who, false, |account| -> DispatchResult {
164 let reduction = account.free.saturating_sub(amount);
166 ensure!(reduction <= max_reduction, Error::<T, I>::InsufficientBalance);
167
168 account.free = amount;
169 Ok(())
170 })?;
171 result?;
172 Ok(maybe_dust)
173 }
174
175 fn set_total_issuance(amount: Self::Balance) {
176 TotalIssuance::<T, I>::mutate(|t| *t = amount);
177 }
178
179 fn deactivate(amount: Self::Balance) {
180 InactiveIssuance::<T, I>::mutate(|b| {
181 *b = b.saturating_add(amount).min(TotalIssuance::<T, I>::get());
183 });
184 }
185
186 fn reactivate(amount: Self::Balance) {
187 InactiveIssuance::<T, I>::mutate(|b| b.saturating_reduce(amount));
188 }
189}
190
191impl<T: Config<I>, I: 'static> fungible::Mutate<T::AccountId> for Pallet<T, I> {
192 fn done_mint_into(who: &T::AccountId, amount: Self::Balance) {
193 Self::deposit_event(Event::<T, I>::Minted { who: who.clone(), amount });
194 }
195 fn done_burn_from(who: &T::AccountId, amount: Self::Balance) {
196 Self::deposit_event(Event::<T, I>::Burned { who: who.clone(), amount });
197 }
198 fn done_shelve(who: &T::AccountId, amount: Self::Balance) {
199 Self::deposit_event(Event::<T, I>::Suspended { who: who.clone(), amount });
200 }
201 fn done_restore(who: &T::AccountId, amount: Self::Balance) {
202 Self::deposit_event(Event::<T, I>::Restored { who: who.clone(), amount });
203 }
204 fn done_transfer(source: &T::AccountId, dest: &T::AccountId, amount: Self::Balance) {
205 Self::deposit_event(Event::<T, I>::Transfer {
206 from: source.clone(),
207 to: dest.clone(),
208 amount,
209 });
210 }
211}
212
213impl<T: Config<I>, I: 'static> fungible::MutateHold<T::AccountId> for Pallet<T, I> {}
214
215impl<T: Config<I>, I: 'static> fungible::InspectHold<T::AccountId> for Pallet<T, I> {
216 type Reason = T::RuntimeHoldReason;
217
218 fn total_balance_on_hold(who: &T::AccountId) -> T::Balance {
219 Self::account(who).reserved
220 }
221 fn reducible_total_balance_on_hold(who: &T::AccountId, force: Fortitude) -> Self::Balance {
222 let a = Self::account(who);
224 let unavailable = if force == Force {
225 Self::Balance::zero()
226 } else {
227 a.frozen.saturating_sub(a.free)
230 };
231 a.reserved.saturating_sub(unavailable)
232 }
233 fn balance_on_hold(reason: &Self::Reason, who: &T::AccountId) -> T::Balance {
234 Holds::<T, I>::get(who)
235 .iter()
236 .find(|x| &x.id == reason)
237 .map_or_else(Zero::zero, |x| x.amount)
238 }
239 fn hold_available(reason: &Self::Reason, who: &T::AccountId) -> bool {
240 if frame_system::Pallet::<T>::providers(who) == 0 {
241 return false
242 }
243 let holds = Holds::<T, I>::get(who);
244 if holds.is_full() && !holds.iter().any(|x| &x.id == reason) {
245 return false
246 }
247 true
248 }
249}
250
251impl<T: Config<I>, I: 'static> fungible::UnbalancedHold<T::AccountId> for Pallet<T, I> {
252 fn set_balance_on_hold(
253 reason: &Self::Reason,
254 who: &T::AccountId,
255 amount: Self::Balance,
256 ) -> DispatchResult {
257 let mut new_account = Self::account(who);
258 let mut holds = Holds::<T, I>::get(who);
259 let mut increase = true;
260 let mut delta = amount;
261
262 if let Some(item) = holds.iter_mut().find(|x| &x.id == reason) {
263 delta = item.amount.max(amount) - item.amount.min(amount);
264 increase = amount > item.amount;
265 item.amount = amount;
266 holds.retain(|x| !x.amount.is_zero());
267 } else {
268 if !amount.is_zero() {
269 holds
270 .try_push(IdAmount { id: *reason, amount })
271 .map_err(|_| Error::<T, I>::TooManyHolds)?;
272 }
273 }
274
275 new_account.reserved = if increase {
276 new_account.reserved.checked_add(&delta).ok_or(ArithmeticError::Overflow)?
277 } else {
278 new_account.reserved.checked_sub(&delta).ok_or(ArithmeticError::Underflow)?
279 };
280
281 let (result, maybe_dust) =
282 Self::try_mutate_account(who, false, |a, _| -> DispatchResult {
283 *a = new_account;
284 Ok(())
285 })?;
286 debug_assert!(
287 maybe_dust.is_none(),
288 "Does not alter main balance; dust only happens when it is altered; qed"
289 );
290 Holds::<T, I>::insert(who, holds);
291 Ok(result)
292 }
293}
294
295impl<T: Config<I>, I: 'static> fungible::InspectFreeze<T::AccountId> for Pallet<T, I> {
296 type Id = T::FreezeIdentifier;
297
298 fn balance_frozen(id: &Self::Id, who: &T::AccountId) -> Self::Balance {
299 let locks = Freezes::<T, I>::get(who);
300 locks.into_iter().find(|l| &l.id == id).map_or(Zero::zero(), |l| l.amount)
301 }
302
303 fn can_freeze(id: &Self::Id, who: &T::AccountId) -> bool {
304 let l = Freezes::<T, I>::get(who);
305 !l.is_full() || l.iter().any(|x| &x.id == id)
306 }
307}
308
309impl<T: Config<I>, I: 'static> fungible::MutateFreeze<T::AccountId> for Pallet<T, I> {
310 fn set_freeze(id: &Self::Id, who: &T::AccountId, amount: Self::Balance) -> DispatchResult {
311 if amount.is_zero() {
312 return Self::thaw(id, who)
313 }
314 let mut locks = Freezes::<T, I>::get(who);
315 if let Some(i) = locks.iter_mut().find(|x| &x.id == id) {
316 i.amount = amount;
317 } else {
318 locks
319 .try_push(IdAmount { id: *id, amount })
320 .map_err(|_| Error::<T, I>::TooManyFreezes)?;
321 }
322 Self::update_freezes(who, locks.as_bounded_slice())
323 }
324
325 fn extend_freeze(id: &Self::Id, who: &T::AccountId, amount: Self::Balance) -> DispatchResult {
326 if amount.is_zero() {
327 return Ok(())
328 }
329 let mut locks = Freezes::<T, I>::get(who);
330 if let Some(i) = locks.iter_mut().find(|x| &x.id == id) {
331 i.amount = i.amount.max(amount);
332 } else {
333 locks
334 .try_push(IdAmount { id: *id, amount })
335 .map_err(|_| Error::<T, I>::TooManyFreezes)?;
336 }
337 Self::update_freezes(who, locks.as_bounded_slice())
338 }
339
340 fn thaw(id: &Self::Id, who: &T::AccountId) -> DispatchResult {
341 let mut locks = Freezes::<T, I>::get(who);
342 locks.retain(|l| &l.id != id);
343 Self::update_freezes(who, locks.as_bounded_slice())
344 }
345}
346
347impl<T: Config<I>, I: 'static> fungible::Balanced<T::AccountId> for Pallet<T, I> {
348 type OnDropCredit = fungible::DecreaseIssuance<T::AccountId, Self>;
349 type OnDropDebt = fungible::IncreaseIssuance<T::AccountId, Self>;
350
351 fn done_deposit(who: &T::AccountId, amount: Self::Balance) {
352 Self::deposit_event(Event::<T, I>::Deposit { who: who.clone(), amount });
353 }
354 fn done_withdraw(who: &T::AccountId, amount: Self::Balance) {
355 Self::deposit_event(Event::<T, I>::Withdraw { who: who.clone(), amount });
356 }
357 fn done_issue(amount: Self::Balance) {
358 if !amount.is_zero() {
359 Self::deposit_event(Event::<T, I>::Issued { amount });
360 }
361 }
362 fn done_rescind(amount: Self::Balance) {
363 Self::deposit_event(Event::<T, I>::Rescinded { amount });
364 }
365}
366
367impl<T: Config<I>, I: 'static> fungible::BalancedHold<T::AccountId> for Pallet<T, I> {}
368
369impl<T: Config<I>, I: 'static>
370 fungible::hold::DoneSlash<T::RuntimeHoldReason, T::AccountId, T::Balance> for Pallet<T, I>
371{
372 fn done_slash(reason: &T::RuntimeHoldReason, who: &T::AccountId, amount: T::Balance) {
373 T::DoneSlashHandler::done_slash(reason, who, amount);
374 }
375}
376
377impl<T: Config<I>, I: 'static> AccountTouch<(), T::AccountId> for Pallet<T, I> {
378 type Balance = T::Balance;
379 fn deposit_required(_: ()) -> Self::Balance {
380 Self::Balance::zero()
381 }
382 fn should_touch(_: (), _: &T::AccountId) -> bool {
383 false
384 }
385 fn touch(_: (), _: &T::AccountId, _: &T::AccountId) -> DispatchResult {
386 Ok(())
387 }
388}