crowdfund.rs 46 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
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
// This file is part of Polkadot.

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

// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! # Parachain Crowdfunding module
//!
//! The point of this module is to allow parachain projects to offer the ability to help fund a
//! deposit for the parachain. When the parachain is retired, the funds may be returned.
//!
//! Contributing funds is permissionless. Each fund has a child-trie which stores all
//! contributors account IDs together with the amount they contributed; the root of this can then be
//! used by the parachain to allow contributors to prove that they made some particular contribution
//! to the project (e.g. to be rewarded through some token or badge). The trie is retained for later
//! (efficient) redistribution back to the contributors.
//!
//! Contributions must be of at least `MinContribution` (to account for the resources taken in
//! tracking contributions), and may never tally greater than the fund's `cap`, set and fixed at the
//! time of creation. The `create` call may be used to create a new fund. In order to do this, then
//! a deposit must be paid of the amount `SubmissionDeposit`. Substantial resources are taken on
//! the main trie in tracking a fund and this accounts for that.
//!
//! Funds may be set up during an auction period; their closing time is fixed at creation (as a
//! block number) and if the fund is not successful by the closing time, then it will become *retired*.
//! Funds may span multiple auctions, and even auctions that sell differing periods. However, for a
//! fund to be active in bidding for an auction, it *must* have had *at least one bid* since the end
//! of the last auction. Until a fund takes a further bid following the end of an auction, then it
//! will be inactive.
//!
//! Contributors may get a refund of their contributions from retired funds. After a period (`RetirementPeriod`)
//! the fund may be dissolved entirely. At this point any non-refunded contributions are considered
//! `orphaned` and are disposed of through the `OrphanedFunds` handler (which may e.g. place them
//! into the treasury).
//!
//! Funds may accept contributions at any point before their success or retirement. When a parachain
//! slot auction enters its ending period, then parachains will each place a bid; the bid will be
//! raised once per block if the parachain had additional funds contributed since the last bid.
//!
//! Funds may set their deploy data (the code hash and head data of their parachain) at any point.
//! It may only be done once and once set cannot be changed. Good procedure would be to set them
//! ahead of receiving any contributions in order that contributors may verify that their parachain
//! contains all expected functionality. However, this is not enforced and deploy data may happen
//! at any point, even after a slot has been successfully won or, indeed, never.
//!
//! Funds that are successful winners of a slot may have their slot claimed through the `onboard`
//! call. This may only be done once and must be after the deploy data has been fixed. Successful
//! funds remain tracked (in the `Funds` storage item and the associated child trie) as long as
//! the parachain remains active. Once it does not, it is up to the parachain to ensure that the
//! funds are returned to this module's fund sub-account in order that they be redistributed back to
//! contributors. *Retirement* may be initiated by any account (using the `begin_retirement` call)
//! once the parachain is removed from the its slot.
//!
//! @WARNING: For funds to be returned, it is imperative that this module's account is provided as
//! the offboarding account for the slot. In the case that a parachain supplemented these funds in
//! order to win a later auction, then it is the parachain's duty to ensure that the right amount of
//! funds ultimately end up in module's fund sub-account.

69
use frame_support::{
70
	decl_module, decl_storage, decl_event, decl_error, storage::child, ensure, traits::{
71
72
		Currency, Get, OnUnbalanced, WithdrawReason, ExistenceRequirement::AllowDeath
	}
73
74
};
use system::ensure_signed;
75
use sp_runtime::{ModuleId,
76
77
	traits::{AccountIdConversion, Hash, Saturating, Zero, CheckedAdd}
};
78
use frame_support::weights::SimpleDispatchInfo;
79
80
use crate::slots;
use codec::{Encode, Decode};
81
use sp_std::vec::Vec;
82
use sp_core::storage::well_known_keys::CHILD_STORAGE_KEY_PREFIX;
83
use primitives::parachain::Id as ParaId;
84
85
86

const MODULE_ID: ModuleId = ModuleId(*b"py/cfund");

87
88
89
90
91
pub type BalanceOf<T> =
	<<T as slots::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
#[allow(dead_code)]
pub type NegativeImbalanceOf<T> =
	<<T as slots::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
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

pub trait Trait: slots::Trait {
	type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;

	/// The amount to be held on deposit by the owner of a crowdfund.
	type SubmissionDeposit: Get<BalanceOf<Self>>;

	/// The minimum amount that may be contributed into a crowdfund. Should almost certainly be at
	/// least ExistentialDeposit.
	type MinContribution: Get<BalanceOf<Self>>;

	/// The period of time (in blocks) after an unsuccessful crowdfund ending when
	/// contributors are able to withdraw their funds. After this period, their funds are lost.
	type RetirementPeriod: Get<Self::BlockNumber>;

	/// What to do with funds that were not withdrawn.
	type OrphanedFunds: OnUnbalanced<NegativeImbalanceOf<Self>>;
}

/// Simple index for identifying a fund.
pub type FundIndex = u32;

#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum LastContribution<BlockNumber> {
	Never,
	PreEnding(slots::AuctionIndex),
	Ending(BlockNumber),
}

#[derive(Encode, Decode, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
124
125
126
127
128
129
130
131
132
struct DeployData<Hash> {
	code_hash: Hash,
	code_size: u32,
	initial_head_data: Vec<u8>,
}

#[derive(Encode, Decode, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
#[codec(dumb_trait_bound)]
133
pub struct FundInfo<AccountId, Balance, Hash, BlockNumber> {
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
	/// The parachain that this fund has funded, if there is one. As long as this is `Some`, then
	/// the funds may not be withdrawn and the fund cannot be dissolved.
	parachain: Option<ParaId>,
	/// The owning account who placed the deposit.
	owner: AccountId,
	/// The amount of deposit placed.
	deposit: Balance,
	/// The total amount raised.
	raised: Balance,
	/// Block number after which the funding must have succeeded. If not successful at this number
	/// then everyone may withdraw their funds.
	end: BlockNumber,
	/// A hard-cap on the amount that may be contributed.
	cap: Balance,
	/// The most recent block that this had a contribution. Determines if we make a bid or not.
	/// If this is `Never`, this fund has never received a contribution.
	/// If this is `PreEnding(n)`, this fund received a contribution sometime in auction
	/// number `n` before the ending period.
	/// If this is `Ending(n)`, this fund received a contribution during the current ending period,
	/// where `n` is how far into the ending period the contribution was made.
	last_contribution: LastContribution<BlockNumber>,
	/// First slot in range to bid on; it's actually a LeasePeriod, but that's the same type as
	/// BlockNumber.
	first_slot: BlockNumber,
	/// Last slot in range to bid on; it's actually a LeasePeriod, but that's the same type as
	/// BlockNumber.
	last_slot: BlockNumber,
	/// The deployment data associated with this fund, if any. Once set it may not be reset. First
162
163
	/// is the code hash, second is the code size, third is the initial head data.
	deploy_data: Option<DeployData<Hash>>,
164
165
166
}

