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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// Copyright 2021 Centrifuge Foundation (centrifuge.io).
//
// This file is part of the Centrifuge chain project.
// Centrifuge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version (see http://www.gnu.org/licenses).
// Centrifuge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

use cfg_traits::PreConditions;
use frame_support::{
	defensive,
	traits::{
		fungible,
		fungibles::{Dust, Inspect, InspectHold, Mutate, MutateHold, Unbalanced},
		tokens::{
			DepositConsequence, Fortitude, Precision, Preservation, Provenance, Restriction,
			WithdrawConsequence,
		},
	},
};

use super::*;

/// Represents the trait `fungibles::Inspect` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesInspectEffects<AssetId, AccountId, Balance> {
	/// A call to the `Inspect::reducible_balance()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, bool, Balance)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person whose balance should be checked.
	/// * tuple.2 = `preservation`. The preservation of the account's liveness.
	/// * tuple.3 = `fortitude`. The privilege with which a withdraw operation
	///   is conducted.
	/// * tuple.4 = `<T::Fungibles as
	///   Inspect<T::AccountId>>::reducible_balance()`. The result of the call
	///   to the not-filtered trait `fungibles::Inspect` implementation.
	ReducibleBalance(AssetId, AccountId, Preservation, Fortitude, Balance),
}

pub struct FungiblesInspectPassthrough;
impl<AssetId, AccountId, Balance>
	PreConditions<FungiblesInspectEffects<AssetId, AccountId, Balance>>
	for FungiblesInspectPassthrough
{
	type Result = Balance;

	fn check(t: FungiblesInspectEffects<AssetId, AccountId, Balance>) -> Self::Result {
		match t {
			FungiblesInspectEffects::ReducibleBalance(_, _, _, _, amount) => amount,
		}
	}
}

impl<T: Config> Inspect<T::AccountId> for Pallet<T> {
	type AssetId = T::CurrencyId;
	type Balance = T::Balance;

	fn total_issuance(asset: Self::AssetId) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::total_issuance()
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::total_issuance(asset)
		}
	}

	fn minimum_balance(asset: Self::AssetId) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::minimum_balance()
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::minimum_balance(asset)
		}
	}

	fn total_balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::total_balance(who)
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::total_balance(asset, who)
		}
	}

	fn balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::balance(who)
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::balance(asset, who)
		}
	}

	fn reducible_balance(
		asset: Self::AssetId,
		who: &T::AccountId,
		preservation: Preservation,
		force: Fortitude,
	) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::reducible_balance(who, preservation, force)
		} else {
			T::PreFungiblesInspect::check(FungiblesInspectEffects::ReducibleBalance(
				asset,
				who.clone(),
				preservation,
				force,
				<T::Fungibles as Inspect<T::AccountId>>::reducible_balance(
					asset,
					who,
					preservation,
					force,
				),
			))
		}
	}

	fn can_deposit(
		asset: Self::AssetId,
		who: &T::AccountId,
		amount: Self::Balance,
		provenance: Provenance,
	) -> DepositConsequence {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::can_deposit(who, amount, provenance)
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::can_deposit(asset, who, amount, provenance)
		}
	}

	fn can_withdraw(
		asset: Self::AssetId,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> WithdrawConsequence<Self::Balance> {
		if asset == T::NativeToken::get() {
			<Self as fungible::Inspect<T::AccountId>>::can_withdraw(who, amount)
		} else {
			<T::Fungibles as Inspect<T::AccountId>>::can_withdraw(asset, who, amount)
		}
	}

	fn asset_exists(asset: Self::AssetId) -> bool {
		<T::Fungibles as Inspect<T::AccountId>>::asset_exists(asset)
	}
}

