referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
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
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
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
969
970
971
972
973
974
975
976
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Democracy pallet benchmarking.

#![cfg(feature = "runtime-benchmarks")]

use super::*;

use frame_benchmarking::v2::*;
use frame_support::{
	assert_noop, assert_ok,
	traits::{Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable},
};
use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
use sp_runtime::{traits::Bounded, BoundedVec};

use crate::Pallet as Democracy;

const REFERENDUM_COUNT_HINT: u32 = 10;
const SEED: u32 = 0;

fn funded_account<T: Config>(name: &'static str, index: u32) -> T::AccountId {
	let caller: T::AccountId = account(name, index, SEED);
	// Give the account half of the maximum value of the `Balance` type.
	// Otherwise some transfers will fail with an overflow error.
	T::Currency::make_free_balance_be(&caller, BalanceOf::<T>::max_value() / 2u32.into());
	caller
}

fn make_proposal<T: Config>(n: u32) -> BoundedCallOf<T> {
	let call: CallOf<T> = frame_system::Call::remark { remark: n.encode() }.into();
	<T as Config>::Preimages::bound(call).unwrap()
}

fn add_proposal<T: Config>(n: u32) -> Result<T::Hash, &'static str> {
	let other = funded_account::<T>("proposer", n);
	let value = T::MinimumDeposit::get();
	let proposal = make_proposal::<T>(n);
	Democracy::<T>::propose(RawOrigin::Signed(other).into(), proposal.clone(), value)?;
	Ok(proposal.hash())
}

// add a referendum with a metadata.
fn add_referendum<T: Config>(n: u32) -> (ReferendumIndex, T::Hash, T::Hash) {
	let vote_threshold = VoteThreshold::SimpleMajority;
	let proposal = make_proposal::<T>(n);
	let hash = proposal.hash();
	let index = Democracy::<T>::inject_referendum(
		T::LaunchPeriod::get(),
		proposal,
		vote_threshold,
		0u32.into(),
	);
	let preimage_hash = note_preimage::<T>();
	MetadataOf::<T>::insert(crate::MetadataOwner::Referendum(index), preimage_hash);
	(index, hash, preimage_hash)
}

fn account_vote<T: Config>(b: BalanceOf<T>) -> AccountVote<BalanceOf<T>> {
	let v = Vote { aye: true, conviction: Conviction::Locked1x };

	AccountVote::Standard { vote: v, balance: b }
}

fn assert_last_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
	frame_system::Pallet::<T>::assert_last_event(generic_event.into());
}

fn assert_has_event<T: Config>(generic_event: <T as Config>::RuntimeEvent) {
	frame_system::Pallet::<T>::assert_has_event(generic_event.into());
}

// note a new preimage.
fn note_preimage<T: Config>() -> T::Hash {
	use alloc::borrow::Cow;
	use core::sync::atomic::{AtomicU8, Ordering};
	// note a new preimage on every function invoke.
	static COUNTER: AtomicU8 = AtomicU8::new(0);
	let data = Cow::from(vec![COUNTER.fetch_add(1, Ordering::Relaxed)]);
	let hash = <T as Config>::Preimages::note(data).unwrap();
	hash
}

#[benchmarks]
mod benchmarks {
	use super::*;

	#[benchmark]
	fn propose() -> Result<(), BenchmarkError> {
		let p = T::MaxProposals::get();

		for i in 0..(p - 1) {
			add_proposal::<T>(i)?;
		}

		let caller = funded_account::<T>("caller", 0);
		let proposal = make_proposal::<T>(0);
		let value = T::MinimumDeposit::get();
		whitelist_account!(caller);

		#[extrinsic_call]
		_(RawOrigin::Signed(caller), proposal, value);

		assert_eq!(PublicProps::<T>::get().len(), p as usize, "Proposals not created.");
		Ok(())
	}

