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
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// 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.

//! The Currency trait and associated types.

use super::{
	imbalance::{Imbalance, SignedImbalance},
	misc::{Balance, ExistenceRequirement, WithdrawReasons},
	CurrencyId,
};
use crate::{dispatch::DispatchResult, traits::Get};

use sp_runtime::{traits::MaybeSerializeDeserialize, DispatchError};
use sp_std::result;

mod reservable;
pub use reservable::{NamedReservableCurrency, ReservableCurrency};
mod lockable;
pub use lockable::{
	LockIdentifier, LockableCurrency, MultiTokenLockableCurrency, MultiTokenVestingLocks,
	MultiTokenVestingSchedule, VestingSchedule,
};

pub trait MultiTokenImbalanceWithZeroTrait<CurrencyId> {
	fn from_zero(currency_id: CurrencyId) -> Self;
}

/// Abstraction over a fungible assets system.
pub trait MultiTokenCurrency<AccountId> {
	/// The balance of an account.
	/// Mangata-node expected Balance to be u128, and uses U256 as higher precision type for arithemthics
	/// we should refactor to some HigherPrecisionType trait in those pallets eventually and remove the Into<_>
	type Balance: Balance + MaybeSerializeDeserialize + Into<u128> + TryFrom<u128>;

	type CurrencyId: CurrencyId + MaybeSerializeDeserialize;

	/// The opaque token type for an imbalance. This is returned by unbalanced
	/// operations and must be dealt with. It may be dropped but cannot be
	/// cloned.
	type PositiveImbalance: Imbalance<Self::Balance, Opposite = Self::NegativeImbalance>
		+ MultiTokenImbalanceWithZeroTrait<Self::CurrencyId>;

	/// The opaque token type for an imbalance. This is returned by unbalanced
	/// operations and must be dealt with. It may be dropped but cannot be
	/// cloned.
	type NegativeImbalance: Imbalance<Self::Balance, Opposite = Self::PositiveImbalance>
		+ MultiTokenImbalanceWithZeroTrait<Self::CurrencyId>;

	// PUBLIC IMMUTABLES

	/// The combined balance of `who`.
	fn total_balance(currency_id: Self::CurrencyId, who: &AccountId) -> Self::Balance;

	/// Same result as `slash(who, value)` (but without the side-effects)
	/// assuming there are no balance changes in the meantime and only the
	/// reserved balance is not taken into account.
	fn can_slash(currency_id: Self::CurrencyId, who: &AccountId, value: Self::Balance) -> bool;

	/// The total amount of issuance in the system.
	fn total_issuance(currency_id: Self::CurrencyId) -> Self::Balance;

	/// The minimum balance any single account may have. This is equivalent to
	/// the `Balances` module's `ExistentialDeposit`.
	fn minimum_balance(currency_id: Self::CurrencyId) -> Self::Balance;

	/// Reduce the total issuance by `amount` and return the according
	/// imbalance. The imbalance will typically be used to reduce an account by
	/// the same amount with e.g. `settle`.
	///
	/// This is infallible, but doesn't guarantee that the entire `amount` is
	/// burnt, for example in the case of underflow.
	fn burn(currency_id: Self::CurrencyId, amount: Self::Balance) -> Self::PositiveImbalance;

	/// Increase the total issuance by `amount` and return the according
	/// imbalance. The imbalance will typically be used to increase an account
	/// by the same amount with e.g. `resolve_into_existing` or
	/// `resolve_creating`.
	///
	/// This is infallible, but doesn't guarantee that the entire `amount` is
	/// issued, for example in the case of overflow.
	fn issue(currency_id: Self::CurrencyId, amount: Self::Balance) -> Self::NegativeImbalance;

	/// Produce a pair of imbalances that cancel each other out exactly.
	///
	/// This is just the same as burning and issuing the same amount and has no
	/// effect on the total issuance.
	fn pair(
		currency_id: Self::CurrencyId,
		amount: Self::Balance,
	) -> (Self::PositiveImbalance, Self::NegativeImbalance) {
		(Self::burn(currency_id, amount.clone()), Self::issue(currency_id, amount))
	}

