purchase.rs 35.3 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Substrate 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.

// Substrate 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.

// You should have received a copy of the GNU General Public License
// along with Substrate.  If not, see <http://www.gnu.org/licenses/>.

17
//! Pallet to process purchase of DOTs.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
18

Shawn Tabrizi's avatar
Shawn Tabrizi committed
19
20
21
use frame_support::{
	pallet_prelude::*,
	traits::{Currency, EnsureOrigin, ExistenceRequirement, Get, VestingSchedule},
Shawn Tabrizi's avatar
Shawn Tabrizi committed
22
};
23
use frame_system::pallet_prelude::*;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
24
25
pub use pallet::*;
use parity_scale_codec::{Decode, Encode};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
26
use sp_core::sr25519;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
27
28
29
30
use sp_runtime::{
	traits::{CheckedAdd, Saturating, Verify, Zero},
	AnySignature, DispatchError, DispatchResult, Permill, RuntimeDebug,
};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
31
32
use sp_std::prelude::*;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
33
34
type BalanceOf<T> =
	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
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

/// The kind of a statement an account needs to make for a claim to be valid.
#[derive(Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug)]
pub enum AccountValidity {
	/// Account is not valid.
	Invalid,
	/// Account has initiated the account creation process.
	Initiated,
	/// Account is pending validation.
	Pending,
	/// Account is valid with a low contribution amount.
	ValidLow,
	/// Account is valid with a high contribution amount.
	ValidHigh,
	/// Account has completed the purchase process.
	Completed,
}

impl Default for AccountValidity {
	fn default() -> Self {
		AccountValidity::Invalid
	}
}

impl AccountValidity {
	fn is_valid(&self) -> bool {
		match self {
			Self::Invalid => false,
			Self::Initiated => false,
			Self::Pending => false,
			Self::ValidLow => true,
			Self::ValidHigh => true,
			Self::Completed => false,
		}
	}
}

/// All information about an account regarding the purchase of DOTs.
#[derive(Encode, Decode, Default, Clone, Eq, PartialEq, RuntimeDebug)]
pub struct AccountStatus<Balance> {
	/// The current validity status of the user. Will denote if the user has passed KYC,
	/// how much they are able to purchase, and when their purchase process has completed.
	validity: AccountValidity,
	/// The amount of free DOTs they have purchased.
	free_balance: Balance,
	/// The amount of locked DOTs they have purchased.
	locked_balance: Balance,
	/// Their sr25519/ed25519 signature verifying they have signed our required statement.
	signature: Vec<u8>,
	/// The percentage of VAT the purchaser is responsible for. This is already factored into account balance.
	vat: Permill,
}

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#[frame_support::pallet]
pub mod pallet {
	use super::*;

	#[pallet::pallet]
	#[pallet::generate_store(pub(super) trait Store)]
	pub struct Pallet<T>(_);

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

		/// Balances Pallet
		type Currency: Currency<Self::AccountId>;

		/// Vesting Pallet
Shawn Tabrizi's avatar
Shawn Tabrizi committed
105
106
107
108
109
		type VestingSchedule: VestingSchedule<
			Self::AccountId,
			Moment = Self::BlockNumber,
			Currency = Self::Currency,
		>;
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

		/// The origin allowed to set account status.
		type ValidityOrigin: EnsureOrigin<Self::Origin>;

		/// The origin allowed to make configurations to the pallet.
		type ConfigurationOrigin: EnsureOrigin<Self::Origin>;

		/// The maximum statement length for the statement users to sign when creating an account.
		#[pallet::constant]
		type MaxStatementLength: Get<u32>;

		/// The amount of purchased locked DOTs that we will unlock for basic actions on the chain.
		#[pallet::constant]
		type UnlockedProportion: Get<Permill>;

		/// The maximum amount of locked DOTs that we will unlock.
		#[pallet::constant]
		type MaxUnlocked: Get<BalanceOf<Self>>;
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	#[pallet::metadata(
		T::AccountId = "AccountId",
		T::BlockNumber = "BlockNumber",
		BalanceOf<T> = "Balance",
	)]
	pub enum Event<T: Config> {
138
		/// A [new] account was created.
139
		AccountCreated(T::AccountId),
140
		/// Someone's account validity was updated. [who, validity]
141
		ValidityUpdated(T::AccountId, AccountValidity),
142
		/// Someone's purchase balance was updated. [who, free, locked]
143
		BalanceUpdated(T::AccountId, BalanceOf<T>, BalanceOf<T>),
144
		/// A payout was made to a purchaser. [who, free, locked]
145
		PaymentComplete(T::AccountId, BalanceOf<T>, BalanceOf<T>),
146
		/// A new payment account was set. [who]
147
		PaymentAccountSet(T::AccountId),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
148
149
		/// A new statement was set.
		StatementUpdated,
Denis_P's avatar
Denis_P committed
150
		/// A new statement was set. `[block_number]`
151
		UnlockBlockUpdated(T::BlockNumber),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
152
153
	}