decl_storage! {
167
	trait Store for Module<T: Trait> as Crowdfund {
168
		/// Info on all of the funds.
169
		Funds get(fn funds):
170
			map hasher(twox_64_concat) FundIndex
Gavin Wood's avatar
Gavin Wood committed
171
			=> Option<FundInfo<T::AccountId, BalanceOf<T>, T::Hash, T::BlockNumber>>;
172
173

		/// The total number of funds that have so far been allocated.
174
		FundCount get(fn fund_count): FundIndex;
175
176
177

		/// The funds that have had additional contributions during the last block. This is used
		/// in order to determine which funds should submit new or updated bids.
178
		NewRaise get(fn new_raise): Vec<FundIndex>;
179
180

		/// The number of auctions that have entered into their ending period so far.
181
		EndingsCount get(fn endings_count): slots::AuctionIndex;
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
	}
}

decl_event! {
	pub enum Event<T> where
		<T as system::Trait>::AccountId,
		Balance = BalanceOf<T>,
	{
		Created(FundIndex),
		Contributed(AccountId, FundIndex, Balance),
		Withdrew(AccountId, FundIndex, Balance),
		Retiring(FundIndex),
		Dissolved(FundIndex),
		DeployDataFixed(FundIndex),
		Onboarded(FundIndex, ParaId),
	}
}

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
decl_error! {
	pub enum Error for Module<T: Trait> {
		/// Last slot must be greater than first slot.
		LastSlotBeforeFirstSlot,
		/// The last slot cannot be more then 3 slots after the first slot.
		LastSlotTooFarInFuture,
		/// The campaign ends before the current block number. The end must be in the future.
		CannotEndInPast,
		/// There was an overflow.
		Overflow,
		/// The contribution was below the minimum, `MinContribution`.
		ContributionTooSmall,
		/// Invalid fund index.
		InvalidFundIndex,
		/// Contributions exceed maximum amount.
		CapExceeded,
		/// The contribution period has already ended.
		ContributionPeriodOver,
		/// The origin of this call is invalid.
		InvalidOrigin,
		/// Deployment data for a fund can only be set once. The deployment data for this fund
		/// already exists.
		ExistingDeployData,
		/// Deployment data has not been set for this fund.
		UnsetDeployData,
		/// This fund has already been onboarded.
		AlreadyOnboard,
		/// This crowdfund does not correspond to a parachain.
		NotParachain,
		/// This parachain still has its deposit. Implies that it has already been offboarded.
		ParaHasDeposit,
		/// Funds have not yet been returned.
		FundsNotReturned,
		/// Fund has not yet retired.
		FundNotRetired,
		/// The crowdfund has not yet ended.
		FundNotEnded,
		/// There are no contributions stored in this crowdfund.
		NoContributions,
		/// This crowdfund has an active parachain and cannot be dissolved.
		HasActiveParachain,
		/// The retirement period has not ended.
		InRetirementPeriod,
	}
}