	#[benchmark]
	fn second() -> Result<(), BenchmarkError> {
		let caller = funded_account::<T>("caller", 0);
		add_proposal::<T>(0)?;

		// Create s existing "seconds"
		// we must reserve one deposit for the `proposal` and one for our benchmarked `second` call.
		for i in 0..T::MaxDeposits::get() - 2 {
			let seconder = funded_account::<T>("seconder", i);
			Democracy::<T>::second(RawOrigin::Signed(seconder).into(), 0)?;
		}

		let deposits = DepositOf::<T>::get(0).ok_or("Proposal not created")?;
		assert_eq!(deposits.0.len(), (T::MaxDeposits::get() - 1) as usize, "Seconds not recorded");
		whitelist_account!(caller);

		#[extrinsic_call]
		_(RawOrigin::Signed(caller), 0);

		let deposits = DepositOf::<T>::get(0).ok_or("Proposal not created")?;
		assert_eq!(
			deposits.0.len(),
			(T::MaxDeposits::get()) as usize,
			"`second` benchmark did not work"
		);
		Ok(())
	}

	#[benchmark]
	fn vote_new() -> Result<(), BenchmarkError> {
		let caller = funded_account::<T>("caller", 0);
		let account_vote = account_vote::<T>(100u32.into());

		// We need to create existing direct votes
		for i in 0..T::MaxVotes::get() - 1 {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(caller.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}
		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), (T::MaxVotes::get() - 1) as usize, "Votes were not recorded.");

		let ref_index = add_referendum::<T>(T::MaxVotes::get() - 1).0;
		whitelist_account!(caller);