154
155
	#[pallet::error]
	pub enum Error<T> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
		/// Account is not currently valid to use.
		InvalidAccount,
		/// Account used in the purchase already exists.
		ExistingAccount,
		/// Provided signature is invalid
		InvalidSignature,
		/// Account has already completed the purchase process.
		AlreadyCompleted,
		/// An overflow occurred when doing calculations.
		Overflow,
		/// The statement is too long to be stored on chain.
		InvalidStatement,
		/// The unlock block is in the past!
		InvalidUnlockBlock,
		/// Vesting schedule already exists for this account.
		VestingScheduleExists,
	}

174
175
	// A map of all participants in the DOT purchase process.
	#[pallet::storage]
Shawn Tabrizi's avatar
Shawn Tabrizi committed
176
177
	pub(super) type Accounts<T: Config> =
		StorageMap<_, Blake2_128Concat, T::AccountId, AccountStatus<BalanceOf<T>>, ValueQuery>;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
178

179
180
181
	// The account that will be used to payout participants of the DOT purchase process.
	#[pallet::storage]
	pub(super) type PaymentAccount<T: Config> = StorageValue<_, T::AccountId, ValueQuery>;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
182

183
184
185
186
187
188
189
	// The statement purchasers will need to sign to participate.
	#[pallet::storage]
	pub(super) type Statement<T> = StorageValue<_, Vec<u8>, ValueQuery>;

	// The block where all locked dots will unlock.
	#[pallet::storage]
	pub(super) type UnlockBlock<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
190

191
192
	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
193

194
195
	#[pallet::call]
	impl<T: Config> Pallet<T> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
196
197
198
199
200
		/// Create a new account. Proof of existence through a valid signed message.
		///
		/// We check that the account does not exist at this stage.
		///
		/// Origin must match the `ValidityOrigin`.
201
		#[pallet::weight(200_000_000 + T::DbWeight::get().reads_writes(4, 1))]
202
		pub fn create_account(
203
			origin: OriginFor<T>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
204
			who: T::AccountId,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
205
			signature: Vec<u8>,
206
		) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
207
208
209
210
			T::ValidityOrigin::ensure_origin(origin)?;
			// Account is already being tracked by the pallet.
			ensure!(!Accounts::<T>::contains_key(&who), Error::<T>::ExistingAccount);
			// Account should not have a vesting schedule.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
211
212
213
214
			ensure!(
				T::VestingSchedule::vesting_balance(&who).is_none(),
				Error::<T>::VestingScheduleExists
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
215
216
217
218
219
220
221
222
223
224
225
226
227

			// Verify the signature provided is valid for the statement.
			Self::verify_signature(&who, &signature)?;

			// Create a new pending account.
			let status = AccountStatus {
				validity: AccountValidity::Initiated,
				signature,
				free_balance: Zero::zero(),
				locked_balance: Zero::zero(),
				vat: Permill::zero(),
			};
			Accounts::<T>::insert(&who, status);
228
229
			Self::deposit_event(Event::<T>::AccountCreated(who));
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
230
231
232
233
234
		}

		/// Update the validity status of an existing account. If set to completed, the account
		/// will no longer be able to continue through the crowdfund process.
		///
Denis_P's avatar
Denis_P committed
235
		/// We check that the account exists at this stage, but has not completed the process.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
236
237
		///
		/// Origin must match the `ValidityOrigin`.
238
		#[pallet::weight(T::DbWeight::get().reads_writes(1, 1))]
239
		pub fn update_validity_status(
240
			origin: OriginFor<T>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
241
			who: T::AccountId,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
242
			validity: AccountValidity,
243
		) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
244
245
			T::ValidityOrigin::ensure_origin(origin)?;
			ensure!(Accounts::<T>::contains_key(&who), Error::<T>::InvalidAccount);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
246
247
248
249
250
251
252
253
254
255
256
			Accounts::<T>::try_mutate(
				&who,
				|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
					ensure!(
						status.validity != AccountValidity::Completed,
						Error::<T>::AlreadyCompleted
					);
					status.validity = validity;
					Ok(())
				},
			)?;
257
258
			Self::deposit_event(Event::<T>::ValidityUpdated(who, validity));
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
259
260
261
262
		}

		/// Update the balance of a valid account.
		///
Denis_P's avatar
Denis_P committed
263
		/// We check that the account is valid for a balance transfer at this point.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
264
265
		///
		/// Origin must match the `ValidityOrigin`.
266
		#[pallet::weight(T::DbWeight::get().reads_writes(2, 1))]
267
		pub fn update_balance(
268
			origin: OriginFor<T>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
269
270
271
272
			who: T::AccountId,
			free_balance: BalanceOf<T>,
			locked_balance: BalanceOf<T>,
			vat: Permill,
273
		) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
274
275
			T::ValidityOrigin::ensure_origin(origin)?;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
276
277
278
279
280
281
282
283
284
285
286
287
288
			Accounts::<T>::try_mutate(
				&who,
				|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
					// Account has a valid status (not Invalid, Pending, or Completed)...
					ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);

					free_balance.checked_add(&locked_balance).ok_or(Error::<T>::Overflow)?;
					status.free_balance = free_balance;
					status.locked_balance = locked_balance;
					status.vat = vat;
					Ok(())
				},
			)?;