/// Represents the trait `fungibles::InspectHold` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesInspectHoldEffects<AssetId, AccountId, Balance> {
	/// A call to the `InspectHold::can_hold()`.
	///
	/// Interpretation of tuple `(AccountId, Balance, bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person who's balance should be reserved.
	/// * tuple.2 = `amount`. The amount that should be reserved.
	/// * tuple.3 = `<T::Fungibles as InspectHold<T::AccountId>>::can_hold()`.
	///   The result of the call to the not-filtered trait
	///   `fungibles::InspectHold` implementation.
	CanHold(AssetId, AccountId, Balance, bool),
	/// A call to the `InspectHold::hold_available()`.
	///
	/// Interpretation of tuple `(AccountId, bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person whose balance should be reserved.
	/// * tuple.2 = `<T::NativeFungible as
	///   InspectHold<T::AccountId>>::hold_available()`. The result of the call
	///   to the not-filtered trait `fungible::InspectHold` implementation.
	HoldAvailable(AssetId, AccountId, bool),
}

impl<T: Config> InspectHold<T::AccountId> for Pallet<T> {
	type Reason = ();

	fn total_balance_on_hold(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::InspectHold<T::AccountId>>::total_balance_on_hold(who)
		} else {
			<T::Fungibles as InspectHold<T::AccountId>>::total_balance_on_hold(asset, who)
		}
	}

	fn reducible_total_balance_on_hold(
		asset: Self::AssetId,
		who: &T::AccountId,
		force: Fortitude,
	) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::InspectHold<T::AccountId>>::reducible_total_balance_on_hold(
				who, force,
			)
		} else {
			<T::Fungibles as InspectHold<T::AccountId>>::reducible_total_balance_on_hold(
				asset, who, force,
			)
		}
	}

	fn balance_on_hold(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		who: &T::AccountId,
	) -> Self::Balance {
		if asset == T::NativeToken::get() {
			<Self as fungible::InspectHold<T::AccountId>>::balance_on_hold(
				&HoldReason::NativeIndex.into(),
				who,
			)
		} else {
			<T::Fungibles as InspectHold<T::AccountId>>::balance_on_hold(asset, &(), who)
		}
	}

	fn hold_available(asset: Self::AssetId, _reason: &Self::Reason, who: &T::AccountId) -> bool {
		if asset == T::NativeToken::get() {
			<Self as fungible::InspectHold<T::AccountId>>::hold_available(
				&HoldReason::NativeIndex.into(),
				who,
			)
		} else {
			let hold_available =
				<T::Fungibles as InspectHold<T::AccountId>>::hold_available(asset, &(), who);

			T::PreFungiblesInspectHold::check(FungiblesInspectHoldEffects::HoldAvailable(
				asset,
				who.clone(),
				hold_available,
			)) && hold_available
		}
	}

	fn can_hold(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> bool {
		if asset == T::NativeToken::get() {
			<Self as fungible::InspectHold<T::AccountId>>::can_hold(
				&HoldReason::NativeIndex.into(),
				who,
				amount,
			)
		} else {
			let can_hold =
				<T::Fungibles as InspectHold<T::AccountId>>::can_hold(asset, &(), who, amount);

			T::PreFungiblesInspectHold::check(FungiblesInspectHoldEffects::CanHold(
				asset,
				who.clone(),
				amount,
				can_hold,
			)) && can_hold
		}
	}
}

/// Represents the trait `fungibles::Mutate` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesMutateEffects<AssetId, AccountId, Balance> {
	/// A call to the `Mutate::mint_into()`.
	///
	/// Interpretation of tuple `(AccountId, Balance, bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person who's balance should be altered.
	/// * tuple.2 = `amount`. The amount that should be minted.
	MintInto(AssetId, AccountId, Balance),

	/// A call to the `Mutate::burn_from()`.
	///
	/// Interpretation of tuple `(AccountId, Balance, bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person who's balance should be altered.
	/// * tuple.2 = `amount`. The amount that should be burned.
	BurnFrom(AssetId, AccountId, Balance),
}