246
247
decl_module! {
	pub struct Module<T: Trait> for enum Call where origin: T::Origin {
248
249
		type Error = Error<T>;

250
		fn deposit_event() = default;
251

252
253
254
255
256
257
258
259
260
261
		/// Create a new crowdfunding campaign for a parachain slot deposit for the current auction.
		#[weight = SimpleDispatchInfo::FixedNormal(100_000)]
		fn create(origin,
			#[compact] cap: BalanceOf<T>,
			#[compact] first_slot: T::BlockNumber,
			#[compact] last_slot: T::BlockNumber,
			#[compact] end: T::BlockNumber
		) {
			let owner = ensure_signed(origin)?;

262
263
264
			ensure!(first_slot < last_slot, Error::<T>::LastSlotBeforeFirstSlot);
			ensure!(last_slot <= first_slot + 3.into(), Error::<T>::LastSlotTooFarInFuture);
			ensure!(end > <system::Module<T>>::block_number(), Error::<T>::CannotEndInPast);
265
266

			let deposit = T::SubmissionDeposit::get();
267
268
			let transfer = WithdrawReason::Transfer.into();
			let imb = T::Currency::withdraw(&owner, deposit, transfer, AllowDeath)?;
269
270

			let index = FundCount::get();
271
			let next_index = index.checked_add(1).ok_or(Error::<T>::Overflow)?;
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
			FundCount::put(next_index);

			// No fees are paid here if we need to create this account; that's why we don't just
			// use the stock `transfer`.
			T::Currency::resolve_creating(&Self::fund_account_id(index), imb);

			<Funds<T>>::insert(index, FundInfo {
				parachain: None,
				owner,
				deposit,
				raised: Zero::zero(),
				end,
				cap,
				last_contribution: LastContribution::Never,
				first_slot,
				last_slot,
				deploy_data: None,
			});

			Self::deposit_event(RawEvent::Created(index));
		}
293

294
295
		/// Contribute to a crowd sale. This will transfer some balance over to fund a parachain
		/// slot. It will be withdrawable in two instances: the parachain becomes retired; or the
Gavin Wood's avatar
Gavin Wood committed
296
		/// slot is unable to be purchased and the timeout expires.
297
298
299
		fn contribute(origin, #[compact] index: FundIndex, #[compact] value: BalanceOf<T>) {
			let who = ensure_signed(origin)?;

300
301
302
303
			ensure!(value >= T::MinContribution::get(), Error::<T>::ContributionTooSmall);
			let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
			fund.raised  = fund.raised.checked_add(&value).ok_or(Error::<T>::Overflow)?;
			ensure!(fund.raised <= fund.cap, Error::<T>::CapExceeded);
304
305
306

			// Make sure crowdfund has not ended
			let now = <system::Module<T>>::block_number();
307
			ensure!(fund.end > now, Error::<T>::ContributionPeriodOver);
308

309
			T::Currency::transfer(&who, &Self::fund_account_id(index), value, AllowDeath)?;
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

			let balance = Self::contribution_get(index, &who);
			let balance = balance.saturating_add(value);
			Self::contribution_put(index, &who, &balance);

			if <slots::Module<T>>::is_ending(now).is_some() {
				match fund.last_contribution {
					// In ending period; must ensure that we are in NewRaise.
					LastContribution::Ending(n) if n == now => {
						// do nothing - already in NewRaise
					}
					_ => {
						NewRaise::mutate(|v| v.push(index));
						fund.last_contribution = LastContribution::Ending(now);
					}
				}
			} else {
				let endings_count = Self::endings_count();
				match fund.last_contribution {
					LastContribution::PreEnding(a) if a == endings_count => {
						// Not in ending period and no auctions have ended ending since our
						// previous bid which was also not in an ending period.
						// `NewRaise` will contain our ID still: Do nothing.
					}
					_ => {
						// Not in ending period; but an auction has been ending since our previous
						// bid, or we never had one to begin with. Add bid.
						NewRaise::mutate(|v| v.push(index));
						fund.last_contribution = LastContribution::PreEnding(endings_count);
					}
				}
			}

			<Funds<T>>::insert(index, &fund);

			Self::deposit_event(RawEvent::Contributed(who, index, value));
		}

		/// Set the deploy data of the funded parachain if not already set. Once set, this cannot
		/// be changed again.
		///
		/// - `origin` must be the fund owner.
		/// - `index` is the fund index that `origin` owns and whose deploy data will be set.
		/// - `code_hash` is the hash of the parachain's Wasm validation function.
		/// - `initial_head_data` is the parachain's initial head data.
		fn fix_deploy_data(origin,
			#[compact] index: FundIndex,
			code_hash: T::Hash,
358
			code_size: u32,
359
360
361
362
			initial_head_data: Vec<u8>
		) {
			let who = ensure_signed(origin)?;

363
364
365
			let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
			ensure!(fund.owner == who, Error::<T>::InvalidOrigin); // must be fund owner
			ensure!(fund.deploy_data.is_none(), Error::<T>::ExistingDeployData);
366

367
			fund.deploy_data = Some(DeployData { code_hash, code_size, initial_head_data });
368
369
370
371
372

			<Funds<T>>::insert(index, &fund);

			Self::deposit_event(RawEvent::DeployDataFixed(index));
		}
373

374
375
376
377
378
379
380
381
		/// Complete onboarding process for a winning parachain fund. This can be called once by
		/// any origin once a fund wins a slot and the fund has set its deploy data (using
		/// `fix_deploy_data`).
		///
		/// - `index` is the fund index that `origin` owns and whose deploy data will be set.
		/// - `para_id` is the parachain index that this fund won.
		fn onboard(origin,
			#[compact] index: FundIndex,
382
			#[compact] para_id: ParaId
383
384
385
		) {
			let _ = ensure_signed(origin)?;

386
			let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
387
388
			let DeployData { code_hash, code_size, initial_head_data }
				= fund.clone().deploy_data.ok_or(Error::<T>::UnsetDeployData)?;
389
			ensure!(fund.parachain.is_none(), Error::<T>::AlreadyOnboard);
390
391
392
			fund.parachain = Some(para_id);

			let fund_origin = system::RawOrigin::Signed(Self::fund_account_id(index)).into();
393
394
395
396
397
398
399
400
			<slots::Module<T>>::fix_deploy_data(
				fund_origin,
				index,
				para_id,
				code_hash,
				code_size,
				initial_head_data,
			)?;
401
402
403
404
405

			<Funds<T>>::insert(index, &fund);

			Self::deposit_event(RawEvent::Onboarded(index, para_id));
		}
406

407
408
409
410
		/// Note that a successful fund has lost its parachain slot, and place it into retirement.
		fn begin_retirement(origin, #[compact] index: FundIndex) {
			let _ = ensure_signed(origin)?;

411
412
			let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
			let parachain_id = fund.parachain.take().ok_or(Error::<T>::NotParachain)?;
413
			// No deposit information implies the parachain was off-boarded
414
			ensure!(<slots::Module<T>>::deposits(parachain_id).len() == 0, Error::<T>::ParaHasDeposit);
415
416
			let account = Self::fund_account_id(index);
			// Funds should be returned at the end of off-boarding
417
			ensure!(T::Currency::free_balance(&account) >= fund.raised, Error::<T>::FundsNotReturned);
418
419
420
421
422
423
424
425
426
427
428
429
430
431

			// This fund just ended. Withdrawal period begins.
			let now = <system::Module<T>>::block_number();
			fund.end = now;

			<Funds<T>>::insert(index, &fund);

			Self::deposit_event(RawEvent::Retiring(index));
		}

		/// Withdraw full balance of a contributor to an unsuccessful or off-boarded fund.
		fn withdraw(origin, #[compact] index: FundIndex) {
			let who = ensure_signed(origin)?;

432
433
			let mut fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
			ensure!(fund.parachain.is_none(), Error::<T>::FundNotRetired);
434
435
436
			let now = <system::Module<T>>::block_number();

			// `fund.end` can represent the end of a failed crowdsale or the beginning of retirement
437
			ensure!(now >= fund.end, Error::<T>::FundNotEnded);
438
439

			let balance = Self::contribution_get(index, &who);
440
			ensure!(balance > Zero::zero(), Error::<T>::NoContributions);
441
442

			// Avoid using transfer to ensure we don't pay any fees.
443
444
445
446
			let fund_account = &Self::fund_account_id(index);
			let transfer = WithdrawReason::Transfer.into();
			let imbalance = T::Currency::withdraw(fund_account, balance, transfer, AllowDeath)?;
			let _ = T::Currency::resolve_into_existing(&who, imbalance);
447
448
449
450
451
452
453
454

			Self::contribution_kill(index, &who);
			fund.raised = fund.raised.saturating_sub(balance);

			<Funds<T>>::insert(index, &fund);

			Self::deposit_event(RawEvent::Withdrew(who, index, balance));
		}
455

456
457
458
459
460
461
		/// Remove a fund after either: it was unsuccessful and it timed out; or it was successful
		/// but it has been retired from its parachain slot. This places any deposits that were not
		/// withdrawn into the treasury.
		fn dissolve(origin, #[compact] index: FundIndex) {
			let _ = ensure_signed(origin)?;

462
463
			let fund = Self::funds(index).ok_or(Error::<T>::InvalidFundIndex)?;
			ensure!(fund.parachain.is_none(), Error::<T>::HasActiveParachain);
464
			let now = <system::Module<T>>::block_number();
465
466
			ensure!(
				now >= fund.end.saturating_add(T::RetirementPeriod::get()),
467
				Error::<T>::InRetirementPeriod
468
			);
469
470
471
472

			let account = Self::fund_account_id(index);

			// Avoid using transfer to ensure we don't pay any fees.
473
474
475
476
477
478
			let transfer = WithdrawReason::Transfer.into();
			let imbalance = T::Currency::withdraw(&account, fund.deposit, transfer, AllowDeath)?;
			let _ = T::Currency::resolve_into_existing(&fund.owner, imbalance);

			let imbalance = T::Currency::withdraw(&account, fund.raised, transfer, AllowDeath)?;
			T::OrphanedFunds::on_unbalanced(imbalance);
479
480
481
482
483
484

			Self::crowdfund_kill(index);
			<Funds<T>>::remove(index);

			Self::deposit_event(RawEvent::Dissolved(index));
		}
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
		fn on_finalize(n: T::BlockNumber) {
			if let Some(n) = <slots::Module<T>>::is_ending(n) {
				let auction_index = <slots::Module<T>>::auction_counter();
				if n.is_zero() {
					// first block of ending period.
					EndingsCount::mutate(|c| *c += 1);
				}
				for (fund, index) in NewRaise::take().into_iter().filter_map(|i| Self::funds(i).map(|f| (f, i))) {
					let bidder = slots::Bidder::New(slots::NewBidder {
						who: Self::fund_account_id(index),
						/// FundIndex and slots::SubId happen to be the same type (u32). If this
						/// ever changes, then some sort of conversion will be needed here.
						sub: index,
					});

					// Care needs to be taken by the crowdfund creator that this function will succeed given
					// the crowdfunding configuration. We do some checks ahead of time in crowdfund `create`.
					let _ = <slots::Module<T>>::handle_bid(
						bidder,
						auction_index,
						fund.first_slot,
						fund.last_slot,
						fund.raised,
					);
				}
			}
		}
	}
}