		#[extrinsic_call]
		vote(RawOrigin::Signed(caller.clone()), ref_index, account_vote);

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};

		assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Vote was not recorded.");
		Ok(())
	}

	#[benchmark]
	fn vote_existing() -> Result<(), BenchmarkError> {
		let caller = funded_account::<T>("caller", 0);
		let account_vote = account_vote::<T>(100u32.into());

		// We need to create existing direct votes
		for i in 0..T::MaxVotes::get() {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(caller.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}
		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Votes were not recorded.");

		// Change vote from aye to nay
		let nay = Vote { aye: false, conviction: Conviction::Locked1x };
		let new_vote = AccountVote::Standard { vote: nay, balance: 1000u32.into() };
		let ref_index = ReferendumCount::<T>::get() - 1;

		// This tests when a user changes a vote
		whitelist_account!(caller);

		#[extrinsic_call]
		vote(RawOrigin::Signed(caller.clone()), ref_index, new_vote);

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Vote was incorrectly added");
		let referendum_info =
			ReferendumInfoOf::<T>::get(ref_index).ok_or("referendum doesn't exist")?;
		let tally = match referendum_info {
			ReferendumInfo::Ongoing(r) => r.tally,
			_ => return Err("referendum not ongoing".into()),
		};
		assert_eq!(tally.nays, 1000u32.into(), "changed vote was not recorded");
		Ok(())
	}

	#[benchmark]
	fn emergency_cancel() -> Result<(), BenchmarkError> {
		let origin = T::CancellationOrigin::try_successful_origin()
			.map_err(|_| BenchmarkError::Weightless)?;
		let (ref_index, _, preimage_hash) = add_referendum::<T>(0);
		assert_ok!(Democracy::<T>::referendum_status(ref_index));

		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, ref_index);
		// Referendum has been canceled
		assert_noop!(Democracy::<T>::referendum_status(ref_index), Error::<T>::ReferendumInvalid,);
		assert_last_event::<T>(
			crate::Event::MetadataCleared {
				owner: MetadataOwner::Referendum(ref_index),
				hash: preimage_hash,
			}
			.into(),
		);
		Ok(())
	}

	#[benchmark]
	fn blacklist() -> Result<(), BenchmarkError> {
		// Place our proposal at the end to make sure it's worst case.
		for i in 0..T::MaxProposals::get() - 1 {
			add_proposal::<T>(i)?;
		}
		// We should really add a lot of seconds here, but we're not doing it elsewhere.

		// Add a referendum of our proposal.
		let (ref_index, hash, preimage_hash) = add_referendum::<T>(0);
		assert_ok!(Democracy::<T>::referendum_status(ref_index));
		// Place our proposal in the external queue, too.
		assert_ok!(Democracy::<T>::external_propose(
			T::ExternalOrigin::try_successful_origin()
				.expect("ExternalOrigin has no successful origin required for the benchmark"),
			make_proposal::<T>(0)
		));
		let origin =
			T::BlacklistOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, hash, Some(ref_index));

		// Referendum has been canceled
		assert_noop!(Democracy::<T>::referendum_status(ref_index), Error::<T>::ReferendumInvalid);
		assert_has_event::<T>(
			crate::Event::MetadataCleared {
				owner: MetadataOwner::Referendum(ref_index),
				hash: preimage_hash,
			}
			.into(),
		);
		Ok(())
	}

	// Worst case scenario, we external propose a previously blacklisted proposal
	#[benchmark]
	fn external_propose() -> Result<(), BenchmarkError> {
		let origin =
			T::ExternalOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
		let proposal = make_proposal::<T>(0);
		// Add proposal to blacklist with block number 0

		let addresses: BoundedVec<_, _> = (0..(T::MaxBlacklisted::get() - 1))
			.into_iter()
			.map(|i| account::<T::AccountId>("blacklist", i, SEED))
			.collect::<Vec<_>>()
			.try_into()
			.unwrap();
		Blacklist::<T>::insert(proposal.hash(), (BlockNumberFor::<T>::zero(), addresses));
		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, proposal);

		// External proposal created
		ensure!(NextExternal::<T>::exists(), "External proposal didn't work");
		Ok(())
	}

	#[benchmark]
	fn external_propose_majority() -> Result<(), BenchmarkError> {
		let origin = T::ExternalMajorityOrigin::try_successful_origin()
			.map_err(|_| BenchmarkError::Weightless)?;
		let proposal = make_proposal::<T>(0);
		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, proposal);

		// External proposal created
		ensure!(NextExternal::<T>::exists(), "External proposal didn't work");
		Ok(())
	}

	#[benchmark]
	fn external_propose_default() -> Result<(), BenchmarkError> {
		let origin = T::ExternalDefaultOrigin::try_successful_origin()
			.map_err(|_| BenchmarkError::Weightless)?;
		let proposal = make_proposal::<T>(0);
		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, proposal);

		// External proposal created
		ensure!(NextExternal::<T>::exists(), "External proposal didn't work");
		Ok(())
	}

	#[benchmark]
	fn fast_track() -> Result<(), BenchmarkError> {
		let origin_propose = T::ExternalDefaultOrigin::try_successful_origin()
			.expect("ExternalDefaultOrigin has no successful origin required for the benchmark");
		let proposal = make_proposal::<T>(0);
		let proposal_hash = proposal.hash();
		Democracy::<T>::external_propose_default(origin_propose.clone(), proposal)?;
		// Set metadata to the external proposal.
		let preimage_hash = note_preimage::<T>();
		assert_ok!(Democracy::<T>::set_metadata(
			origin_propose,
			MetadataOwner::External,
			Some(preimage_hash)
		));
		// NOTE: Instant origin may invoke a little bit more logic, but may not always succeed.
		let origin_fast_track =
			T::FastTrackOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
		let voting_period = T::FastTrackVotingPeriod::get();
		let delay = 0u32;
		#[extrinsic_call]
		_(origin_fast_track as T::RuntimeOrigin, proposal_hash, voting_period, delay.into());

		assert_eq!(ReferendumCount::<T>::get(), 1, "referendum not created");
		assert_last_event::<T>(
			crate::Event::MetadataTransferred {
				prev_owner: MetadataOwner::External,
				owner: MetadataOwner::Referendum(0),
				hash: preimage_hash,
			}
			.into(),
		);
		Ok(())
	}

	#[benchmark]
	fn veto_external() -> Result<(), BenchmarkError> {
		let proposal = make_proposal::<T>(0);
		let proposal_hash = proposal.hash();

		let origin_propose = T::ExternalDefaultOrigin::try_successful_origin()
			.expect("ExternalDefaultOrigin has no successful origin required for the benchmark");
		Democracy::<T>::external_propose_default(origin_propose.clone(), proposal)?;

		let preimage_hash = note_preimage::<T>();
		assert_ok!(Democracy::<T>::set_metadata(
			origin_propose,
			MetadataOwner::External,
			Some(preimage_hash)
		));

		let mut vetoers: BoundedVec<T::AccountId, _> = Default::default();
		for i in 0..(T::MaxBlacklisted::get() - 1) {
			vetoers.try_push(account::<T::AccountId>("vetoer", i, SEED)).unwrap();
		}
		vetoers.sort();
		Blacklist::<T>::insert(proposal_hash, (BlockNumberFor::<T>::zero(), vetoers));

		let origin =
			T::VetoOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
		ensure!(NextExternal::<T>::get().is_some(), "no external proposal");
		#[extrinsic_call]
		_(origin as T::RuntimeOrigin, proposal_hash);

		assert!(NextExternal::<T>::get().is_none());
		let (_, new_vetoers) = Blacklist::<T>::get(&proposal_hash).ok_or("no blacklist")?;
		assert_eq!(new_vetoers.len(), T::MaxBlacklisted::get() as usize, "vetoers not added");
		Ok(())
	}

	#[benchmark]
	fn cancel_proposal() -> Result<(), BenchmarkError> {
		// Place our proposal at the end to make sure it's worst case.
		for i in 0..T::MaxProposals::get() {
			add_proposal::<T>(i)?;
		}
		// Add metadata to the first proposal.
		let proposer = funded_account::<T>("proposer", 0);
		let preimage_hash = note_preimage::<T>();
		assert_ok!(Democracy::<T>::set_metadata(
			RawOrigin::Signed(proposer).into(),
			MetadataOwner::Proposal(0),
			Some(preimage_hash)
		));
		let cancel_origin = T::CancelProposalOrigin::try_successful_origin()
			.map_err(|_| BenchmarkError::Weightless)?;
		#[extrinsic_call]
		_(cancel_origin as T::RuntimeOrigin, 0);

		assert_last_event::<T>(
			crate::Event::MetadataCleared {
				owner: MetadataOwner::Proposal(0),
				hash: preimage_hash,
			}
			.into(),
		);
		Ok(())
	}

	#[benchmark]
	fn cancel_referendum() -> Result<(), BenchmarkError> {
		let (ref_index, _, preimage_hash) = add_referendum::<T>(0);
		#[extrinsic_call]
		_(RawOrigin::Root, ref_index);

		assert_last_event::<T>(
			crate::Event::MetadataCleared {
				owner: MetadataOwner::Referendum(0),
				hash: preimage_hash,
			}
			.into(),
		);
		Ok(())
	}

	#[benchmark(extra)]
	fn on_initialize_external(r: Linear<0, REFERENDUM_COUNT_HINT>) -> Result<(), BenchmarkError> {
		for i in 0..r {
			add_referendum::<T>(i);
		}

		assert_eq!(ReferendumCount::<T>::get(), r, "referenda not created");

		// Launch external
		LastTabledWasExternal::<T>::put(false);

		let origin = T::ExternalMajorityOrigin::try_successful_origin()
			.map_err(|_| BenchmarkError::Weightless)?;
		let proposal = make_proposal::<T>(r);
		let call = Call::<T>::external_propose_majority { proposal };
		call.dispatch_bypass_filter(origin)?;
		// External proposal created
		ensure!(NextExternal::<T>::exists(), "External proposal didn't work");

		let block_number = T::LaunchPeriod::get();

		#[block]
		{
			Democracy::<T>::on_initialize(block_number);
		}

		// One extra because of next external
		assert_eq!(ReferendumCount::<T>::get(), r + 1, "referenda not created");
		ensure!(!NextExternal::<T>::exists(), "External wasn't taken");

		// All but the new next external should be finished
		for i in 0..r {
			if let Some(value) = ReferendumInfoOf::<T>::get(i) {
				match value {
					ReferendumInfo::Finished { .. } => (),
					ReferendumInfo::Ongoing(_) => return Err("Referendum was not finished".into()),
				}
			}
		}
		Ok(())
	}

	#[benchmark(extra)]
	fn on_initialize_public(
		r: Linear<0, { T::MaxVotes::get() - 1 }>,
	) -> Result<(), BenchmarkError> {
		for i in 0..r {
			add_referendum::<T>(i);
		}

		assert_eq!(ReferendumCount::<T>::get(), r, "referenda not created");

		// Launch public
		assert!(add_proposal::<T>(r).is_ok(), "proposal not created");
		LastTabledWasExternal::<T>::put(true);

		let block_number = T::LaunchPeriod::get();

		#[block]
		{
			Democracy::<T>::on_initialize(block_number);
		}

		// One extra because of next public
		assert_eq!(ReferendumCount::<T>::get(), r + 1, "proposal not accepted");

		// All should be finished
		for i in 0..r {
			if let Some(value) = ReferendumInfoOf::<T>::get(i) {
				match value {
					ReferendumInfo::Finished { .. } => (),
					ReferendumInfo::Ongoing(_) => return Err("Referendum was not finished".into()),
				}
			}
		}
		Ok(())
	}

	// No launch no maturing referenda.
	#[benchmark]
	fn on_initialize_base(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> {
		for i in 0..r {
			add_referendum::<T>(i);
		}

		for (key, mut info) in ReferendumInfoOf::<T>::iter() {
			if let ReferendumInfo::Ongoing(ref mut status) = info {
				status.end += 100u32.into();
			}
			ReferendumInfoOf::<T>::insert(key, info);
		}

		assert_eq!(ReferendumCount::<T>::get(), r, "referenda not created");
		assert_eq!(LowestUnbaked::<T>::get(), 0, "invalid referenda init");

		#[block]
		{
			Democracy::<T>::on_initialize(1u32.into());
		}

		// All should be on going
		for i in 0..r {
			if let Some(value) = ReferendumInfoOf::<T>::get(i) {
				match value {
					ReferendumInfo::Finished { .. } =>
						return Err("Referendum has been finished".into()),
					ReferendumInfo::Ongoing(_) => (),
				}
			}
		}
		Ok(())
	}

	#[benchmark]
	fn on_initialize_base_with_launch_period(
		r: Linear<0, { T::MaxVotes::get() - 1 }>,
	) -> Result<(), BenchmarkError> {
		for i in 0..r {
			add_referendum::<T>(i);
		}

		for (key, mut info) in ReferendumInfoOf::<T>::iter() {
			if let ReferendumInfo::Ongoing(ref mut status) = info {
				status.end += 100u32.into();
			}
			ReferendumInfoOf::<T>::insert(key, info);
		}

		assert_eq!(ReferendumCount::<T>::get(), r, "referenda not created");
		assert_eq!(LowestUnbaked::<T>::get(), 0, "invalid referenda init");

		let block_number = T::LaunchPeriod::get();

		#[block]
		{
			Democracy::<T>::on_initialize(block_number);
		}

		// All should be on going
		for i in 0..r {
			if let Some(value) = ReferendumInfoOf::<T>::get(i) {
				match value {
					ReferendumInfo::Finished { .. } =>
						return Err("Referendum has been finished".into()),
					ReferendumInfo::Ongoing(_) => (),
				}
			}
		}
		Ok(())
	}

	#[benchmark]
	fn delegate(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> {
		let initial_balance: BalanceOf<T> = 100u32.into();
		let delegated_balance: BalanceOf<T> = 1000u32.into();

		let caller = funded_account::<T>("caller", 0);
		// Caller will initially delegate to `old_delegate`
		let old_delegate: T::AccountId = funded_account::<T>("old_delegate", r);
		let old_delegate_lookup = T::Lookup::unlookup(old_delegate.clone());
		Democracy::<T>::delegate(
			RawOrigin::Signed(caller.clone()).into(),
			old_delegate_lookup,
			Conviction::Locked1x,
			delegated_balance,
		)?;
		let (target, balance) = match VotingOf::<T>::get(&caller) {
			Voting::Delegating { target, balance, .. } => (target, balance),
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(target, old_delegate, "delegation target didn't work");
		assert_eq!(balance, delegated_balance, "delegation balance didn't work");
		// Caller will now switch to `new_delegate`
		let new_delegate: T::AccountId = funded_account::<T>("new_delegate", r);
		let new_delegate_lookup = T::Lookup::unlookup(new_delegate.clone());
		let account_vote = account_vote::<T>(initial_balance);
		// We need to create existing direct votes for the `new_delegate`
		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(new_delegate.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}
		let votes = match VotingOf::<T>::get(&new_delegate) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), r as usize, "Votes were not recorded.");
		whitelist_account!(caller);

		#[extrinsic_call]
		_(
			RawOrigin::Signed(caller.clone()),
			new_delegate_lookup,
			Conviction::Locked1x,
			delegated_balance,
		);

		let (target, balance) = match VotingOf::<T>::get(&caller) {
			Voting::Delegating { target, balance, .. } => (target, balance),
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(target, new_delegate, "delegation target didn't work");
		assert_eq!(balance, delegated_balance, "delegation balance didn't work");
		let delegations = match VotingOf::<T>::get(&new_delegate) {
			Voting::Direct { delegations, .. } => delegations,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(delegations.capital, delegated_balance, "delegation was not recorded.");
		Ok(())
	}

	#[benchmark]
	fn undelegate(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> {
		let initial_balance: BalanceOf<T> = 100u32.into();
		let delegated_balance: BalanceOf<T> = 1000u32.into();

		let caller = funded_account::<T>("caller", 0);
		// Caller will delegate
		let the_delegate: T::AccountId = funded_account::<T>("delegate", r);
		let the_delegate_lookup = T::Lookup::unlookup(the_delegate.clone());
		Democracy::<T>::delegate(
			RawOrigin::Signed(caller.clone()).into(),
			the_delegate_lookup,
			Conviction::Locked1x,
			delegated_balance,
		)?;
		let (target, balance) = match VotingOf::<T>::get(&caller) {
			Voting::Delegating { target, balance, .. } => (target, balance),
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(target, the_delegate, "delegation target didn't work");
		assert_eq!(balance, delegated_balance, "delegation balance didn't work");
		// We need to create votes direct votes for the `delegate`
		let account_vote = account_vote::<T>(initial_balance);
		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(the_delegate.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}
		let votes = match VotingOf::<T>::get(&the_delegate) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), r as usize, "Votes were not recorded.");
		whitelist_account!(caller);

		#[extrinsic_call]
		_(RawOrigin::Signed(caller.clone()));

		// Voting should now be direct
		match VotingOf::<T>::get(&caller) {
			Voting::Direct { .. } => (),
			_ => return Err("undelegation failed".into()),
		}
		Ok(())
	}

	#[benchmark]
	fn clear_public_proposals() -> Result<(), BenchmarkError> {
		add_proposal::<T>(0)?;

		#[extrinsic_call]
		_(RawOrigin::Root);

		Ok(())
	}

	// Test when unlock will remove locks
	#[benchmark]
	fn unlock_remove(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> {
		let locker = funded_account::<T>("locker", 0);
		let locker_lookup = T::Lookup::unlookup(locker.clone());
		// Populate votes so things are locked
		let base_balance: BalanceOf<T> = 100u32.into();
		let small_vote = account_vote::<T>(base_balance);
		// Vote and immediately unvote
		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_index, small_vote)?;
			Democracy::<T>::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_index)?;
		}

		let caller = funded_account::<T>("caller", 0);
		whitelist_account!(caller);

		#[extrinsic_call]
		unlock(RawOrigin::Signed(caller), locker_lookup);

		// Note that we may want to add a `get_lock` api to actually verify
		let voting = VotingOf::<T>::get(&locker);
		assert_eq!(voting.locked_balance(), BalanceOf::<T>::zero());
		Ok(())
	}

	// Test when unlock will set a new value
	#[benchmark]
	fn unlock_set(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> {
		let locker = funded_account::<T>("locker", 0);
		let locker_lookup = T::Lookup::unlookup(locker.clone());
		// Populate votes so things are locked
		let base_balance: BalanceOf<T> = 100u32.into();
		let small_vote = account_vote::<T>(base_balance);
		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_index, small_vote)?;
		}

		// Create a big vote so lock increases
		let big_vote = account_vote::<T>(base_balance * 10u32.into());
		let ref_index = add_referendum::<T>(r).0;
		Democracy::<T>::vote(RawOrigin::Signed(locker.clone()).into(), ref_index, big_vote)?;

		let votes = match VotingOf::<T>::get(&locker) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), (r + 1) as usize, "Votes were not recorded.");

		let voting = VotingOf::<T>::get(&locker);
		assert_eq!(voting.locked_balance(), base_balance * 10u32.into());

		Democracy::<T>::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_index)?;

		let caller = funded_account::<T>("caller", 0);
		whitelist_account!(caller);

		#[extrinsic_call]
		unlock(RawOrigin::Signed(caller), locker_lookup);

		let votes = match VotingOf::<T>::get(&locker) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), r as usize, "Vote was not removed");

		let voting = VotingOf::<T>::get(&locker);
		// Note that we may want to add a `get_lock` api to actually verify
		assert_eq!(voting.locked_balance(), if r > 0 { base_balance } else { 0u32.into() });
		Ok(())
	}

	#[benchmark]
	fn remove_vote(r: Linear<1, { T::MaxVotes::get() }>) -> Result<(), BenchmarkError> {
		let caller = funded_account::<T>("caller", 0);
		let account_vote = account_vote::<T>(100u32.into());

		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(caller.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), r as usize, "Votes not created");

		let ref_index = r - 1;
		whitelist_account!(caller);

		#[extrinsic_call]
		_(RawOrigin::Signed(caller.clone()), ref_index);

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed");
		Ok(())
	}

	// Worst case is when target == caller and referendum is ongoing
	#[benchmark]
	fn remove_other_vote(r: Linear<1, { T::MaxVotes::get() }>) -> Result<(), BenchmarkError> {
		let caller = funded_account::<T>("caller", r);
		let caller_lookup = T::Lookup::unlookup(caller.clone());
		let account_vote = account_vote::<T>(100u32.into());

		for i in 0..r {
			let ref_index = add_referendum::<T>(i).0;
			Democracy::<T>::vote(
				RawOrigin::Signed(caller.clone()).into(),
				ref_index,
				account_vote,
			)?;
		}

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), r as usize, "Votes not created");

		let ref_index = r - 1;
		whitelist_account!(caller);

		#[extrinsic_call]
		_(RawOrigin::Signed(caller.clone()), caller_lookup, ref_index);

		let votes = match VotingOf::<T>::get(&caller) {
			Voting::Direct { votes, .. } => votes,
			_ => return Err("Votes are not direct".into()),
		};
		assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed");
		Ok(())
	}

	#[benchmark]
	fn set_external_metadata() -> Result<(), BenchmarkError> {
		let origin = T::ExternalOrigin::try_successful_origin()
			.expect("ExternalOrigin has no successful origin required for the benchmark");
		assert_ok!(Democracy::<T>::external_propose(origin.clone(), make_proposal::<T>(0)));
		let owner = MetadataOwner::External;
		let hash = note_preimage::<T>();

		#[extrinsic_call]
		set_metadata(origin as T::RuntimeOrigin, owner.clone(), Some(hash));

		assert_last_event::<T>(crate::Event::MetadataSet { owner, hash }.into());
		Ok(())
	}

	#[benchmark]
	fn clear_external_metadata() -> Result<(), BenchmarkError> {
		let origin = T::ExternalOrigin::try_successful_origin()
			.expect("ExternalOrigin has no successful origin required for the benchmark");
		assert_ok!(Democracy::<T>::external_propose(origin.clone(), make_proposal::<T>(0)));
		let owner = MetadataOwner::External;
		let _proposer = funded_account::<T>("proposer", 0);
		let hash = note_preimage::<T>();
		assert_ok!(Democracy::<T>::set_metadata(origin.clone(), owner.clone(), Some(hash)));

		#[extrinsic_call]
		set_metadata(origin as T::RuntimeOrigin, owner.clone(), None);

		assert_last_event::<T>(crate::Event::MetadataCleared { owner, hash }.into());
		Ok(())
	}

	#[benchmark]
	fn set_proposal_metadata() -> Result<(), BenchmarkError> {
		// Place our proposal at the end to make sure it's worst case.
		for i in 0..T::MaxProposals::get() {
			add_proposal::<T>(i)?;
		}
		let owner = MetadataOwner::Proposal(0);
		let proposer = funded_account::<T>("proposer", 0);
		let hash = note_preimage::<T>();

		#[extrinsic_call]
		set_metadata(RawOrigin::Signed(proposer), owner.clone(), Some(hash));

		assert_last_event::<T>(crate::Event::MetadataSet { owner, hash }.into());
		Ok(())
	}

	#[benchmark]
	fn clear_proposal_metadata() -> Result<(), BenchmarkError> {
		// Place our proposal at the end to make sure it's worst case.
		for i in 0..T::MaxProposals::get() {
			add_proposal::<T>(i)?;
		}
		let proposer = funded_account::<T>("proposer", 0);
		let owner = MetadataOwner::Proposal(0);
		let hash = note_preimage::<T>();
		assert_ok!(Democracy::<T>::set_metadata(
			RawOrigin::Signed(proposer.clone()).into(),
			owner.clone(),
			Some(hash)
		));

		#[extrinsic_call]
		set_metadata::<T::RuntimeOrigin>(RawOrigin::Signed(proposer), owner.clone(), None);

		assert_last_event::<T>(crate::Event::MetadataCleared { owner, hash }.into());
		Ok(())
	}

	#[benchmark]
	fn set_referendum_metadata() -> Result<(), BenchmarkError> {
		// create not ongoing referendum.
		ReferendumInfoOf::<T>::insert(
			0,
			ReferendumInfo::Finished { end: BlockNumberFor::<T>::zero(), approved: true },
		);
		let owner = MetadataOwner::Referendum(0);
		let _caller = funded_account::<T>("caller", 0);
		let hash = note_preimage::<T>();

		#[extrinsic_call]
		set_metadata::<T::RuntimeOrigin>(RawOrigin::Root, owner.clone(), Some(hash));

		assert_last_event::<T>(crate::Event::MetadataSet { owner, hash }.into());
		Ok(())
	}

	#[benchmark]
	fn clear_referendum_metadata() -> Result<(), BenchmarkError> {
		// create not ongoing referendum.
		ReferendumInfoOf::<T>::insert(
			0,
			ReferendumInfo::Finished { end: BlockNumberFor::<T>::zero(), approved: true },
		);
		let owner = MetadataOwner::Referendum(0);
		let hash = note_preimage::<T>();
		MetadataOf::<T>::insert(owner.clone(), hash);
		let caller = funded_account::<T>("caller", 0);

		#[extrinsic_call]
		set_metadata::<T::RuntimeOrigin>(RawOrigin::Signed(caller), owner.clone(), None);

		assert_last_event::<T>(crate::Event::MetadataCleared { owner, hash }.into());
		Ok(())
	}

	impl_benchmark_test_suite!(Democracy, crate::tests::new_test_ext(), crate::tests::Test);
}