289
290
			Self::deposit_event(Event::<T>::BalanceUpdated(who, free_balance, locked_balance));
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
291
292
293
294
295
296
297
		}

		/// Pay the user and complete the purchase process.
		///
		/// We reverify all assumptions about the state of an account, and complete the process.
		///
		/// Origin must match the configured `PaymentAccount`.
298
		#[pallet::weight(T::DbWeight::get().reads_writes(4, 2))]
299
		pub fn payout(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
300
301
302
303
304
			// Payments must be made directly by the `PaymentAccount`.
			let payment_account = ensure_signed(origin)?;
			ensure!(payment_account == PaymentAccount::<T>::get(), DispatchError::BadOrigin);

			// Account should not have a vesting schedule.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
305
306
307
308
			ensure!(
				T::VestingSchedule::vesting_balance(&who).is_none(),
				Error::<T>::VestingScheduleExists
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
309

Shawn Tabrizi's avatar
Shawn Tabrizi committed
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
			Accounts::<T>::try_mutate(
				&who,
				|status: &mut AccountStatus<BalanceOf<T>>| -> DispatchResult {
					// Account has a valid status (not Invalid, Pending, or Completed)...
					ensure!(status.validity.is_valid(), Error::<T>::InvalidAccount);

					// Transfer funds from the payment account into the purchasing user.
					let total_balance = status
						.free_balance
						.checked_add(&status.locked_balance)
						.ok_or(Error::<T>::Overflow)?;
					T::Currency::transfer(
						&payment_account,
						&who,
						total_balance,
						ExistenceRequirement::AllowDeath,
					)?;

					if !status.locked_balance.is_zero() {
						let unlock_block = UnlockBlock::<T>::get();
						// We allow some configurable portion of the purchased locked DOTs to be unlocked for basic usage.
						let unlocked = (T::UnlockedProportion::get() * status.locked_balance)
							.min(T::MaxUnlocked::get());
						let locked = status.locked_balance.saturating_sub(unlocked);
						// We checked that this account has no existing vesting schedule. So this function should
						// never fail, however if it does, not much we can do about it at this point.
						let _ = T::VestingSchedule::add_vesting_schedule(
							// Apply vesting schedule to this user
							&who,
							// For this much amount
							locked,
							// Unlocking the full amount after one block
							locked,
							// When everything unlocks
							unlock_block,
						);
					}

					// Setting the user account to `Completed` ends the purchase process for this user.
					status.validity = AccountValidity::Completed;
					Self::deposit_event(Event::<T>::PaymentComplete(
						who.clone(),
						status.free_balance,
						status.locked_balance,
					));
					Ok(())
				},
			)?;
358
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
359
360
361
362
363
364
365
		}

		/* Configuration Operations */

		/// Set the account that will be used to payout users in the DOT purchase process.
		///
		/// Origin must match the `ConfigurationOrigin`
366
		#[pallet::weight(T::DbWeight::get().writes(1))]
367
		pub fn set_payment_account(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
368
369
370
			T::ConfigurationOrigin::ensure_origin(origin)?;
			// Possibly this is worse than having the caller account be the payment account?
			PaymentAccount::<T>::set(who.clone());
371
372
			Self::deposit_event(Event::<T>::PaymentAccountSet(who));
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
373
374
375
376
377
		}

		/// Set the statement that must be signed for a user to participate on the DOT sale.
		///
		/// Origin must match the `ConfigurationOrigin`
378
		#[pallet::weight(T::DbWeight::get().writes(1))]
379
		pub fn set_statement(origin: OriginFor<T>, statement: Vec<u8>) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
380
			T::ConfigurationOrigin::ensure_origin(origin)?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
381
382
383
384
			ensure!(
				(statement.len() as u32) < T::MaxStatementLength::get(),
				Error::<T>::InvalidStatement
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
385
			// Possibly this is worse than having the caller account be the payment account?
386
387
388
			Statement::<T>::set(statement);
			Self::deposit_event(Event::<T>::StatementUpdated);
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
389
390
391
392
393
		}

		/// Set the block where locked DOTs will become unlocked.
		///
		/// Origin must match the `ConfigurationOrigin`
394
		#[pallet::weight(T::DbWeight::get().writes(1))]
Shawn Tabrizi's avatar
Shawn Tabrizi committed
395
396
397
398
		pub fn set_unlock_block(
			origin: OriginFor<T>,
			unlock_block: T::BlockNumber,
		) -> DispatchResult {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
399
			T::ConfigurationOrigin::ensure_origin(origin)?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
400
401
402
403
			ensure!(
				unlock_block > frame_system::Pallet::<T>::block_number(),
				Error::<T>::InvalidUnlockBlock
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
404
405
			// Possibly this is worse than having the caller account be the payment account?
			UnlockBlock::<T>::set(unlock_block);
406
407
			Self::deposit_event(Event::<T>::UnlockBlockUpdated(unlock_block));
			Ok(())
Shawn Tabrizi's avatar
Shawn Tabrizi committed
408
409
410
411
		}
	}
}