	/// The 'free' balance of a given account.
	///
	/// This is the only balance that matters in terms of most operations on
	/// tokens. It alone is used to determine the balance when in the contract
	/// execution environment. When this balance falls below the value of
	/// `ExistentialDeposit`, then the 'current account' is
	/// deleted: specifically `FreeBalance`.
	///
	/// `system::AccountNonce` is also deleted if `ReservedBalance` is also zero
	/// (it also gets collapsed to zero if it ever becomes less than
	/// `ExistentialDeposit`.
	fn free_balance(currency_id: Self::CurrencyId, who: &AccountId) -> Self::Balance;

	/// Returns `Ok` iff the account is able to make a withdrawal of the given
	/// amount for the given reason. Basically, it's just a dry-run of
	/// `withdraw`.
	///
	/// `Err(...)` with the reason why not otherwise.
	fn ensure_can_withdraw(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		_amount: Self::Balance,
		reasons: WithdrawReasons,
		new_balance: Self::Balance,
	) -> DispatchResult;

	// PUBLIC MUTABLES (DANGEROUS)

	/// Transfer some liquid free balance to another staker.
	///
	/// This is a very high-level function. It will ensure all appropriate fees
	/// are paid and no imbalance in the system remains.
	fn transfer(
		currency_id: Self::CurrencyId,
		source: &AccountId,
		dest: &AccountId,
		value: Self::Balance,
		existence_requirement: ExistenceRequirement,
	) -> DispatchResult;

	/// Deducts up to `value` from the combined balance of `who`, preferring to
	/// deduct from the free balance. This function cannot fail.
	///
	/// The resulting imbalance is the first item of the tuple returned.
	///
	/// As much funds up to `value` will be deducted as possible. If this is
	/// less than `value`, then a non-zero second item will be returned.
	fn slash(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::Balance,
	) -> (Self::NegativeImbalance, Self::Balance);

	/// Mints `value` to the free balance of `who`.
	///
	/// If `who` doesn't exist, nothing is done and an Err returned.
	fn deposit_into_existing(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::Balance,
	) -> result::Result<Self::PositiveImbalance, DispatchError>;

	/// Similar to deposit_creating, only accepts a `NegativeImbalance` and
	/// returns nothing on success.
	fn resolve_into_existing(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::NegativeImbalance,
	) -> result::Result<(), Self::NegativeImbalance> {
		let v = value.peek();
		match Self::deposit_into_existing(currency_id, who, v) {
			Ok(opposite) => Ok(drop(value.offset(opposite))),
			_ => Err(value),
		}
	}

	/// Adds up to `value` to the free balance of `who`. If `who` doesn't exist,
	/// it is created.
	///
	/// Infallible.
	fn deposit_creating(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::Balance,
	) -> Self::PositiveImbalance;

	/// Similar to deposit_creating, only accepts a `NegativeImbalance` and
	/// returns nothing on success.
	fn resolve_creating(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::NegativeImbalance,
	) {
		let v = value.peek();
		drop(value.offset(Self::deposit_creating(currency_id, who, v)));
	}

	/// Removes some free balance from `who` account for `reason` if possible.
	/// If `liveness` is `KeepAlive`, then no less than `ExistentialDeposit`
	/// must be left remaining.
	///
	/// This checks any locks, vesting, and liquidity requirements. If the
	/// removal is not possible, then it returns `Err`.
	///
	/// If the operation is successful, this will return `Ok` with a
	/// `NegativeImbalance` whose value is `value`.
	fn withdraw(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::Balance,
		reasons: WithdrawReasons,
		liveness: ExistenceRequirement,
	) -> result::Result<Self::NegativeImbalance, DispatchError>;

