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

// Copyright (C) 2020-2022  Intergalactic, Limited (GIB).
// 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.

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![allow(clippy::upper_case_acronyms)]

#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;

pub mod weights;

use frame_support::{dispatch::DispatchResult, ensure, traits::Contains, traits::Get};

use orml_traits::{
	arithmetic::{Signed, SimpleArithmetic},
	GetByKey, MultiCurrency, MultiCurrencyExtended,
};

use frame_system::ensure_signed;

use sp_std::convert::{TryFrom, TryInto};

// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use crate::weights::WeightInfo;
	use frame_support::pallet_prelude::*;
	use frame_support::sp_runtime::traits::AtLeast32BitUnsigned;
	use frame_system::pallet_prelude::{BlockNumberFor, OriginFor};

	#[pallet::pallet]
	#[pallet::without_storage_info]
	pub struct Pallet<T>(_);

	#[pallet::storage]
	#[pallet::getter(fn blacklisted)]
	/// Accounts excluded from dusting.
	pub type AccountBlacklist<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, (), OptionQuery>;

	#[pallet::storage]
	#[pallet::getter(fn reward_account)]
	/// Account to take reward from.
	pub type RewardAccount<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;

	#[pallet::storage]
	#[pallet::getter(fn dust_dest_account)]
	/// Account to send dust to.
	pub type DustAccount<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

	#[pallet::config]
	pub trait Config: frame_system::Config {
		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;

		/// Balance type
		type Balance: Parameter
			+ Member
			+ AtLeast32BitUnsigned
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize
			+ MaxEncodedLen;

		/// The amount type, should be signed version of `Balance`
		type Amount: Signed
			+ TryInto<Self::Balance>
			+ TryFrom<Self::Balance>
			+ Parameter
			+ Member
			+ SimpleArithmetic
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize;

		/// Asset type
		type CurrencyId: Parameter + Member + Copy + MaybeSerializeDeserialize + Ord;

		/// Currency for transfers
		type MultiCurrency: MultiCurrencyExtended<
			Self::AccountId,
			CurrencyId = Self::CurrencyId,
			Balance = Self::Balance,
			Amount = Self::Amount,
		>;

		/// The minimum amount required to keep an account.
		type MinCurrencyDeposits: GetByKey<Self::CurrencyId, Self::Balance>;

		/// Reward amount
		#[pallet::constant]
		type Reward: Get<Self::Balance>;

		/// Native Asset Id
		#[pallet::constant]
		type NativeCurrencyId: Get<Self::CurrencyId>;

		/// The origin which can manage whiltelist.
		type BlacklistUpdateOrigin: EnsureOrigin<Self::Origin>;

		/// Weight information for extrinsics in this module.
		type WeightInfo: WeightInfo;
	}

	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config> {
		pub account_blacklist: Vec<T::AccountId>,
		pub reward_account: Option<T::AccountId>,
		pub dust_account: Option<T::AccountId>,
	}

	#[cfg(feature = "std")]
	impl<T: Config> Default for GenesisConfig<T> {
		fn default() -> Self {
			GenesisConfig {
				account_blacklist: vec![],
				reward_account: None,
				dust_account: None,
			}
		}
	}

	#[pallet::genesis_build]
	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
		fn build(&self) {
			self.account_blacklist.iter().for_each(|account_id| {
				AccountBlacklist::<T>::insert(account_id, ());
			});

			if self.reward_account.is_none() {
				panic!("Reward account is not set in genesis config");
			}

			if self.dust_account.is_none() {
				panic!("Dust account is not set in genesis config");
			}

			RewardAccount::<T>::put(
				&self
					.reward_account
					.clone()
					.expect("Reward account is not set in genesis config"),
			);
			DustAccount::<T>::put(
				&self
					.dust_account
					.clone()
					.expect("Dust account is not set in genesis config"),
			);
		}
	}

	#[pallet::error]
	pub enum Error<T> {
		/// Account is excluded from dusting.
		AccountBlacklisted,

		/// Account is not present in the non-dustable list.
		AccountNotBlacklisted,

		/// The balance is zero.
		ZeroBalance,

		/// The balance is sufficient to keep account open.
		BalanceSufficient,

		/// Dust account is not set.
		DustAccountNotSet,

		/// Reserve account is not set.
		ReserveAccountNotSet,
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
	pub enum Event<T: Config> {
		/// Account dusted.
		Dusted { who: T::AccountId, amount: T::Balance },

		/// Account added to non-dustable list.
		Added { who: T::AccountId },

		/// Account removed from non-dustable list.
		Removed { who: T::AccountId },
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Dust specified account.
		/// IF account balance is < min. existential deposit of given currency, and account is allowed to
		/// be dusted, the remaining balance is transferred to selected account (usually treasury).
		///
		/// Caller is rewarded with chosen reward in native currency.
		#[pallet::weight((<T as Config>::WeightInfo::dust_account(), DispatchClass::Normal, Pays::Yes))]
		pub fn dust_account(origin: OriginFor<T>, account: T::AccountId, currency_id: T::CurrencyId) -> DispatchResult {
			let who = ensure_signed(origin)?;

			ensure!(Self::blacklisted(&account).is_none(), Error::<T>::AccountBlacklisted);

			let (dustable, dust) = Self::is_dustable(&account, currency_id);

			ensure!(dust != T::Balance::from(0u32), Error::<T>::ZeroBalance);

			ensure!(dustable, Error::<T>::BalanceSufficient);

			// Error should never occur here
			let dust_dest_account = Self::dust_dest_account().ok_or(Error::<T>::DustAccountNotSet)?;

			Self::transfer_dust(&account, &dust_dest_account, currency_id, dust)?;

			Self::deposit_event(Event::Dusted {
				who: account,
				amount: dust,
			});

			// Ignore the result, it fails - no problem.
			let _ = Self::reward_duster(&who, currency_id, dust);

			Ok(())
		}

		/// Add account to list of non-dustable account. Account whihc are excluded from udsting.
		/// If such account should be dusted - `AccountBlacklisted` error is returned.
		/// Only root can perform this action.
		#[pallet::weight((<T as Config>::WeightInfo::add_nondustable_account(), DispatchClass::Normal, Pays::No))]
		pub fn add_nondustable_account(origin: OriginFor<T>, account: T::AccountId) -> DispatchResult {
			T::BlacklistUpdateOrigin::ensure_origin(origin)?;

			AccountBlacklist::<T>::insert(&account, ());

			Self::deposit_event(Event::Added { who: account });

			Ok(())
		}

		/// Remove account from list of non-dustable accounts. That means account can be dusted again.
		#[pallet::weight((<T as Config>::WeightInfo::remove_nondustable_account(), DispatchClass::Normal, Pays::No))]
		pub fn remove_nondustable_account(origin: OriginFor<T>, account: T::AccountId) -> DispatchResult {
			T::BlacklistUpdateOrigin::ensure_origin(origin)?;

			AccountBlacklist::<T>::mutate(&account, |maybe_account| -> DispatchResult {
				ensure!(!maybe_account.is_none(), Error::<T>::AccountNotBlacklisted);

				*maybe_account = None;

				Ok(())
			})?;

			Self::deposit_event(Event::Removed { who: account });

			Ok(())
		}
	}
}
impl<T: Config> Pallet<T> {
	/// Check is account's balance is below minimum deposit.
	fn is_dustable(account: &T::AccountId, currency_id: T::CurrencyId) -> (bool, T::Balance) {
		let ed = T::MinCurrencyDeposits::get(&currency_id);

		let total = T::MultiCurrency::total_balance(currency_id, account);

		(total < ed, total)
	}