impl<T: Trait> Module<T> {
	/// The account ID of the fund pot.
	///
	/// This actually does computation. If you need to keep using it, then make sure you cache the
	/// value and only call this once.
	pub fn fund_account_id(index: FundIndex) -> T::AccountId {
		MODULE_ID.into_sub_account(index)
	}

	pub fn id_from_index(index: FundIndex) -> Vec<u8> {
		let mut buf = Vec::new();
		buf.extend_from_slice(b"crowdfund");
		buf.extend_from_slice(&index.to_le_bytes()[..]);

		CHILD_STORAGE_KEY_PREFIX.into_iter()
			.chain(b"default:")
			.chain(T::Hashing::hash(&buf[..]).as_ref().into_iter())
			.cloned()
			.collect()
	}

537
538
539
540
541
542
	/// Child trie unique id for a crowdfund is built from the hash part of the fund id.
	pub fn trie_unique_id(fund_id: &[u8]) -> child::ChildInfo {
		let start = CHILD_STORAGE_KEY_PREFIX.len() + b"default:".len();
		child::ChildInfo::new_default(&fund_id[start..])
	}

543
544
	pub fn contribution_put(index: FundIndex, who: &T::AccountId, balance: &BalanceOf<T>) {
		let id = Self::id_from_index(index);
545
		who.using_encoded(|b| child::put(id.as_ref(), Self::trie_unique_id(id.as_ref()), b, balance));
546
547
548
549
	}

	pub fn contribution_get(index: FundIndex, who: &T::AccountId) -> BalanceOf<T> {
		let id = Self::id_from_index(index);
550
551
552
553
554
		who.using_encoded(|b| child::get_or_default::<BalanceOf<T>>(
			id.as_ref(),
			Self::trie_unique_id(id.as_ref()),
			b,
		))
555
556
557
558
	}

	pub fn contribution_kill(index: FundIndex, who: &T::AccountId) {
		let id = Self::id_from_index(index);
559
		who.using_encoded(|b| child::kill(id.as_ref(), Self::trie_unique_id(id.as_ref()), b));
560
561
562
563
	}