	/// Similar to withdraw, only accepts a `PositiveImbalance` and returns
	/// nothing on success.
	fn settle(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		value: Self::PositiveImbalance,
		reasons: WithdrawReasons,
		liveness: ExistenceRequirement,
	) -> result::Result<(), Self::PositiveImbalance> {
		let v = value.peek();
		match Self::withdraw(currency_id, who, v, reasons, liveness) {
			Ok(opposite) => Ok(drop(value.offset(opposite))),
			_ => Err(value),
		}
	}

	/// Ensure an account's free balance equals some value; this will create the
	/// account if needed.
	///
	/// Returns a signed imbalance and status to indicate if the account was
	/// successfully updated or update has led to killing of the account.
	fn make_free_balance_be(
		currency_id: Self::CurrencyId,
		who: &AccountId,
		balance: Self::Balance,
	) -> SignedImbalance<Self::Balance, Self::PositiveImbalance>;
}

/// Abstraction over a fungible assets system.
pub trait Currency<AccountId> {
	/// The balance of an account.
	type Balance: Balance + MaybeSerializeDeserialize;

	/// The opaque token type for an imbalance. This is returned by unbalanced operations
	/// and must be dealt with. It may be dropped but cannot be cloned.
	type PositiveImbalance: Imbalance<Self::Balance, Opposite = Self::NegativeImbalance>;

	/// The opaque token type for an imbalance. This is returned by unbalanced operations
	/// and must be dealt with. It may be dropped but cannot be cloned.
	type NegativeImbalance: Imbalance<Self::Balance, Opposite = Self::PositiveImbalance>;

	// PUBLIC IMMUTABLES

	/// The combined balance of `who`.
	fn total_balance(who: &AccountId) -> Self::Balance;

	/// Same result as `slash(who, value)` (but without the side-effects) assuming there are no
	/// balance changes in the meantime and only the reserved balance is not taken into account.
	fn can_slash(who: &AccountId, value: Self::Balance) -> bool;

	/// The total amount of issuance in the system.
	fn total_issuance() -> Self::Balance;

	/// The total amount of issuance in the system excluding those which are controlled by the
	/// system.
	fn active_issuance() -> Self::Balance {
		Self::total_issuance()
	}

	/// Reduce the active issuance by some amount.
	fn deactivate(_: Self::Balance) {}

	/// Increase the active issuance by some amount, up to the outstanding amount reduced.
	fn reactivate(_: Self::Balance) {}

	/// The minimum balance any single account may have. This is equivalent to the `Balances`
	/// module's `ExistentialDeposit`.
	fn minimum_balance() -> Self::Balance;

	/// Reduce the total issuance by `amount` and return the according imbalance. The imbalance will
	/// typically be used to reduce an account by the same amount with e.g. `settle`.
	///
	/// This is infallible, but doesn't guarantee that the entire `amount` is burnt, for example
	/// in the case of underflow.
	fn burn(amount: Self::Balance) -> Self::PositiveImbalance;

	/// Increase the total issuance by `amount` and return the according imbalance. The imbalance
	/// will typically be used to increase an account by the same amount with e.g.
	/// `resolve_into_existing` or `resolve_creating`.
	///
	/// This is infallible, but doesn't guarantee that the entire `amount` is issued, for example
	/// in the case of overflow.
	fn issue(amount: Self::Balance) -> Self::NegativeImbalance;

	/// Produce a pair of imbalances that cancel each other out exactly.
	///
	/// This is just the same as burning and issuing the same amount and has no effect on the
	/// total issuance.
	fn pair(amount: Self::Balance) -> (Self::PositiveImbalance, Self::NegativeImbalance) {
		(Self::burn(amount), Self::issue(amount))
	}