412
impl<T: Config> Pallet<T> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
413
414
415
416
417
418
419
420
421
	fn verify_signature(who: &T::AccountId, signature: &[u8]) -> Result<(), DispatchError> {
		// sr25519 always expects a 64 byte signature.
		ensure!(signature.len() == 64, Error::<T>::InvalidSignature);
		let signature: AnySignature = sr25519::Signature::from_slice(signature).into();

		// In Polkadot, the AccountId is always the same as the 32 byte public key.
		let account_bytes: [u8; 32] = account_to_bytes(who)?;
		let public_key = sr25519::Public::from_raw(account_bytes);

422
		let message = Statement::<T>::get();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
423
424
425
426
427
428
429
430
431
432
433

		// Check if everything is good or not.
		match signature.verify(message.as_slice(), &public_key) {
			true => Ok(()),
			false => Err(Error::<T>::InvalidSignature)?,
		}
	}
}

// This function converts a 32 byte AccountId to its byte-array equivalent form.
fn account_to_bytes<AccountId>(account: &AccountId) -> Result<[u8; 32], DispatchError>
Shawn Tabrizi's avatar
Shawn Tabrizi committed
434
435
where
	AccountId: Encode,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
436
437
438
439
440
441
442
443
{
	let account_vec = account.encode();
	ensure!(account_vec.len() == 32, "AccountId must be 32 bytes.");
	let mut bytes = [0u8; 32];
	bytes.copy_from_slice(&account_vec);
	Ok(bytes)
}

444
445
446
/// WARNING: Executing this function will clear all storage used by this pallet.
/// Be sure this is what you want...
pub fn remove_pallet<T>() -> frame_support::weights::Weight
Shawn Tabrizi's avatar
Shawn Tabrizi committed
447
448
where
	T: frame_system::Config,
449
450
451
452
453
454
455
{
	use frame_support::migration::remove_storage_prefix;
	remove_storage_prefix(b"Purchase", b"Accounts", b"");
	remove_storage_prefix(b"Purchase", b"PaymentAccount", b"");
	remove_storage_prefix(b"Purchase", b"Statement", b"");
	remove_storage_prefix(b"Purchase", b"UnlockBlock", b"");

456
	<T as frame_system::Config>::BlockWeights::get().max_block
457
458
}

Shawn Tabrizi's avatar
Shawn Tabrizi committed
459
460
461
462
#[cfg(test)]
mod tests {
	use super::*;

Shawn Tabrizi's avatar
Shawn Tabrizi committed
463
	use sp_core::{crypto::AccountId32, ed25519, Pair, Public, H256};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
464
465
	// The testing primitives are very useful for avoiding having to work with signatures
	// or public keys. `u64` is used as the `AccountId` and no `Signature`s are required.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
466
	use crate::purchase;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
467
	use frame_support::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
468
469
		assert_noop, assert_ok, dispatch::DispatchError::BadOrigin, ord_parameter_types,
		parameter_types, traits::Currency,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
470
	};
471
	use pallet_balances::Error as BalancesError;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
472
473
474
475
476
	use sp_runtime::{
		testing::Header,
		traits::{BlakeTwo256, Dispatchable, IdentifyAccount, Identity, IdentityLookup, Verify},
		MultiSignature,
	};
477
478
479
480
481
482
483
484
485
486

	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
	type Block = frame_system::mocking::MockBlock<Test>;

	frame_support::construct_runtime!(
		pub enum Test where
			Block = Block,
			NodeBlock = Block,
			UncheckedExtrinsic = UncheckedExtrinsic,
		{
487
488
489
490
			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
			Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
			Vesting: pallet_vesting::{Pallet, Call, Storage, Config<T>, Event<T>},
			Purchase: purchase::{Pallet, Call, Storage, Event<T>},
Shawn Tabrizi's avatar
Shawn Tabrizi committed
491
		}
492
	);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
493
494
495
496
497
498

	type AccountId = AccountId32;

	parameter_types! {
		pub const BlockHashCount: u32 = 250;
	}
499
	impl frame_system::Config for Test {
500
		type BaseCallFilter = frame_support::traits::Everything;
501
502
503
		type BlockWeights = ();
		type BlockLength = ();
		type DbWeight = ();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
504
505
506
507
508
509
510
511
512
		type Origin = Origin;
		type Call = Call;
		type Index = u64;
		type BlockNumber = u64;
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = AccountId;
		type Lookup = IdentityLookup<AccountId>;
		type Header = Header;
513
		type Event = Event;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
514
515
		type BlockHashCount = BlockHashCount;
		type Version = ();
516
		type PalletInfo = PalletInfo;
517
		type AccountData = pallet_balances::AccountData<u64>;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
518
		type OnNewAccount = ();
519
		type OnKilledAccount = ();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
520
		type SystemWeightInfo = ();
521
		type SS58Prefix = ();
522
		type OnSetCode = ();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
523
524
525
526
527
528
	}

	parameter_types! {
		pub const ExistentialDeposit: u64 = 1;
	}