	pub fn crowdfund_kill(index: FundIndex) {
		let id = Self::id_from_index(index);
564
		child::kill_storage(id.as_ref(), Self::trie_unique_id(id.as_ref()));
565
566
567
568
569
570
571
572
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	use std::{collections::HashMap, cell::RefCell};
573
	use frame_support::{impl_outer_origin, assert_ok, assert_noop, parameter_types};
Gavin Wood's avatar
Gavin Wood committed
574
	use frame_support::traits::Contains;
575
	use sp_core::H256;
576
	use primitives::parachain::{Info as ParaInfo, Id as ParaId};
577
578
	// 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 requried.
579
	use sp_runtime::{
Gavin Wood's avatar
Gavin Wood committed
580
		Perbill, Permill, Percent, testing::Header, DispatchResult,
581
		traits::{BlakeTwo256, OnInitialize, OnFinalize, IdentityLookup},
582
	};
583
	use crate::registrar::Registrar;
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615

	impl_outer_origin! {
		pub enum Origin for Test {}
	}

	// For testing the module, we construct most of a mock runtime. This means
	// first constructing a configuration type (`Test`) which `impl`s each of the
	// configuration traits of modules we want to use.
	#[derive(Clone, Eq, PartialEq)]
	pub struct Test;
	parameter_types! {
		pub const BlockHashCount: u32 = 250;
		pub const MaximumBlockWeight: u32 = 4 * 1024 * 1024;
		pub const MaximumBlockLength: u32 = 4 * 1024 * 1024;
		pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
	}
	impl system::Trait for Test {
		type Origin = Origin;
		type Call = ();
		type Index = u64;
		type BlockNumber = u64;
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = u64;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
		type Event = ();
		type BlockHashCount = BlockHashCount;
		type MaximumBlockWeight = MaximumBlockWeight;
		type MaximumBlockLength = MaximumBlockLength;
		type AvailableBlockRatio = AvailableBlockRatio;
		type Version = ();
616
		type ModuleToIndex = ();
617
		type AccountData = balances::AccountData<u64>;
Gavin Wood's avatar
Gavin Wood committed
618
		type OnNewAccount = ();
619
		type OnKilledAccount = Balances;
620
621
	}
	parameter_types! {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
622
		pub const ExistentialDeposit: u64 = 1;
623
624
625
	}
	impl balances::Trait for Test {
		type Balance = u64;
Gavin Wood's avatar
Gavin Wood committed
626
		type Event = ();
627
		type DustRemoval = ();
628
		type ExistentialDeposit = ExistentialDeposit;
629
		type AccountStore = System;
630
631
632
633
634
635
636
	}

	parameter_types! {
		pub const ProposalBond: Permill = Permill::from_percent(5);
		pub const ProposalBondMinimum: u64 = 1;
		pub const SpendPeriod: u64 = 2;
		pub const Burn: Permill = Permill::from_percent(50);
Gavin Wood's avatar
Gavin Wood committed
637
638
639
640
641
642
643
644
645
		pub const TipCountdown: u64 = 1;
		pub const TipFindersFee: Percent = Percent::from_percent(20);
		pub const TipReportDepositBase: u64 = 1;
		pub const TipReportDepositPerByte: u64 = 1;
	}
	pub struct Nobody;
	impl Contains<u64> for Nobody {
		fn contains(_: &u64) -> bool { false }
		fn sorted_members() -> Vec<u64> { vec![] }
646
647
		#[cfg(feature = "runtime-benchmarks")]
		fn add(_: &u64) { unimplemented!() }
648
649
650
651
652
653
654
655
656
657
658
	}
	impl treasury::Trait for Test {
		type Currency = balances::Module<Test>;
		type ApproveOrigin = system::EnsureRoot<u64>;
		type RejectOrigin = system::EnsureRoot<u64>;
		type Event = ();
		type ProposalRejection = ();
		type ProposalBond = ProposalBond;
		type ProposalBondMinimum = ProposalBondMinimum;
		type SpendPeriod = SpendPeriod;
		type Burn = Burn;
Gavin Wood's avatar
Gavin Wood committed
659
660
661
662
663
		type Tippers = Nobody;
		type TipCountdown = TipCountdown;
		type TipFindersFee = TipFindersFee;
		type TipReportDepositBase = TipReportDepositBase;
		type TipReportDepositPerByte = TipReportDepositPerByte;
664
665
666
667
668
669
670
671
	}

	thread_local! {
		pub static PARACHAIN_COUNT: RefCell<u32> = RefCell::new(0);
		pub static PARACHAINS:
			RefCell<HashMap<u32, (Vec<u8>, Vec<u8>)>> = RefCell::new(HashMap::new());
	}

672
673
674
	const MAX_CODE_SIZE: u32 = 100;
	const MAX_HEAD_DATA_SIZE: u32 = 10;

675
	pub struct TestParachains;
676
677
	impl Registrar<u64> for TestParachains {
		fn new_id() -> ParaId {
678
679
680
681
682
			PARACHAIN_COUNT.with(|p| {
				*p.borrow_mut() += 1;
				(*p.borrow() - 1).into()
			})
		}
683

684
685
686
687
688
689
690
691
		fn head_data_size_allowed(head_data_size: u32) -> bool {
			head_data_size <= MAX_HEAD_DATA_SIZE
		}

		fn code_size_allowed(code_size: u32) -> bool {
			code_size <= MAX_CODE_SIZE
		}

692
693
694
		fn register_para(
			id: ParaId,
			_info: ParaInfo,
695
696
			code: Vec<u8>,
			initial_head_data: Vec<u8>
697
		) -> DispatchResult {
698
			PARACHAINS.with(|p| {
699
				if p.borrow().contains_key(&id.into()) {
700
701
					panic!("ID already exists")
				}
702
				p.borrow_mut().insert(id.into(), (code, initial_head_data));
703
704
705
				Ok(())
			})
		}
706
707

		fn deregister_para(id: ParaId) -> DispatchResult {
708
			PARACHAINS.with(|p| {
709
				if !p.borrow().contains_key(&id.into()) {
710
711
					panic!("ID doesn't exist")
				}
712
				p.borrow_mut().remove(&id.into());
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
				Ok(())
			})
		}
	}

	parameter_types!{
		pub const LeasePeriod: u64 = 10;
		pub const EndingPeriod: u64 = 3;
	}
	impl slots::Trait for Test {
		type Event = ();
		type Currency = Balances;
		type Parachains = TestParachains;
		type LeasePeriod = LeasePeriod;
		type EndingPeriod = EndingPeriod;
728
		type Randomness = RandomnessCollectiveFlip;
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
	}
	parameter_types! {
		pub const SubmissionDeposit: u64 = 1;
		pub const MinContribution: u64 = 10;
		pub const RetirementPeriod: u64 = 5;
	}
	impl Trait for Test {
		type Event = ();
		type SubmissionDeposit = SubmissionDeposit;
		type MinContribution = MinContribution;
		type RetirementPeriod = RetirementPeriod;
		type OrphanedFunds = Treasury;
	}

	type System = system::Module<Test>;
	type Balances = balances::Module<Test>;
	type Slots = slots::Module<Test>;
	type Treasury = treasury::Module<Test>;
	type Crowdfund = Module<Test>;
748
	type RandomnessCollectiveFlip = randomness_collective_flip::Module<Test>;
Gavin Wood's avatar
Gavin Wood committed
749
	use balances::Error as BalancesError;
750
	use slots::Error as SlotsError;
751
752
753

	// This function basically just builds a genesis storage key/value store according to
	// our desired mockup.
754
	fn new_test_ext() -> sp_io::TestExternalities {
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
		let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
		balances::GenesisConfig::<Test>{
			balances: vec![(1, 1000), (2, 2000), (3, 3000), (4, 4000)],
		}.assimilate_storage(&mut t).unwrap();
		t.into()
	}

	fn run_to_block(n: u64) {
		while System::block_number() < n {
			Crowdfund::on_finalize(System::block_number());
			Treasury::on_finalize(System::block_number());
			Slots::on_finalize(System::block_number());
			Balances::on_finalize(System::block_number());
			System::on_finalize(System::block_number());
			System::set_block_number(System::block_number() + 1);
			System::on_initialize(System::block_number());
			Balances::on_initialize(System::block_number());
			Slots::on_initialize(System::block_number());
773
			Treasury::on_initialize(System::block_number());
774
775
776
777
778
779
			Crowdfund::on_initialize(System::block_number());
		}
	}

	#[test]
	fn basic_setup_works() {
780
		new_test_ext().execute_with(|| {
781
782
783
784
785
786
787
788
789
790
791
792
			assert_eq!(System::block_number(), 1);
			assert_eq!(Crowdfund::fund_count(), 0);
			assert_eq!(Crowdfund::funds(0), None);
			let empty: Vec<FundIndex> = Vec::new();
			assert_eq!(Crowdfund::new_raise(), empty);
			assert_eq!(Crowdfund::contribution_get(0, &1), 0);
			assert_eq!(Crowdfund::endings_count(), 0);
		});
	}

	#[test]
	fn create_works() {
793
		new_test_ext().execute_with(|| {
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
			// Now try to create a crowdfund campaign
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Crowdfund::fund_count(), 1);
			// This is what the initial `fund_info` should look like
			let fund_info = FundInfo {
				parachain: None,
				owner: 1,
				deposit: 1,
				raised: 0,
				// 5 blocks length + 3 block ending period + 1 starting block
				end: 9,
				cap: 1000,
				last_contribution: LastContribution::Never,
				first_slot: 1,
				last_slot: 4,
				deploy_data: None,
			};
			assert_eq!(Crowdfund::funds(0), Some(fund_info));
			// User has deposit removed from their free balance
			assert_eq!(Balances::free_balance(1), 999);
			// Deposit is placed in crowdfund free balance
			assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 1);
			// No new raise until first contribution
			let empty: Vec<FundIndex> = Vec::new();
			assert_eq!(Crowdfund::new_raise(), empty);
		});
	}

	#[test]
	fn create_handles_basic_errors() {
824
		new_test_ext().execute_with(|| {
825
			// Cannot create a crowdfund with bad slots
826
827
828
829
830
831
832
833
			assert_noop!(
				Crowdfund::create(Origin::signed(1), 1000, 4, 1, 9),
				Error::<Test>::LastSlotBeforeFirstSlot
			);
			assert_noop!(
				Crowdfund::create(Origin::signed(1), 1000, 1, 5, 9),
				Error::<Test>::LastSlotTooFarInFuture
			);
834
835

			// Cannot create a crowdfund without some deposit funds
836
837
838
839
			assert_noop!(
				Crowdfund::create(Origin::signed(1337), 1000, 1, 3, 9),
				BalancesError::<Test, _>::InsufficientBalance
			);
840
841
842
843
844
		});
	}

	#[test]
	fn contribute_works() {
845
		new_test_ext().execute_with(|| {
846
847
848
849
850
851
852
853
854
855
856
			// Set up a crowdfund
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);
			assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 1);

			// No contributions yet
			assert_eq!(Crowdfund::contribution_get(0, &1), 0);

			// User 1 contributes to their own crowdfund
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 49));
			// User 1 has spent some funds to do this, transfer fees **are** taken