	/// The 'free' balance of a given account.
	///
	/// This is the only balance that matters in terms of most operations on tokens. It alone
	/// is used to determine the balance when in the contract execution environment. When this
	/// balance falls below the value of `ExistentialDeposit`, then the 'current account' is
	/// deleted: specifically `FreeBalance`.
	///
	/// `system::AccountNonce` is also deleted if `ReservedBalance` is also zero (it also gets
	/// collapsed to zero if it ever becomes less than `ExistentialDeposit`.
	fn free_balance(who: &AccountId) -> Self::Balance;

	/// Returns `Ok` iff the account is able to make a withdrawal of the given amount
	/// for the given reason. Basically, it's just a dry-run of `withdraw`.
	///
	/// `Err(...)` with the reason why not otherwise.
	fn ensure_can_withdraw(
		who: &AccountId,
		_amount: Self::Balance,
		reasons: WithdrawReasons,
		new_balance: Self::Balance,
	) -> DispatchResult;

	// PUBLIC MUTABLES (DANGEROUS)

	/// Transfer some liquid free balance to another staker.
	///
	/// This is a very high-level function. It will ensure no imbalance in the system remains.
	fn transfer(
		source: &AccountId,
		dest: &AccountId,
		value: Self::Balance,
		existence_requirement: ExistenceRequirement,
	) -> DispatchResult;

	/// Deducts up to `value` from the combined balance of `who`, preferring to deduct from the
	/// free balance. This function cannot fail.
	///
	/// The resulting imbalance is the first item of the tuple returned.
	///
	/// As much funds up to `value` will be deducted as possible. If this is less than `value`,
	/// then a non-zero second item will be returned.
	fn slash(who: &AccountId, value: Self::Balance) -> (Self::NegativeImbalance, Self::Balance);

	/// Mints `value` to the free balance of `who`.
	///
	/// If `who` doesn't exist, nothing is done and an Err returned.
	fn deposit_into_existing(
		who: &AccountId,
		value: Self::Balance,
	) -> Result<Self::PositiveImbalance, DispatchError>;

	/// Similar to deposit_creating, only accepts a `NegativeImbalance` and returns nothing on
	/// success.
	fn resolve_into_existing(
		who: &AccountId,
		value: Self::NegativeImbalance,
	) -> Result<(), Self::NegativeImbalance> {
		let v = value.peek();
		match Self::deposit_into_existing(who, v) {
			Ok(opposite) => Ok(drop(value.offset(opposite))),
			_ => Err(value),
		}
	}

	/// Adds up to `value` to the free balance of `who`. If `who` doesn't exist, it is created.
	///
	/// Infallible.
	fn deposit_creating(who: &AccountId, value: Self::Balance) -> Self::PositiveImbalance;

	/// Similar to deposit_creating, only accepts a `NegativeImbalance` and returns nothing on
	/// success.
	fn resolve_creating(who: &AccountId, value: Self::NegativeImbalance) {
		let v = value.peek();
		drop(value.offset(Self::deposit_creating(who, v)));
	}

	/// Removes some free balance from `who` account for `reason` if possible. If `liveness` is
	/// `KeepAlive`, then no less than `ExistentialDeposit` must be left remaining.
	///
	/// This checks any locks, vesting, and liquidity requirements. If the removal is not possible,
	/// then it returns `Err`.
	///
	/// If the operation is successful, this will return `Ok` with a `NegativeImbalance` whose value
	/// is `value`.
	fn withdraw(
		who: &AccountId,
		value: Self::Balance,
		reasons: WithdrawReasons,
		liveness: ExistenceRequirement,
	) -> Result<Self::NegativeImbalance, DispatchError>;

	/// Similar to withdraw, only accepts a `PositiveImbalance` and returns nothing on success.
	fn settle(
		who: &AccountId,
		value: Self::PositiveImbalance,
		reasons: WithdrawReasons,
		liveness: ExistenceRequirement,
	) -> Result<(), Self::PositiveImbalance> {
		let v = value.peek();
		match Self::withdraw(who, v, reasons, liveness) {
			Ok(opposite) => Ok(drop(value.offset(opposite))),
			_ => Err(value),
		}
	}