529
	impl pallet_balances::Config for Test {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
530
		type Balance = u64;
531
		type Event = Event;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
532
533
534
		type DustRemoval = ();
		type ExistentialDeposit = ExistentialDeposit;
		type AccountStore = System;
535
		type MaxLocks = ();
Gavin Wood's avatar
Gavin Wood committed
536
537
		type MaxReserves = ();
		type ReserveIdentifier = [u8; 8];
Shawn Tabrizi's avatar
Shawn Tabrizi committed
538
539
540
541
542
543
544
		type WeightInfo = ();
	}

	parameter_types! {
		pub const MinVestedTransfer: u64 = 0;
	}

545
	impl pallet_vesting::Config for Test {
546
		type Event = Event;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
547
548
549
550
551
552
553
		type Currency = Balances;
		type BlockNumberToBalance = Identity;
		type MinVestedTransfer = MinVestedTransfer;
		type WeightInfo = ();
	}

	parameter_types! {
554
		pub const MaxStatementLength: u32 =  1_000;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
555
556
557
558
559
560
561
562
563
564
		pub const UnlockedProportion: Permill = Permill::from_percent(10);
		pub const MaxUnlocked: u64 = 10;
	}

	ord_parameter_types! {
		pub const ValidityOrigin: AccountId = AccountId32::from([0u8; 32]);
		pub const PaymentOrigin: AccountId = AccountId32::from([1u8; 32]);
		pub const ConfigurationOrigin: AccountId = AccountId32::from([2u8; 32]);
	}

565
	impl Config for Test {
566
		type Event = Event;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
567
568
		type Currency = Balances;
		type VestingSchedule = Vesting;
569
570
		type ValidityOrigin = frame_system::EnsureSignedBy<ValidityOrigin, AccountId>;
		type ConfigurationOrigin = frame_system::EnsureSignedBy<ConfigurationOrigin, AccountId>;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
571
572
573
574
575
576
577
578
		type MaxStatementLength = MaxStatementLength;
		type UnlockedProportion = UnlockedProportion;
		type MaxUnlocked = MaxUnlocked;
	}

	// This function basically just builds a genesis storage key/value store according to
	// our desired mockup. It also executes our `setup` function which sets up this pallet for use.
	pub fn new_test_ext() -> sp_io::TestExternalities {
579
		let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
580
581
582
583
584
585
586
587
588
589
		let mut ext = sp_io::TestExternalities::new(t);
		ext.execute_with(|| setup());
		ext
	}

	fn setup() {
		let statement = b"Hello, World".to_vec();
		let unlock_block = 100;
		Purchase::set_statement(Origin::signed(configuration_origin()), statement).unwrap();
		Purchase::set_unlock_block(Origin::signed(configuration_origin()), unlock_block).unwrap();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
590
591
		Purchase::set_payment_account(Origin::signed(configuration_origin()), payment_account())
			.unwrap();
Shawn Tabrizi's avatar
Shawn Tabrizi committed
592
593
594
595
596
597
598
599
600
601
602
603
604
		Balances::make_free_balance_be(&payment_account(), 100_000);
	}

	type AccountPublic = <MultiSignature as Verify>::Signer;

	/// Helper function to generate a crypto pair from seed
	fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
		TPublic::Pair::from_string(&format!("//{}", seed), None)
			.expect("static values are valid; qed")
			.public()
	}

	/// Helper function to generate an account ID from seed
Shawn Tabrizi's avatar
Shawn Tabrizi committed
605
606
607
	fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
	where
		AccountPublic: From<<TPublic::Pair as Pair>::Public>,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
	{
		AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
	}

	fn alice() -> AccountId {
		get_account_id_from_seed::<sr25519::Public>("Alice")
	}

	fn alice_ed25519() -> AccountId {
		get_account_id_from_seed::<ed25519::Public>("Alice")
	}

	fn bob() -> AccountId {
		get_account_id_from_seed::<sr25519::Public>("Bob")
	}

	fn alice_signature() -> [u8; 64] {
		// echo -n "Hello, World" | subkey -s sign "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice"
		hex_literal::hex!("20e0faffdf4dfe939f2faa560f73b1d01cde8472e2b690b7b40606a374244c3a2e9eb9c8107c10b605138374003af8819bd4387d7c24a66ee9253c2e688ab881")
	}

	fn bob_signature() -> [u8; 64] {
		// echo -n "Hello, World" | subkey -s sign "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Bob"
		hex_literal::hex!("d6d460187ecf530f3ec2d6e3ac91b9d083c8fbd8f1112d92a82e4d84df552d18d338e6da8944eba6e84afaacf8a9850f54e7b53a84530d649be2e0119c7ce889")
	}

	fn alice_signature_ed25519() -> [u8; 64] {
		// echo -n "Hello, World" | subkey -e sign "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice"
		hex_literal::hex!("ee3f5a6cbfc12a8f00c18b811dc921b550ddf272354cda4b9a57b1d06213fcd8509f5af18425d39a279d13622f14806c3e978e2163981f2ec1c06e9628460b0e")
	}

	fn validity_origin() -> AccountId {
		ValidityOrigin::get()
	}

	fn configuration_origin() -> AccountId {
		ConfigurationOrigin::get()
	}

	fn payment_account() -> AccountId {
		[42u8; 32].into()
	}

	#[test]
	fn set_statement_works_and_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			let statement = b"Test Set Statement".to_vec();
			// Invalid origin
			assert_noop!(
				Purchase::set_statement(Origin::signed(alice()), statement.clone()),
				BadOrigin,
			);
			// Too Long
			let long_statement = [0u8; 10_000].to_vec();
			assert_noop!(
				Purchase::set_statement(Origin::signed(configuration_origin()), long_statement),
				Error::<Test>::InvalidStatement,
			);
			// Just right...
