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
// Copyright 2021 Centrifuge GmbH (centrifuge.io).
// This file is part of 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.

//! # A common trait lib for centrifuge
//!
//! This crate provides some common traits used by centrifuge.

// Ensure we're `no_std` when compiling for WebAssembly.
#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{
	dispatch::{Codec, DispatchResult, DispatchResultWithPostInfo},
	scale_info::TypeInfo,
	traits::UnixTime,
	Parameter, RuntimeDebug,
};
use impl_trait_for_tuples::impl_for_tuples;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use sp_runtime::{
	traits::{
		AtLeast32BitUnsigned, Bounded, Get, MaybeDisplay, MaybeSerialize,
		MaybeSerializeDeserialize, Member, Zero,
	},
	DispatchError,
};
use sp_std::{fmt::Debug, hash::Hash, marker::PhantomData, str::FromStr, vec::Vec};

/// Traits related to checked changes.
pub mod changes;
/// Traits related to data registry and collection.
pub mod data;
/// Traits related to Ethereum/EVM.
pub mod ethereum;
/// Traits related to pool fees.
pub mod fee;
/// Traits related to fees payment.
pub mod fees;
/// Traits related to interest rates.
pub mod interest;
/// Traits related to investments.
pub mod investments;
/// Traits related to liquidity pools.
pub mod liquidity_pools;
/// Traits related to rewards.
pub mod rewards;
/// Traits related to swaps.
pub mod swaps;

#[cfg(feature = "runtime-benchmarks")]
/// Traits related to benchmarking tooling.
pub mod benchmarking;

/// A trait used for loosely coupling the claim pallet with a reward mechanism.
///
/// ## Overview
/// The crowdloan reward mechanism is separated from the crowdloan claiming
/// process, the latter being generic, acting as a kind of proxy to the
/// rewarding mechanism, that is specific to to each crowdloan campaign. The aim
/// of this pallet is to ensure that a claim for a reward payout is well-formed,
/// checking for replay attacks, spams or invalid claim (e.g. unknown
/// contributor, exceeding reward amount, ...).
/// See the [`crowdloan-reward`] pallet, that implements a reward mechanism with
/// vesting, for instance.
pub trait Reward {
	/// The account from the parachain, that the claimer provided in her/his
	/// transaction.
	type ParachainAccountId: Debug
		+ MaybeSerialize
		+ MaybeSerializeDeserialize
		+ Member
		+ Ord
		+ Parameter
		+ TypeInfo;

	/// The contribution amount in relay chain tokens.
	type ContributionAmount: AtLeast32BitUnsigned
		+ Codec
		+ Copy
		+ Debug
		+ Default
		+ MaybeSerializeDeserialize
		+ Member
		+ Parameter
		+ Zero
		+ TypeInfo;

	/// Block number type used by the runtime
	type BlockNumber: AtLeast32BitUnsigned
		+ Bounded
		+ Copy
		+ Debug
		+ Default
		+ FromStr
		+ Hash
		+ MaybeDisplay
		+ MaybeSerializeDeserialize
		+ Member
		+ Parameter
		+ TypeInfo;

	/// Rewarding function that is invoked from the claim pallet.
	///
	/// If this function returns successfully, any subsequent claim of the same
	/// claimer will be rejected by the claim module.
	fn reward(
		who: Self::ParachainAccountId,
		contribution: Self::ContributionAmount,
	) -> DispatchResultWithPostInfo;
}

/// A trait that can be used to fetch the nav and update nav for a given pool
pub trait PoolNAV<PoolId, Amount> {
	type ClassId;
	type RuntimeOrigin;
	// nav returns the nav and the last time it was calculated
	fn nav(pool_id: PoolId) -> Option<(Amount, u64)>;
	fn update_nav(pool_id: PoolId) -> Result<Amount, DispatchError>;
	fn initialise(
		origin: Self::RuntimeOrigin,
		pool_id: PoolId,
		class_id: Self::ClassId,
	) -> DispatchResult;
}

/// A trait that support pool inspection operations such as pool existence
/// checks and pool admin of permission set.
pub trait PoolInspect<AccountId, CurrencyId> {
	type PoolId;
	type TrancheId;
	type Moment;

	/// Check if the pool exists
	fn pool_exists(pool_id: Self::PoolId) -> bool;

	/// Check if the tranche exists for the given pool
	fn tranche_exists(pool_id: Self::PoolId, tranche_id: Self::TrancheId) -> bool;