	/// Ensure an account's free balance equals some value; this will create the account
	/// if needed.
	///
	/// Returns a signed imbalance and status to indicate if the account was successfully updated or
	/// update has led to killing of the account.
	fn make_free_balance_be(
		who: &AccountId,
		balance: Self::Balance,
	) -> SignedImbalance<Self::Balance, Self::PositiveImbalance>;
}

/// A non-const `Get` implementation parameterised by a `Currency` impl which provides the result
/// of `total_issuance`.
pub struct TotalIssuanceOf<C: Currency<A>, A>(sp_std::marker::PhantomData<(C, A)>);
impl<C: Currency<A>, A> Get<C::Balance> for TotalIssuanceOf<C, A> {
	fn get() -> C::Balance {
		C::total_issuance()
	}
}

/// A non-const `Get` implementation parameterised by a `Currency` impl which provides the result
/// of `active_issuance`.
pub struct ActiveIssuanceOf<C: Currency<A>, A>(sp_std::marker::PhantomData<(C, A)>);
impl<C: Currency<A>, A> Get<C::Balance> for ActiveIssuanceOf<C, A> {
	fn get() -> C::Balance {
		C::active_issuance()
	}
}

#[cfg(feature = "std")]
impl<AccountId> Currency<AccountId> for () {
	type Balance = u32;
	type PositiveImbalance = ();
	type NegativeImbalance = ();
	fn total_balance(_: &AccountId) -> Self::Balance {
		0
	}
	fn can_slash(_: &AccountId, _: Self::Balance) -> bool {
		true
	}
	fn total_issuance() -> Self::Balance {
		0
	}
	fn minimum_balance() -> Self::Balance {
		0
	}
	fn burn(_: Self::Balance) -> Self::PositiveImbalance {
		()
	}
	fn issue(_: Self::Balance) -> Self::NegativeImbalance {
		()
	}
	fn pair(_: Self::Balance) -> (Self::PositiveImbalance, Self::NegativeImbalance) {
		((), ())
	}
	fn free_balance(_: &AccountId) -> Self::Balance {
		0
	}
	fn ensure_can_withdraw(
		_: &AccountId,
		_: Self::Balance,
		_: WithdrawReasons,
		_: Self::Balance,
	) -> DispatchResult {
		Ok(())
	}
	fn transfer(
		_: &AccountId,
		_: &AccountId,
		_: Self::Balance,
		_: ExistenceRequirement,
	) -> DispatchResult {
		Ok(())
	}
	fn slash(_: &AccountId, _: Self::Balance) -> (Self::NegativeImbalance, Self::Balance) {
		((), 0)
	}
	fn deposit_into_existing(
		_: &AccountId,
		_: Self::Balance,
	) -> Result<Self::PositiveImbalance, DispatchError> {
		Ok(())
	}
	fn resolve_into_existing(
		_: &AccountId,
		_: Self::NegativeImbalance,
	) -> Result<(), Self::NegativeImbalance> {
		Ok(())
	}
	fn deposit_creating(_: &AccountId, _: Self::Balance) -> Self::PositiveImbalance {
		()
	}
	fn resolve_creating(_: &AccountId, _: Self::NegativeImbalance) {}
	fn withdraw(
		_: &AccountId,
		_: Self::Balance,
		_: WithdrawReasons,
		_: ExistenceRequirement,
	) -> Result<Self::NegativeImbalance, DispatchError> {
		Ok(())
	}
	fn settle(
		_: &AccountId,
		_: Self::PositiveImbalance,
		_: WithdrawReasons,
		_: ExistenceRequirement,
	) -> Result<(), Self::PositiveImbalance> {
		Ok(())
	}
	fn make_free_balance_be(
		_: &AccountId,
		_: Self::Balance,
	) -> SignedImbalance<Self::Balance, Self::PositiveImbalance> {
		SignedImbalance::Positive(())
	}
}