Gavin Wood's avatar
Gavin Wood committed
857
			assert_eq!(Balances::free_balance(1), 950);
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
			// Contributions are stored in the trie
			assert_eq!(Crowdfund::contribution_get(0, &1), 49);
			// Contributions appear in free balance of crowdfund
			assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 50);
			// Crowdfund is added to NewRaise
			assert_eq!(Crowdfund::new_raise(), vec![0]);

			let fund = Crowdfund::funds(0).unwrap();

			// Last contribution time recorded
			assert_eq!(fund.last_contribution, LastContribution::PreEnding(0));
			assert_eq!(fund.raised, 49);
		});
	}

	#[test]
	fn contribute_handles_basic_errors() {
875
		new_test_ext().execute_with(|| {
876
			// Cannot contribute to non-existing fund
877
			assert_noop!(Crowdfund::contribute(Origin::signed(1), 0, 49), Error::<Test>::InvalidFundIndex);
878
			// Cannot contribute below minimum contribution
879
			assert_noop!(Crowdfund::contribute(Origin::signed(1), 0, 9), Error::<Test>::ContributionTooSmall);
880
881
882
883
884
885

			// Set up a crowdfund
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 101));

			// Cannot contribute past the limit
886
			assert_noop!(Crowdfund::contribute(Origin::signed(2), 0, 900), Error::<Test>::CapExceeded);
887
888
889
890
891

			// Move past end date
			run_to_block(10);

			// Cannot contribute to ended fund
892
			assert_noop!(Crowdfund::contribute(Origin::signed(1), 0, 49), Error::<Test>::ContributionPeriodOver);
893
894
895
896
897
		});
	}

	#[test]
	fn fix_deploy_data_works() {
898
		new_test_ext().execute_with(|| {
899
900
901
902
903
904
905
906
907
			// Set up a crowdfund
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
908
				0,
909
910
911
912
913
914
				vec![0]
			));

			let fund = Crowdfund::funds(0).unwrap();

			// Confirm deploy data is stored correctly
915
916
917
918
919
920
921
922
			assert_eq!(
				fund.deploy_data,
				Some(DeployData {
					code_hash: <Test as system::Trait>::Hash::default(),
					code_size: 0,
					initial_head_data: vec![0],
				}),
			);
923
924
925
926
927
		});
	}

	#[test]
	fn fix_deploy_data_handles_basic_errors() {
928
		new_test_ext().execute_with(|| {
929
930
931
932
933
934
935
936
937
			// Set up a crowdfund
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Cannot set deploy data by non-owner
			assert_noop!(Crowdfund::fix_deploy_data(
				Origin::signed(2),
				0,
				<Test as system::Trait>::Hash::default(),
938
				0,
939
				vec![0]),
940
				Error::<Test>::InvalidOrigin
941
942
943
944
945
946
947
			);

			// Cannot set deploy data to an invalid index
			assert_noop!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				1,
				<Test as system::Trait>::Hash::default(),
948
				0,
949
				vec![0]),
950
				Error::<Test>::InvalidFundIndex
951
952
953
954
955
956
957
			);

			// Cannot set deploy data after it already has been set
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
958
				0,
959
960
961
962
963
964
965
				vec![0]
			));

			assert_noop!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