	/// Get the account used for the given `pool_id`.
	fn account_for(pool_id: Self::PoolId) -> AccountId;

	/// Get the currency used for the given `pool_id`.
	fn currency_for(pool_id: Self::PoolId) -> Option<CurrencyId>;
}

/// Get the latest price for a given tranche token
pub trait TrancheTokenPrice<AccountId, CurrencyId> {
	type PoolId;
	type TrancheId;
	type BalanceRatio;
	type Moment;

	fn get(
		pool_id: Self::PoolId,
		tranche_id: Self::TrancheId,
	) -> Option<PriceValue<CurrencyId, Self::BalanceRatio, Self::Moment>>;
}

/// Variants for valid Pool updates to send out as events
#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub enum UpdateState {
	NoExecution,
	Executed(u32),
	Stored(u32),
}

/// A trait that supports modifications of pools
pub trait PoolMutate<AccountId, PoolId> {
	type Balance;
	type CurrencyId;
	type MaxTokenNameLength: Get<u32>;
	type MaxTokenSymbolLength: Get<u32>;
	type MaxTranches: Get<u32>;
	type TrancheInput: Encode + Decode + Clone + TypeInfo + Debug + PartialEq;
	type PoolChanges: Encode + Decode + Clone + TypeInfo + Debug + PartialEq + MaxEncodedLen;
	type PoolFeeInput: Encode + Decode + Clone + TypeInfo + Debug;

	fn create(
		admin: AccountId,
		depositor: AccountId,
		pool_id: PoolId,
		tranche_inputs: Vec<Self::TrancheInput>,
		currency: Self::CurrencyId,
		max_reserve: Self::Balance,
		pool_fees: Vec<Self::PoolFeeInput>,
	) -> DispatchResult;

	fn update(pool_id: PoolId, changes: Self::PoolChanges) -> Result<UpdateState, DispatchError>;

	fn execute_update(pool_id: PoolId) -> Result<u32, DispatchError>;
}

/// A trait that supports retrieval and mutation of pool and tranche token
/// metadata.
pub trait PoolMetadata<Balance, VersionedMultiLocation> {
	type AssetMetadata;
	type CustomMetadata;
	type PoolMetadata;
	type PoolId: Parameter
		+ Member
		+ Debug
		+ Copy
		+ Default
		+ TypeInfo
		+ Encode
		+ Decode
		+ MaxEncodedLen;
	type TrancheId: Parameter + Member + Debug + Copy + Default + TypeInfo + MaxEncodedLen;

	/// Get the metadata of the given pool.
	fn get_pool_metadata(pool_id: Self::PoolId) -> Result<Self::PoolMetadata, DispatchError>;

	/// Set the metadata of the given pool.
	fn set_pool_metadata(pool_id: Self::PoolId, metadata: Vec<u8>) -> DispatchResult;

	/// Get the metadata of the given pair of pool and tranche id.
	fn get_tranche_token_metadata(
		pool_id: Self::PoolId,
		tranche: Self::TrancheId,
	) -> Result<Self::AssetMetadata, DispatchError>;

	/// Register the metadata for the currency derived from the given pair of
	/// pool id and tranche.
	fn create_tranche_token_metadata(
		pool_id: Self::PoolId,
		tranche: Self::TrancheId,
		metadata: Self::AssetMetadata,
	) -> DispatchResult;

	#[allow(clippy::too_many_arguments)]
	/// Update the metadata of the given pair of pool and tranche id.
	fn update_tranche_token_metadata(
		pool_id: Self::PoolId,
		tranche: Self::TrancheId,
		decimals: Option<u32>,
		name: Option<Vec<u8>>,
		symbol: Option<Vec<u8>>,
		existential_deposit: Option<Balance>,
		location: Option<Option<VersionedMultiLocation>>,
		additional: Option<Self::CustomMetadata>,
	) -> DispatchResult;
}

/// A trait that support pool reserve operations such as withdraw and deposit
pub trait PoolReserve<AccountId, CurrencyId>: PoolInspect<AccountId, CurrencyId> {
	type Balance;

	/// Withdraw `amount` from the reserve to the `to` account.
	fn withdraw(pool_id: Self::PoolId, to: AccountId, amount: Self::Balance) -> DispatchResult;