Shawn Tabrizi's avatar
Shawn Tabrizi committed
667
668
669
670
			assert_ok!(Purchase::set_statement(
				Origin::signed(configuration_origin()),
				statement.clone()
			));
671
			assert_eq!(Statement::<Test>::get(), statement);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
		});
	}

	#[test]
	fn set_unlock_block_works_and_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			let unlock_block = 69;
			// Invalid origin
			assert_noop!(
				Purchase::set_unlock_block(Origin::signed(alice()), unlock_block),
				BadOrigin,
			);
			// Block Number in Past
			let bad_unlock_block = 50;
			System::set_block_number(bad_unlock_block);
			assert_noop!(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
688
689
690
691
				Purchase::set_unlock_block(
					Origin::signed(configuration_origin()),
					bad_unlock_block
				),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
692
693
694
				Error::<Test>::InvalidUnlockBlock,
			);
			// Just right...
Shawn Tabrizi's avatar
Shawn Tabrizi committed
695
696
697
698
			assert_ok!(Purchase::set_unlock_block(
				Origin::signed(configuration_origin()),
				unlock_block
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
699
700
701
702
703
704
705
706
707
708
709
710
711
712
			assert_eq!(UnlockBlock::<Test>::get(), unlock_block);
		});
	}

	#[test]
	fn set_payment_account_works_and_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			let payment_account: AccountId = [69u8; 32].into();
			// Invalid Origin
			assert_noop!(
				Purchase::set_payment_account(Origin::signed(alice()), payment_account.clone()),
				BadOrigin,
			);
			// Just right...
Shawn Tabrizi's avatar
Shawn Tabrizi committed
713
714
715
716
			assert_ok!(Purchase::set_payment_account(
				Origin::signed(configuration_origin()),
				payment_account.clone()
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
717
718
719
720
721
722
723
724
725
726
727
728
			assert_eq!(PaymentAccount::<Test>::get(), payment_account);
		});
	}

	#[test]
	fn signature_verification_works() {
		new_test_ext().execute_with(|| {
			assert_ok!(Purchase::verify_signature(&alice(), &alice_signature()));
			assert_ok!(Purchase::verify_signature(&alice_ed25519(), &alice_signature_ed25519()));
			assert_ok!(Purchase::verify_signature(&bob(), &bob_signature()));

			// Mixing and matching fails
Shawn Tabrizi's avatar
Shawn Tabrizi committed
729
730
731
732
733
734
735
736
			assert_noop!(
				Purchase::verify_signature(&alice(), &bob_signature()),
				Error::<Test>::InvalidSignature
			);
			assert_noop!(
				Purchase::verify_signature(&bob(), &alice_signature()),
				Error::<Test>::InvalidSignature
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
		});
	}

	#[test]
	fn account_creation_works() {
		new_test_ext().execute_with(|| {
			assert!(!Accounts::<Test>::contains_key(alice()));
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
				alice_signature().to_vec(),
			));
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::Initiated,
					free_balance: Zero::zero(),
					locked_balance: Zero::zero(),
					signature: alice_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
		});
	}

	#[test]
	fn account_creation_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			// Wrong Origin
			assert_noop!(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
767
768
769
770
771
				Purchase::create_account(
					Origin::signed(alice()),
					alice(),
					alice_signature().to_vec()
				),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
772
773
774
775
776
				BadOrigin,
			);

			// Wrong Account/Signature
			assert_noop!(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
777
778
779
780
781
				Purchase::create_account(
					Origin::signed(validity_origin()),
					alice(),
					bob_signature().to_vec()
				),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
782
783
784
785
				Error::<Test>::InvalidSignature,
			);

			// Account with vesting
786
			assert_ok!(<Test as Config>::VestingSchedule::add_vesting_schedule(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
787
788
789
790
791
792
				&alice(),
				100,
				1,
				50
			));
			assert_noop!(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
793
794
795
796
797
				Purchase::create_account(
					Origin::signed(validity_origin()),
					alice(),
					alice_signature().to_vec()
				),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
798
799
800
801
				Error::<Test>::VestingScheduleExists,
			);

			// Duplicate Purchasing Account