impl<T: Config> Mutate<T::AccountId> for Pallet<T> {
	fn mint_into(
		asset: Self::AssetId,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> Result<Self::Balance, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::Mutate<T::AccountId>>::mint_into(who, amount)
		} else {
			ensure!(
				T::PreFungiblesMutate::check(FungiblesMutateEffects::MintInto(
					asset,
					who.clone(),
					amount
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as Mutate<T::AccountId>>::mint_into(asset, who, amount)
		}
	}

	fn burn_from(
		asset: Self::AssetId,
		who: &T::AccountId,
		amount: Self::Balance,
		precision: Precision,
		force: Fortitude,
	) -> Result<Self::Balance, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::Mutate<T::AccountId>>::burn_from(who, amount, precision, force)
		} else {
			ensure!(
				T::PreFungiblesMutate::check(FungiblesMutateEffects::BurnFrom(
					asset,
					who.clone(),
					amount
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as Mutate<T::AccountId>>::burn_from(asset, who, amount, precision, force)
		}
	}

	fn transfer(
		asset: Self::AssetId,
		source: &T::AccountId,
		dest: &T::AccountId,
		amount: Self::Balance,
		preservation: Preservation,
	) -> Result<Self::Balance, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::Mutate<T::AccountId>>::transfer(source, dest, amount, preservation)
		} else {
			ensure!(
				T::PreFungiblesTransfer::check(FungiblesTransferEffects::Transfer(
					asset,
					source.clone(),
					dest.clone(),
					amount,
					preservation != Preservation::Expendable,
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as Mutate<T::AccountId>>::transfer(
				asset,
				source,
				dest,
				amount,
				preservation,
			)
		}
	}
}

/// Represents the trait `fungibles::MutateHold` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesMutateHoldEffects<AssetId, AccountId, Balance> {
	/// A call to the `MutateHold::hold()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, Balance)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person who's balance should be altered.
	/// * tuple.2 = `amount`. The amount that should be hold.
	Hold(AssetId, AccountId, Balance),

	/// A call to the `MutateHold::release()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, Balance)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The person who's balance should be altered.
	/// * tuple.2 = `amount`. The amount that should be released.
	Release(AssetId, AccountId, Balance, bool),

	/// A call to the `MutateHold::transfer_held()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, AccountId, Balance, bool,
	/// bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `send`. The sender of the tokens.
	/// * tuple.2 = `recv`. The receiver of the tokens.
	/// * tuple.3 = `amount`. The amount that should be transferred.
	/// * tuple.4 = `on_hold`. Indicating if on_hold transfers should still be
	///   on_hold at receiver.
	/// * tuple.5 = `best_effort`. Indicating if the transfer should be done on
	///   a best effort base.
	TransferHeld(AssetId, AccountId, AccountId, Balance, bool, bool),
}

impl<T: Config> fungibles::hold::Unbalanced<T::AccountId> for Pallet<T> {
	fn set_balance_on_hold(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> sp_runtime::DispatchResult {
		if asset == T::NativeToken::get() {
			<Self as fungible::hold::Unbalanced<T::AccountId>>::set_balance_on_hold(
				&HoldReason::NativeIndex.into(),
				who,
				amount,
			)
		} else {
			ensure!(
				T::PreFungiblesMutateHold::check(FungiblesMutateHoldEffects::Hold(
					asset,
					who.clone(),
					amount
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as fungibles::hold::Unbalanced<T::AccountId>>::set_balance_on_hold(
				asset,
				&(),
				who,
				amount,
			)
		}
	}
}

impl<T: Config> MutateHold<T::AccountId> for Pallet<T> {
	fn hold(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> DispatchResult {
		if asset == T::NativeToken::get() {
			<Self as fungible::MutateHold<T::AccountId>>::hold(
				&HoldReason::NativeIndex.into(),
				who,
				amount,
			)
		} else {
			ensure!(
				T::PreFungiblesMutateHold::check(FungiblesMutateHoldEffects::Hold(
					asset,
					who.clone(),
					amount
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as MutateHold<T::AccountId>>::hold(asset, &(), who, amount)
		}
	}

	fn release(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		who: &T::AccountId,
		amount: Self::Balance,
		precision: Precision,
	) -> Result<Self::Balance, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::MutateHold<T::AccountId>>::release(
				&HoldReason::NativeIndex.into(),
				who,
				amount,
				precision,
			)
		} else {
			ensure!(
				T::PreFungiblesMutateHold::check(FungiblesMutateHoldEffects::Release(
					asset,
					who.clone(),
					amount,
					precision == Precision::BestEffort,
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as MutateHold<T::AccountId>>::release(asset, &(), who, amount, precision)
		}
	}

	fn transfer_on_hold(
		asset: Self::AssetId,
		_reason: &Self::Reason,
		source: &T::AccountId,
		dest: &T::AccountId,
		amount: Self::Balance,
		precision: Precision,
		mode: Restriction,
		force: Fortitude,
	) -> Result<Self::Balance, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::MutateHold<T::AccountId>>::transfer_on_hold(
				&HoldReason::NativeIndex.into(),
				source,
				dest,
				amount,
				precision,
				mode,
				force,
			)
		} else {
			ensure!(
				T::PreFungiblesMutateHold::check(FungiblesMutateHoldEffects::TransferHeld(
					asset,
					source.clone(),
					dest.clone(),
					amount,
					precision == Precision::BestEffort,
					mode == Restriction::OnHold,
				)),
				Error::<T>::PreConditionsNotMet
			);

			<T::Fungibles as MutateHold<T::AccountId>>::transfer_on_hold(
				asset,
				&(),
				source,
				dest,
				amount,
				precision,
				mode,
				force,
			)
		}
	}
}

/// Represents the trait `fungibles::Transfer` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesTransferEffects<AssetId, AccountId, Balance> {
	/// A call to the `Transfer::transfer()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, AccountId, Balance,
	/// bool)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `send`. The sender of the tokens.
	/// * tuple.2 = `recv`. The receiver of the tokens.
	/// * tuple.3 = `amount`. The amount that should be transferred.
	/// * tuple.4 = `keep_alice`. The lifeness requirements.
	Transfer(AssetId, AccountId, AccountId, Balance, bool),
}

/// Represents the traits `fungibles::Unbalanced` effects that are called via
/// the pallet-restricted-tokens.
pub enum FungiblesUnbalancedEffects<AssetId, AccountId, Balance> {
	/// A call to the `Unbalanced::write_balance()`.
	///
	/// Interpretation of tuple `(AssetId, AccountId, Balance)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `who`. The target account.
	/// * tuple.2 = `amount`. The amount that should be written to the target.
	WriteBalance(AssetId, AccountId, Balance),

	/// A call to the `Unbalanced::set_total_issuance()`.
	///
	/// Interpretation of tuple `(AssetId, Balance)`:
	/// * tuple.0 = `asset`. The asset that should be used.
	/// * tuple.1 = `amount`. The amount that should be set as total issuance.
	SetTotalIssuance(AssetId, Balance),
}

impl<T: Config> Unbalanced<T::AccountId> for Pallet<T> {
	fn handle_dust(_dust: Dust<T::AccountId, Self>) {
		// NOTE: Uses an always triggering `debug_assert` internally
		defensive!("DustRemoval disabled");
	}

	fn write_balance(
		asset: Self::AssetId,
		who: &T::AccountId,
		amount: Self::Balance,
	) -> Result<Option<Self::Balance>, DispatchError> {
		if asset == T::NativeToken::get() {
			<Self as fungible::Unbalanced<T::AccountId>>::write_balance(who, amount)
		} else {
			ensure!(
				T::PreFungiblesUnbalanced::check(FungiblesUnbalancedEffects::WriteBalance(
					asset,
					who.clone(),
					amount
				)),
				Error::<T>::PreConditionsNotMet
			);
			<Self as fungibles::Unbalanced<T::AccountId>>::write_balance(asset, who, amount)
		}
	}

	fn set_total_issuance(asset: Self::AssetId, amount: Self::Balance) {
		if asset == T::NativeToken::get() {
			<Self as fungible::Unbalanced<T::AccountId>>::set_total_issuance(amount)
		} else if T::PreFungiblesUnbalanced::check(FungiblesUnbalancedEffects::SetTotalIssuance(
			asset, amount,
		)) {
			<Self as fungibles::Unbalanced<T::AccountId>>::set_total_issuance(asset, amount)
		}
	}
}