	/// Deposit `amount` from the `from` account into the reserve.
	fn deposit(pool_id: Self::PoolId, from: AccountId, amount: Self::Balance) -> DispatchResult;
}

/// A trait that supports modifications of pool write-off policies
pub trait PoolWriteOffPolicyMutate<PoolId> {
	type Policy: Parameter;

	/// Updates the policy with the new policy
	fn update(pool_id: PoolId, policy: Self::Policy) -> DispatchResult;

	#[cfg(feature = "runtime-benchmarks")]
	fn worst_case_policy() -> Self::Policy;
}

/// A trait that can be used to retrieve the current price for a currency
pub struct CurrencyPair<CurrencyId> {
	pub base: CurrencyId,
	pub quote: CurrencyId,
}

pub struct PriceValue<CurrencyId, Rate, Moment> {
	pub pair: CurrencyPair<CurrencyId>,
	pub price: Rate,
	pub last_updated: Moment,
}

pub trait CurrencyPrice<CurrencyId> {
	type Rate;
	type Moment;

	/// Retrieve the latest price of `base` currency, denominated in the `quote`
	/// currency If `quote` currency is not passed, then the default `quote`
	/// currency is used (when possible)
	fn get_latest(
		base: CurrencyId,
		quote: Option<CurrencyId>,
	) -> Option<PriceValue<CurrencyId, Self::Rate, Self::Moment>>;
}

pub trait Permissions<AccountId> {
	type Scope;
	type Role;
	type Error: Debug;
	type Ok: Debug;

	fn has(scope: Self::Scope, who: AccountId, role: Self::Role) -> bool;

	fn add(scope: Self::Scope, who: AccountId, role: Self::Role) -> Result<Self::Ok, Self::Error>;

	fn remove(
		scope: Self::Scope,
		who: AccountId,
		role: Self::Role,
	) -> Result<Self::Ok, Self::Error>;
}

pub trait Properties {
	type Property;
	type Error;
	type Ok;

	fn exists(&self, property: Self::Property) -> bool;

	fn empty(&self) -> bool;

	fn rm(&mut self, property: Self::Property) -> Result<Self::Ok, Self::Error>;

	fn add(&mut self, property: Self::Property) -> Result<Self::Ok, Self::Error>;
}

pub trait PoolUpdateGuard {
	type PoolDetails;
	type ScheduledUpdateDetails;
	type Moment: Copy;

	fn released(
		pool: &Self::PoolDetails,
		update: &Self::ScheduledUpdateDetails,
		now: Self::Moment,
	) -> bool;
}

pub trait PreConditions<T> {
	type Result;

	fn check(t: T) -> Self::Result;

	/// Perform the required changes to satisfy the `check()` method in a
	/// successful way
	#[cfg(feature = "runtime-benchmarks")]
	fn satisfy(_t: T) {}
}