966
				0,
967
				vec![1]),
968
				Error::<Test>::ExistingDeployData
969
970
971
972
973
974
			);
		});
	}

	#[test]
	fn onboard_works() {
975
		new_test_ext().execute_with(|| {
976
977
978
979
980
981
982
983
984
985
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
986
				0,
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
				vec![0]
			));

			// Fund crowdfund
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 1000));

			run_to_block(10);

			// Endings count incremented
			assert_eq!(Crowdfund::endings_count(), 1);

			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));

			let fund = Crowdfund::funds(0).unwrap();
			// Crowdfund is now assigned a parachain id
			assert_eq!(fund.parachain, Some(0.into()));
			// This parachain is managed by Slots
			assert_eq!(Slots::managed_ids(), vec![0.into()]);
		});
	}

	#[test]
	fn onboard_handles_basic_errors() {
1011
		new_test_ext().execute_with(|| {
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Fund crowdfund
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 1000));

			run_to_block(10);

			// Cannot onboard invalid fund index
1023
			assert_noop!(Crowdfund::onboard(Origin::signed(1), 1, 0.into()), Error::<Test>::InvalidFundIndex);
1024
			// Cannot onboard crowdfund without deploy data
1025
			assert_noop!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()), Error::<Test>::UnsetDeployData);
1026
1027
1028
1029
1030
1031

			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1032
				0,
1033
1034
1035
1036
				vec![0]
			));

			// Cannot onboard fund with incorrect parachain id
1037
			assert_noop!(Crowdfund::onboard(Origin::signed(1), 0, 1.into()), SlotsError::<Test>::ParaNotOnboarding);
1038
1039
1040
1041
1042

			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));

			// Cannot onboard fund again
1043
			assert_noop!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()), Error::<Test>::AlreadyOnboard);
1044
1045
1046
1047
1048
		});
	}

	#[test]
	fn begin_retirement_works() {
1049
		new_test_ext().execute_with(|| {
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1060
				0,
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
				vec![0]
			));

			// Fund crowdfund
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 1000));

			run_to_block(10);

			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));
			// Fund is assigned a parachain id
			let fund = Crowdfund::funds(0).unwrap();
			assert_eq!(fund.parachain, Some(0.into()));

			// Off-boarding is set to the crowdfund account
			assert_eq!(Slots::offboarding(ParaId::from(0)), Crowdfund::fund_account_id(0));

			run_to_block(50);

			// Retire crowdfund to remove parachain id
			assert_ok!(Crowdfund::begin_retirement(Origin::signed(1), 0));

			// Fund should no longer have parachain id
			let fund = Crowdfund::funds(0).unwrap();
			assert_eq!(fund.parachain, None);

		});
	}

	#[test]
	fn begin_retirement_handles_basic_errors() {
1092
		new_test_ext().execute_with(|| {
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			assert_eq!(Balances::free_balance(1), 999);

			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1103
				0,
1104
1105
1106
1107
1108
1109
1110
1111
1112
				vec![0]
			));

			// Fund crowdfund
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 1000));

			run_to_block(10);

			// Cannot retire fund that is not onboarded
1113
			assert_noop!(Crowdfund::begin_retirement(Origin::signed(1), 0), Error::<Test>::NotParachain);
1114
1115
1116
1117
1118
1119
1120
1121

			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));
			// Fund is assigned a parachain id
			let fund = Crowdfund::funds(0).unwrap();
			assert_eq!(fund.parachain, Some(0.into()));

			// Cannot retire fund whose deposit has not been returned
1122
			assert_noop!(Crowdfund::begin_retirement(Origin::signed(1), 0), Error::<Test>::ParaHasDeposit);
1123
1124
1125
1126

			run_to_block(50);

			// Cannot retire invalid fund index
1127
			assert_noop!(Crowdfund::begin_retirement(Origin::signed(1), 1), Error::<Test>::InvalidFundIndex);
1128
1129
1130

			// Cannot retire twice
			assert_ok!(Crowdfund::begin_retirement(Origin::signed(1), 0));
1131
			assert_noop!(Crowdfund::begin_retirement(Origin::signed(1), 0), Error::<Test>::NotParachain);
1132
1133
1134
1135
1136
		});
	}

	#[test]
	fn withdraw_works() {
1137
		new_test_ext().execute_with(|| {
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			// Transfer fee is taken here
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 100));
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 200));
			assert_ok!(Crowdfund::contribute(Origin::signed(3), 0, 300));

			// Skip all the way to the end
			run_to_block(50);

			// User can withdraw their full balance without fees
			assert_ok!(Crowdfund::withdraw(Origin::signed(1), 0));
Gavin Wood's avatar
Gavin Wood committed
1151
			assert_eq!(Balances::free_balance(1), 999);
1152
1153

			assert_ok!(Crowdfund::withdraw(Origin::signed(2), 0));
Gavin Wood's avatar
Gavin Wood committed
1154
			assert_eq!(Balances::free_balance(2), 2000);
1155
1156

			assert_ok!(Crowdfund::withdraw(Origin::signed(3), 0));
Gavin Wood's avatar
Gavin Wood committed
1157
			assert_eq!(Balances::free_balance(3), 3000);
1158
1159
		});
	}
1160