	/// Send reward to account which did the dusting.
	fn reward_duster(_duster: &T::AccountId, _currency_id: T::CurrencyId, _dust: T::Balance) -> DispatchResult {
		// Error should never occur here
		let reserve_account = Self::reward_account().ok_or(Error::<T>::ReserveAccountNotSet)?;
		let reward = T::Reward::get();

		T::MultiCurrency::transfer(T::NativeCurrencyId::get(), &reserve_account, _duster, reward)?;

		Ok(())
	}

	/// Transfer dust amount to selected DustAccount ( usually treasury)
	fn transfer_dust(
		from: &T::AccountId,
		dest: &T::AccountId,
		currency_id: T::CurrencyId,
		dust: T::Balance,
	) -> DispatchResult {
		T::MultiCurrency::transfer(currency_id, from, dest, dust)
	}
}

use orml_traits::OnDust;

use sp_std::marker::PhantomData;
pub struct DusterWhitelist<T>(PhantomData<T>);

impl<T: Config> OnDust<T::AccountId, T::CurrencyId, T::Balance> for Pallet<T> {
	fn on_dust(who: &T::AccountId, currency_id: T::CurrencyId, amount: T::Balance) {
		if let Some(dust_dest_account) = Self::dust_dest_account() {
			let _ = Self::transfer_dust(who, &dust_dest_account, currency_id, amount);
		}
	}
}

impl<T: Config> Contains<T::AccountId> for DusterWhitelist<T> {
	fn contains(t: &T::AccountId) -> bool {
		AccountBlacklist::<T>::contains_key(t)
	}
}

use frame_support::sp_runtime::DispatchError;
use hydradx_traits::pools::DustRemovalAccountWhitelist;

impl<T: Config> DustRemovalAccountWhitelist<T::AccountId> for Pallet<T> {
	type Error = DispatchError;

	fn add_account(account: &T::AccountId) -> Result<(), Self::Error> {
		AccountBlacklist::<T>::insert(account, ());
		Ok(())
	}

	fn remove_account(account: &T::AccountId) -> Result<(), Self::Error> {
		AccountBlacklist::<T>::mutate(account, |maybe_account| -> Result<(), DispatchError> {
			ensure!(!maybe_account.is_none(), Error::<T>::AccountNotBlacklisted);

			*maybe_account = None;

			Ok(())
		})
	}
}