#[impl_for_tuples(1, 10)]
#[tuple_types_custom_trait_bound(PreConditions<T, Result = bool>)]
#[allow(clippy::redundant_clone)]
impl<T> PreConditions<T> for Tuple
where
	T: Clone,
{
	type Result = bool;

	fn check(t: T) -> Self::Result {
		for_tuples!( #( <Tuple as PreConditions::<T>>::check(t.clone()) )&* )
	}
}

#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct Always;
impl<T> PreConditions<T> for Always {
	type Result = bool;

	fn check(_t: T) -> bool {
		true
	}
}

#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct Never;
impl<T> PreConditions<T> for Never {
	type Result = bool;

	fn check(_t: T) -> bool {
		false
	}
}

/// Trait to determine whether a sending account and currency have a
/// restriction, and if so is there an allowance for the receiver location.
pub trait TransferAllowance<AccountId> {
	type CurrencyId;
	type Location: Member + Debug + Eq + PartialEq + TypeInfo + Encode + Decode + MaxEncodedLen;
	/// Determines whether the `send` account is allowed to make a transfer to
	/// the `receive` location with `currency` type currency. Returns result
	/// wrapped bool for whether allowance is allowed.
	fn allowance(
		send: AccountId,
		receive: Self::Location,
		currency: Self::CurrencyId,
	) -> Result<Option<Self::Location>, DispatchError>;
}

/// Trait to retrieve information about currencies.
pub trait CurrencyInspect {
	type CurrencyId;

	/// Checks whether the provided currency is a tranche token.
	fn is_tranche_token(currency: Self::CurrencyId) -> bool;
}

/// Trait to transmit a change of status for anything uniquely identifiable.
///
/// NOTE: The main use case to handle asynchronous operations.
pub trait StatusNotificationHook {
	/// The identifying type
	type Id;
	/// The type for possible states
	type Status;
	/// The error type
	type Error: Debug;

	/// Notify that the status has changed for the given id
	fn notify_status_change(id: Self::Id, status: Self::Status) -> Result<(), Self::Error>;
}

/// Trait to signal an epoch transition.
pub trait EpochTransitionHook {
	type Balance;
	type PoolId;
	type Time;
	type Error;

	/// Hook into the closing of an epoch
	fn on_closing_mutate_reserve(
		pool_id: Self::PoolId,
		assets_under_management: Self::Balance,
		reserve: &mut Self::Balance,
	) -> Result<(), Self::Error>;

	/// Hook into the execution of an epoch before any investment and
	/// redemption fulfillments
	fn on_execution_pre_fulfillments(pool_id: Self::PoolId) -> Result<(), Self::Error>;
}

/// Trait to synchronously provide a currency conversion estimation for foreign
/// currencies into/from pool currencies.
pub trait IdentityCurrencyConversion {
	type Balance;
	type Currency;
	type Error;

	/// Estimate the worth of an outgoing currency amount in the incoming
	/// currency.
	///
	/// NOTE: At least applies decimal conversion if both currencies mismatch.
	fn stable_to_stable(
		currency_in: Self::Currency,
		currency_out: Self::Currency,
		amount_out: Self::Balance,
	) -> Result<Self::Balance, Self::Error>;
}

/// A trait for trying to convert between two types.
// TODO: Remove usage for the one from sp_runtime::traits once we are on
// the same Polkadot version
pub trait TryConvert<A, B> {
	type Error;

	/// Attempt to make conversion. If returning [Result::Err], the inner must
	/// always be `a`.
	fn try_convert(a: A) -> Result<B, Self::Error>;
}

/// Converts a balance value into an asset balance.
// TODO: Remove usage for the one from frame_support::traits::tokens once we are
// on the same Polkadot version
pub trait ConversionToAssetBalance<InBalance, AssetId, AssetBalance> {
	fn to_asset_balance(
		balance: InBalance,
		asset_id: AssetId,
	) -> Result<AssetBalance, DispatchError>;
}

/// Converts an asset balance value into balance.
// TODO: Remove usage for the one from frame_support::traits::tokens once we are
// on the same Polkadot version
pub trait ConversionFromAssetBalance<AssetBalance, AssetId, OutBalance> {
	type Error;
	fn from_asset_balance(
		balance: AssetBalance,
		asset_id: AssetId,
	) -> Result<OutBalance, Self::Error>;
}

// TODO: Probably these should be in a future cfg-utils.
// Issue: https://github.com/centrifuge/centrifuge-chain/issues/1380

/// Type to represent milliseconds
pub type Millis = u64;

/// Type to represent seconds
pub type Seconds = u64;

/// Trait to obtain the time as seconds
pub trait TimeAsSecs: UnixTime {
	fn now() -> Seconds {
		<Self as UnixTime>::now().as_secs()
	}
}

impl<T: UnixTime> TimeAsSecs for T {}

/// Trait to convert into seconds
pub trait IntoSeconds {
	fn into_seconds(self) -> Seconds;
}

impl IntoSeconds for Millis {
	fn into_seconds(self) -> Seconds {
		self / 1000
	}
}

pub trait ValueProvider<Source, Key> {
	type Value;

	fn get(source: &Source, id: &Key) -> Result<Option<Self::Value>, DispatchError>;

	#[cfg(feature = "runtime-benchmarks")]
	fn set(_source: &Source, _key: &Key, _value: Self::Value) {}
}

/// A provider that never returns a value
pub struct NoProvider<Value>(PhantomData<Value>);
impl<Source, Key, Value> ValueProvider<Source, Key> for NoProvider<Value> {
	type Value = Value;

	fn get(_: &Source, _: &Key) -> Result<Option<Self::Value>, DispatchError> {
		Err(DispatchError::Other("No value"))
	}
}

/// Checks whether an asset is the local representation of another one
pub trait HasLocalAssetRepresentation<AssetRegistry> {
	fn is_local_representation_of(&self, variant_currency: &Self) -> Result<bool, DispatchError>;
}