1161
1162
	#[test]
	fn withdraw_handles_basic_errors() {
1163
		new_test_ext().execute_with(|| {
1164
1165
1166
1167
1168
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			// Transfer fee is taken here
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 49));
Gavin Wood's avatar
Gavin Wood committed
1169
			assert_eq!(Balances::free_balance(1), 950);
1170
1171
1172
1173

			run_to_block(5);

			// Cannot withdraw before fund ends
1174
			assert_noop!(Crowdfund::withdraw(Origin::signed(1), 0), Error::<Test>::FundNotEnded);
1175
1176
1177
1178

			run_to_block(10);

			// Cannot withdraw if they did not contribute
1179
			assert_noop!(Crowdfund::withdraw(Origin::signed(2), 0), Error::<Test>::NoContributions);
1180
			// Cannot withdraw from a non-existent fund
1181
			assert_noop!(Crowdfund::withdraw(Origin::signed(1), 1), Error::<Test>::InvalidFundIndex);
1182
1183
1184
1185
1186
		});
	}

	#[test]
	fn dissolve_works() {
1187
		new_test_ext().execute_with(|| {
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			// Transfer fee is taken here
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 100));
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 200));
			assert_ok!(Crowdfund::contribute(Origin::signed(3), 0, 300));

			// Skip all the way to the end
			run_to_block(50);
1198

Gavin Wood's avatar
Gavin Wood committed
1199
1200
			// Check initiator's balance.
			assert_eq!(Balances::free_balance(1), 899);
1201
1202
1203
1204
1205
1206
1207
1208
1209
			// Check current funds (contributions + deposit)
			assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 601);

			// Dissolve the crowdfund
			assert_ok!(Crowdfund::dissolve(Origin::signed(1), 0));

			// Fund account is emptied
			assert_eq!(Balances::free_balance(Crowdfund::fund_account_id(0)), 0);
			// Deposit is returned
Gavin Wood's avatar
Gavin Wood committed
1210
			assert_eq!(Balances::free_balance(1), 900);
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
			// Treasury account is filled
			assert_eq!(Balances::free_balance(Treasury::account_id()), 600);

			// Storage trie is removed
			assert_eq!(Crowdfund::contribution_get(0,&0), 0);
			// Fund storage is removed
			assert_eq!(Crowdfund::funds(0), None);

		});
	}

	#[test]
	fn dissolve_handles_basic_errors() {
1224
		new_test_ext().execute_with(|| {
1225
1226
1227
1228
1229
1230
1231
1232
1233
			// Set up a crowdfund
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			// Transfer fee is taken here
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 100));
			assert_ok!(Crowdfund::contribute(Origin::signed(2), 0, 200));
			assert_ok!(Crowdfund::contribute(Origin::signed(3), 0, 300));

			// Cannot dissolve an invalid fund index
1234
			assert_noop!(Crowdfund::dissolve(Origin::signed(1), 1), Error::<Test>::InvalidFundIndex);
1235
			// Cannot dissolve a fund in progress
1236
			assert_noop!(Crowdfund::dissolve(Origin::signed(1), 0), Error::<Test>::InRetirementPeriod);
1237
1238
1239
1240
1241
1242
1243
1244

			run_to_block(10);

			// Onboard fund
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1245
				0,
1246
1247
1248
1249
1250
				vec![0]
			));
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));

			// Cannot dissolve an active fund
1251
			assert_noop!(Crowdfund::dissolve(Origin::signed(1), 0), Error::<Test>::HasActiveParachain);
1252
1253
1254
1255
1256
		});
	}

	#[test]
	fn fund_before_auction_works() {
1257
		new_test_ext().execute_with(|| {
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
			// Create a crowdfund before an auction is created
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 9));
			// Users can already contribute
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 49));
			// Fund added to NewRaise
			assert_eq!(Crowdfund::new_raise(), vec![0]);

			// Some blocks later...
			run_to_block(2);
			// Create an auction
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			// Add deploy data
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1274
				0,
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
				vec![0]
			));
			// Move to the end of auction...
			run_to_block(12);

			// Endings count incremented
			assert_eq!(Crowdfund::endings_count(), 1);

			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));

			let fund = Crowdfund::funds(0).unwrap();
			// Crowdfund is now assigned a parachain id
			assert_eq!(fund.parachain, Some(0.into()));
			// This parachain is managed by Slots
			assert_eq!(Slots::managed_ids(), vec![0.into()]);
		});
	}

	#[test]
	fn fund_across_multiple_auctions_works() {
1296
		new_test_ext().execute_with(|| {
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
			// Create an auction
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			// Create two competing crowdfunds, with end dates across multiple auctions
			// Each crowdfund is competing for the same slots, so only one can win
			assert_ok!(Crowdfund::create(Origin::signed(1), 1000, 1, 4, 30));
			assert_ok!(Crowdfund::create(Origin::signed(2), 1000, 1, 4, 30));

			// Contribute to all, but more money to 0, less to 1
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 0, 300));
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 1, 200));

			// Add deploy data to all
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(1),
				0,
				<Test as system::Trait>::Hash::default(),
1313
				0,
1314
1315
1316
1317
1318
1319
				vec![0]
			));
			assert_ok!(Crowdfund::fix_deploy_data(
				Origin::signed(2),
				1,
				<Test as system::Trait>::Hash::default(),
1320
				0,
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
				vec![0]
			));

			// End the current auction, fund 0 wins!
			run_to_block(10);
			assert_eq!(Crowdfund::endings_count(), 1);
			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(1), 0, 0.into()));
			let fund = Crowdfund::funds(0).unwrap();
			// Crowdfund is now assigned a parachain id
			assert_eq!(fund.parachain, Some(0.into()));
			// This parachain is managed by Slots
			assert_eq!(Slots::managed_ids(), vec![0.into()]);

			// Create a second auction
			assert_ok!(Slots::new_auction(Origin::ROOT, 5, 1));
			// Contribute to existing funds add to NewRaise
			assert_ok!(Crowdfund::contribute(Origin::signed(1), 1, 10));

			// End the current auction, fund 1 wins!
			run_to_block(20);
			assert_eq!(Crowdfund::endings_count(), 2);
			// Onboard crowdfund
			assert_ok!(Crowdfund::onboard(Origin::signed(2), 1, 1.into()));
			let fund = Crowdfund::funds(1).unwrap();
			// Crowdfund is now assigned a parachain id
			assert_eq!(fund.parachain, Some(1.into()));
			// This parachain is managed by Slots
			assert_eq!(Slots::managed_ids(), vec![0.into(), 1.into()]);
		});
	}
}