Shawn Tabrizi's avatar
Shawn Tabrizi committed
802
803
804
805
806
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				bob(),
				bob_signature().to_vec()
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
807
			assert_noop!(
Shawn Tabrizi's avatar
Shawn Tabrizi committed
808
809
810
811
812
				Purchase::create_account(
					Origin::signed(validity_origin()),
					bob(),
					bob_signature().to_vec()
				),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
				Error::<Test>::ExistingAccount,
			);
		});
	}

	#[test]
	fn update_validity_status_works() {
		new_test_ext().execute_with(|| {
			// Alice account is created.
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
				alice_signature().to_vec(),
			));
			// She submits KYC, and we update the status to `Pending`.
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::Pending,
			));
			// KYC comes back negative, so we mark the account invalid.
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::Invalid,
			));
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::Invalid,
					free_balance: Zero::zero(),
					locked_balance: Zero::zero(),
					signature: alice_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
			// She fixes it, we mark her account valid.
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::ValidLow,
			));
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::ValidLow,
					free_balance: Zero::zero(),
					locked_balance: Zero::zero(),
					signature: alice_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
		});
	}

	#[test]
	fn update_validity_status_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			// Wrong Origin
Shawn Tabrizi's avatar
Shawn Tabrizi committed
872
873
874
875
876
877
878
879
			assert_noop!(
				Purchase::update_validity_status(
					Origin::signed(alice()),
					alice(),
					AccountValidity::Pending,
				),
				BadOrigin
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
880
			// Inactive Account
Shawn Tabrizi's avatar
Shawn Tabrizi committed
881
882
883
884
885
886
887
888
			assert_noop!(
				Purchase::update_validity_status(
					Origin::signed(validity_origin()),
					alice(),
					AccountValidity::Pending,
				),
				Error::<Test>::InvalidAccount
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
889
890
891
892
893
894
895
896
897
898
899
			// Already Completed
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
				alice_signature().to_vec(),
			));
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::Completed,
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
900
901
902
903
904
905
906
907
			assert_noop!(
				Purchase::update_validity_status(
					Origin::signed(validity_origin()),
					alice(),
					AccountValidity::Pending,
				),
				Error::<Test>::AlreadyCompleted
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
908
909
910
911
912
913
914
915
916
917
		});
	}

	#[test]
	fn update_balance_works() {
		new_test_ext().execute_with(|| {
			// Alice account is created
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
918
919
				alice_signature().to_vec()
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
920
921
922
923
924
925
926
927
928
929
930
931
			// And approved for basic contribution
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::ValidLow,
			));
			// We set a balance on the user based on the payment they made. 50 locked, 50 free.
			assert_ok!(Purchase::update_balance(
				Origin::signed(validity_origin()),
				alice(),
				50,
				50,
Kian Paimani's avatar
Kian Paimani committed
932
				Permill::from_rational(77u32, 1000u32),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
			));
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::ValidLow,
					free_balance: 50,
					locked_balance: 50,
					signature: alice_signature().to_vec(),
					vat: Permill::from_parts(77000),
				}
			);
			// We can update the balance based on new information.
			assert_ok!(Purchase::update_balance(
				Origin::signed(validity_origin()),
				alice(),
				25,
				50,
				Permill::zero(),
			));
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::ValidLow,
					free_balance: 25,
					locked_balance: 50,
					signature: alice_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
		});
	}

	#[test]
	fn update_balance_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			// Wrong Origin
Shawn Tabrizi's avatar
Shawn Tabrizi committed
969
970
971
972
			assert_noop!(
				Purchase::update_balance(Origin::signed(alice()), alice(), 50, 50, Permill::zero(),),
				BadOrigin
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
973
			// Inactive Account
Shawn Tabrizi's avatar
Shawn Tabrizi committed
974
975
976
977
978
979
980
981
982
983
			assert_noop!(
				Purchase::update_balance(
					Origin::signed(validity_origin()),
					alice(),
					50,
					50,
					Permill::zero(),
				),
				Error::<Test>::InvalidAccount
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
984
			// Overflow
Shawn Tabrizi's avatar
Shawn Tabrizi committed
985
986
987
988
989
990
991
992
993
994
			assert_noop!(
				Purchase::update_balance(
					Origin::signed(validity_origin()),
					alice(),
					u64::MAX,
					u64::MAX,
					Permill::zero(),
				),
				Error::<Test>::InvalidAccount
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
995
996
997
998
999
1000
1001
1002
1003
1004
		});
	}

	#[test]
	fn payout_works() {
		new_test_ext().execute_with(|| {
			// Alice and Bob accounts are created
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1005
1006
				alice_signature().to_vec()
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1007
1008
1009
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				bob(),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1010
1011
				bob_signature().to_vec()
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
			// Alice is approved for basic contribution
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::ValidLow,
			));
			// Bob is approved for high contribution
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				bob(),
				AccountValidity::ValidHigh,
			));
			// We set a balance on the users based on the payment they made. 50 locked, 50 free.
			assert_ok!(Purchase::update_balance(
				Origin::signed(validity_origin()),
				alice(),
				50,
				50,
				Permill::zero(),
			));
			assert_ok!(Purchase::update_balance(
				Origin::signed(validity_origin()),
				bob(),
				100,
				150,
				Permill::zero(),
			));
			// Now we call payout for Alice and Bob.
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1040
1041
			assert_ok!(Purchase::payout(Origin::signed(payment_account()), alice(),));
			assert_ok!(Purchase::payout(Origin::signed(payment_account()), bob(),));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1042
			// Payment is made.
1043
1044
			assert_eq!(<Test as Config>::Currency::free_balance(&payment_account()), 99_650);
			assert_eq!(<Test as Config>::Currency::free_balance(&alice()), 100);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1045
			// 10% of the 50 units is unlocked automatically for Alice
1046
1047
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&alice()), Some(45));
			assert_eq!(<Test as Config>::Currency::free_balance(&bob()), 250);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1048
			// A max of 10 units is unlocked automatically for Bob
1049
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&bob()), Some(140));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
			// Status is completed.
			assert_eq!(
				Accounts::<Test>::get(alice()),
				AccountStatus {
					validity: AccountValidity::Completed,
					free_balance: 50,
					locked_balance: 50,
					signature: alice_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
			assert_eq!(
				Accounts::<Test>::get(bob()),
				AccountStatus {
					validity: AccountValidity::Completed,
					free_balance: 100,
					locked_balance: 150,
					signature: bob_signature().to_vec(),
					vat: Permill::zero(),
				}
			);
			// Vesting lock is removed in whole on block 101 (100 blocks after block 1)
			System::set_block_number(100);
1073
			let vest_call = Call::Vesting(pallet_vesting::Call::<Test>::vest());
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1074
1075
			assert_ok!(vest_call.clone().dispatch(Origin::signed(alice())));
			assert_ok!(vest_call.clone().dispatch(Origin::signed(bob())));
1076
1077
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&alice()), Some(45));
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&bob()), Some(140));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1078
1079
1080
			System::set_block_number(101);
			assert_ok!(vest_call.clone().dispatch(Origin::signed(alice())));
			assert_ok!(vest_call.clone().dispatch(Origin::signed(bob())));
1081
1082
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&alice()), None);
			assert_eq!(<Test as Config>::VestingSchedule::vesting_balance(&bob()), None);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1083
1084
1085
1086
1087
1088
1089
		});
	}

	#[test]
	fn payout_handles_basic_errors() {
		new_test_ext().execute_with(|| {
			// Wrong Origin
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1090
			assert_noop!(Purchase::payout(Origin::signed(alice()), alice(),), BadOrigin);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1091
			// Account with Existing Vesting Schedule
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1092
1093
1094
1095
1096
1097
1098
			assert_ok!(
				<Test as Config>::VestingSchedule::add_vesting_schedule(&bob(), 100, 1, 50,)
			);
			assert_noop!(
				Purchase::payout(Origin::signed(payment_account()), bob(),),
				Error::<Test>::VestingScheduleExists
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1099
			// Invalid Account (never created)
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1100
1101
1102
1103
			assert_noop!(
				Purchase::payout(Origin::signed(payment_account()), alice(),),
				Error::<Test>::InvalidAccount
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1104
1105
1106
1107
			// Invalid Account (created, but not valid)
			assert_ok!(Purchase::create_account(
				Origin::signed(validity_origin()),
				alice(),
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1108
1109
1110
1111
1112
				alice_signature().to_vec()
			));
			assert_noop!(
				Purchase::payout(Origin::signed(payment_account()), alice(),),
				Error::<Test>::InvalidAccount
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
			);
			// Not enough funds in payment account
			assert_ok!(Purchase::update_validity_status(
				Origin::signed(validity_origin()),
				alice(),
				AccountValidity::ValidHigh,
			));
			assert_ok!(Purchase::update_balance(
				Origin::signed(validity_origin()),
				alice(),
				100_000,
				100_000,
				Permill::zero(),
			));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1127
1128
1129
1130
			assert_noop!(
				Purchase::payout(Origin::signed(payment_account()), alice(),),
				BalancesError::<Test, _>::InsufficientBalance
			);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1131
1132
		});
	}
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148

	#[test]
	fn remove_pallet_works() {
		new_test_ext().execute_with(|| {
			let account_status = AccountStatus {
				validity: AccountValidity::Completed,
				free_balance: 1234,
				locked_balance: 4321,
				signature: b"my signature".to_vec(),
				vat: Permill::from_percent(50),
			};

			// Add some storage.
			Accounts::<Test>::insert(alice(), account_status.clone());
			Accounts::<Test>::insert(bob(), account_status);
			PaymentAccount::<Test>::put(alice());
1149
			Statement::<Test>::put(b"hello, world!".to_vec());
1150
1151
1152
1153
1154
			UnlockBlock::<Test>::put(4);

			// Verify storage exists.
			assert_eq!(Accounts::<Test>::iter().count(), 2);
			assert!(PaymentAccount::<Test>::exists());
1155
			assert!(Statement::<Test>::exists());
1156
1157
1158
1159
1160
1161
1162
1163
			assert!(UnlockBlock::<Test>::exists());

			// Remove storage.
			remove_pallet::<Test>();

			// Verify storage is gone.
			assert_eq!(Accounts::<Test>::iter().count(), 0);
			assert!(!PaymentAccount::<Test>::exists());
1164
			assert!(!Statement::<Test>::exists());
1165
1166
1167
			assert!(!UnlockBlock::<Test>::exists());
		});
	}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1168
}