1
// Copyright 2019-2022 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

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

            
17
#![cfg_attr(not(feature = "std"), no_std)]
18

            
19
use account::SYSTEM_ACCOUNT_SIZE;
20
use fp_evm::PrecompileHandle;
21
use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo};
22
use frame_support::traits::{Currency, Polling};
23
use frame_system::pallet_prelude::BlockNumberFor;
24
use pallet_conviction_voting::Call as ConvictionVotingCall;
25
use pallet_conviction_voting::{
26
	AccountVote, Casting, ClassLocksFor, Conviction, Delegating, Tally, TallyOf, Vote, Voting,
27
	VotingFor,
28
};
29
use pallet_evm::{AddressMapping, Log};
30
use precompile_utils::prelude::*;
31
use sp_core::{Get, MaxEncodedLen, H160, H256, U256};
32
use sp_runtime::traits::{Dispatchable, StaticLookup};
33
use sp_std::marker::PhantomData;
34
use sp_std::vec::Vec;
35

            
36
#[cfg(test)]
37
mod mock;
38
#[cfg(test)]
39
mod tests;
40

            
41
type BalanceOf<Runtime> = <<Runtime as pallet_conviction_voting::Config>::Currency as Currency<
42
	<Runtime as frame_system::Config>::AccountId,
43
>>::Balance;
44
type IndexOf<Runtime> = <<Runtime as pallet_conviction_voting::Config>::Polls as Polling<
45
	Tally<
46
		<<Runtime as pallet_conviction_voting::Config>::Currency as Currency<
47
			<Runtime as frame_system::Config>::AccountId,
48
		>>::Balance,
49
		<Runtime as pallet_conviction_voting::Config>::MaxTurnout,
50
	>,
51
>>::Index;
52
type ClassOf<Runtime> = <<Runtime as pallet_conviction_voting::Config>::Polls as Polling<
53
	Tally<
54
		<<Runtime as pallet_conviction_voting::Config>::Currency as Currency<
55
			<Runtime as frame_system::Config>::AccountId,
56
		>>::Balance,
57
		<Runtime as pallet_conviction_voting::Config>::MaxTurnout,
58
	>,
59
>>::Class;
60
type VotingOf<Runtime> = Voting<
61
	BalanceOf<Runtime>,
62
	<Runtime as frame_system::Config>::AccountId,
63
	BlockNumberFor<Runtime>,
64
	<<Runtime as pallet_conviction_voting::Config>::Polls as Polling<TallyOf<Runtime>>>::Index,
65
	<Runtime as pallet_conviction_voting::Config>::MaxVotes,
66
>;
67

            
68
/// Solidity selector of the Vote log, which is the Keccak of the Log signature.
69
pub(crate) const SELECTOR_LOG_VOTED: [u8; 32] =
70
	keccak256!("Voted(uint32,address,bool,uint256,uint8)");
71

            
72
/// Solidity selector of the Vote Split log, which is the Keccak of the Log signature.
73
pub(crate) const SELECTOR_LOG_VOTE_SPLIT: [u8; 32] =
74
	keccak256!("VoteSplit(uint32,address,uint256,uint256)");
75

            
76
/// Solidity selector of the Vote Split Abstained log, which is the Keccak of the Log signature.
77
pub(crate) const SELECTOR_LOG_VOTE_SPLIT_ABSTAINED: [u8; 32] =
78
	keccak256!("VoteSplitAbstained(uint32,address,uint256,uint256,uint256)");
79

            
80
/// Solidity selector of the VoteRemove log, which is the Keccak of the Log signature.
81
pub(crate) const SELECTOR_LOG_VOTE_REMOVED: [u8; 32] = keccak256!("VoteRemoved(uint32,address)");
82

            
83
/// Solidity selector of the SomeVoteRemove log, which is the Keccak of the Log signature.
84
pub(crate) const SELECTOR_LOG_VOTE_REMOVED_FOR_TRACK: [u8; 32] =
85
	keccak256!("VoteRemovedForTrack(uint32,uint16,address)");
86

            
87
/// Solidity selector of the VoteRemoveOther log, which is the Keccak of the Log signature.
88
pub(crate) const SELECTOR_LOG_VOTE_REMOVED_OTHER: [u8; 32] =
89
	keccak256!("VoteRemovedOther(uint32,address,address,uint16)");
90

            
91
/// Solidity selector of the Delegate log, which is the Keccak of the Log signature.
92
pub(crate) const SELECTOR_LOG_DELEGATED: [u8; 32] =
93
	keccak256!("Delegated(uint16,address,address,uint256,uint8)");
94

            
95
/// Solidity selector of the Undelegate log, which is the Keccak of the Log signature.
96
pub(crate) const SELECTOR_LOG_UNDELEGATED: [u8; 32] = keccak256!("Undelegated(uint16,address)");
97

            
98
/// Solidity selector of the Unlock log, which is the Keccak of the Log signature.
99
pub(crate) const SELECTOR_LOG_UNLOCKED: [u8; 32] = keccak256!("Unlocked(uint16,address)");
100

            
101
/// A precompile to wrap the functionality from pallet-conviction-voting.
102
pub struct ConvictionVotingPrecompile<Runtime>(PhantomData<Runtime>);
103

            
104
137
#[precompile_utils::precompile]
105
impl<Runtime> ConvictionVotingPrecompile<Runtime>
106
where
107
	Runtime: pallet_conviction_voting::Config + pallet_evm::Config + frame_system::Config,
108
	BalanceOf<Runtime>: TryFrom<U256> + Into<U256>,
109
	<Runtime as frame_system::Config>::RuntimeCall:
110
		Dispatchable<PostInfo = PostDispatchInfo> + GetDispatchInfo,
111
	<<Runtime as frame_system::Config>::RuntimeCall as Dispatchable>::RuntimeOrigin:
112
		From<Option<Runtime::AccountId>>,
113
	Runtime::AccountId: Into<H160>,
114
	<Runtime as frame_system::Config>::RuntimeCall: From<ConvictionVotingCall<Runtime>>,
115
	IndexOf<Runtime>: TryFrom<u32> + TryInto<u32>,
116
	ClassOf<Runtime>: TryFrom<u16> + TryInto<u16>,
117
	<Runtime as pallet_conviction_voting::Config>::Polls: Polling<
118
		Tally<
119
			<<Runtime as pallet_conviction_voting::Config>::Currency as Currency<
120
				<Runtime as frame_system::Config>::AccountId,
121
			>>::Balance,
122
			<Runtime as pallet_conviction_voting::Config>::MaxTurnout,
123
		>,
124
	>,
125
{
126
	/// Internal helper function for vote* extrinsics exposed in this precompile.
127
12
	fn vote(
128
12
		handle: &mut impl PrecompileHandle,
129
12
		poll_index: u32,
130
12
		vote: AccountVote<U256>,
131
12
	) -> EvmResult {
132
12
		let caller = handle.context().caller;
133
12
		let (poll_index, vote, event) = Self::log_vote_event(handle, poll_index, vote)?;
134

            
135
12
		let origin = Runtime::AddressMapping::into_account_id(caller);
136
12
		let call = ConvictionVotingCall::<Runtime>::vote { poll_index, vote }.into();
137
12

            
138
12
		<RuntimeHelper<Runtime>>::try_dispatch(handle, Some(origin).into(), call, 0)?;
139

            
140
12
		event.record(handle)?;
141

            
142
12
		Ok(())
143
12
	}
144

            
145
	/// Vote yes in a poll.
146
	///
147
	/// Parameters:
148
	/// * poll_index: Index of poll
149
	/// * vote_amount: Balance locked for vote
150
	/// * conviction: Conviction multiplier for length of vote lock
151
	#[precompile::public("voteYes(uint32,uint256,uint8)")]
152
7
	fn vote_yes(
153
7
		handle: &mut impl PrecompileHandle,
154
7
		poll_index: u32,
155
7
		vote_amount: U256,
156
7
		conviction: u8,
157
7
	) -> EvmResult {
158
7
		Self::vote(
159
7
			handle,
160
7
			poll_index,
161
7
			AccountVote::Standard {
162
7
				vote: Vote {
163
7
					aye: true,
164
7
					conviction: Self::u8_to_conviction(conviction).in_field("conviction")?,
165
				},
166
7
				balance: vote_amount,
167
			},
168
		)
169
7
	}
170

            
171
	/// Vote no in a poll.
172
	///
173
	/// Parameters:
174
	/// * poll_index: Index of poll
175
	/// * vote_amount: Balance locked for vote
176
	/// * conviction: Conviction multiplier for length of vote lock
177
	#[precompile::public("voteNo(uint32,uint256,uint8)")]
178
1
	fn vote_no(
179
1
		handle: &mut impl PrecompileHandle,
180
1
		poll_index: u32,
181
1
		vote_amount: U256,
182
1
		conviction: u8,
183
1
	) -> EvmResult {
184
1
		Self::vote(
185
1
			handle,
186
1
			poll_index,
187
1
			AccountVote::Standard {
188
1
				vote: Vote {
189
1
					aye: false,
190
1
					conviction: Self::u8_to_conviction(conviction).in_field("conviction")?,
191
				},
192
1
				balance: vote_amount,
193
			},
194
		)
195
1
	}
196

            
197
	/// Vote split in a poll.
198
	///
199
	/// Parameters:
200
	/// * poll_index: Index of poll
201
	/// * aye: Balance locked for aye vote
202
	/// * nay: Balance locked for nay vote
203
	#[precompile::public("voteSplit(uint32,uint256,uint256)")]
204
2
	fn vote_split(
205
2
		handle: &mut impl PrecompileHandle,
206
2
		poll_index: u32,
207
2
		aye: U256,
208
2
		nay: U256,
209
2
	) -> EvmResult {
210
2
		Self::vote(handle, poll_index, AccountVote::Split { aye, nay })
211
2
	}
212

            
213
	/// Vote split in a poll.
214
	///
215
	/// Parameters:
216
	/// * poll_index: Index of poll
217
	/// * aye: Balance locked for aye vote
218
	/// * nay: Balance locked for nay vote
219
	#[precompile::public("voteSplitAbstain(uint32,uint256,uint256,uint256)")]
220
2
	fn vote_split_abstain(
221
2
		handle: &mut impl PrecompileHandle,
222
2
		poll_index: u32,
223
2
		aye: U256,
224
2
		nay: U256,
225
2
		abstain: U256,
226
2
	) -> EvmResult {
227
2
		Self::vote(
228
2
			handle,
229
2
			poll_index,
230
2
			AccountVote::SplitAbstain { aye, nay, abstain },
231
2
		)
232
2
	}
233

            
234
	#[precompile::public("removeVote(uint32)")]
235
2
	fn remove_vote(handle: &mut impl PrecompileHandle, poll_index: u32) -> EvmResult {
236
2
		Self::rm_vote(handle, poll_index, None)
237
2
	}
238

            
239
	#[precompile::public("removeVoteForTrack(uint32,uint16)")]
240
1
	fn remove_vote_for_track(
241
1
		handle: &mut impl PrecompileHandle,
242
1
		poll_index: u32,
243
1
		track_id: u16,
244
1
	) -> EvmResult {
245
1
		Self::rm_vote(handle, poll_index, Some(track_id))
246
1
	}
247

            
248
	/// Helper function for common code between remove_vote and remove_some_vote
249
3
	fn rm_vote(
250
3
		handle: &mut impl PrecompileHandle,
251
3
		poll_index: u32,
252
3
		maybe_track_id: Option<u16>,
253
3
	) -> EvmResult {
254
3
		let caller = handle.context().caller;
255
3
		let index = Self::u32_to_index(poll_index).in_field("pollIndex")?;
256
3
		let (event, class) = if let Some(track_id) = maybe_track_id {
257
1
			log::trace!(
258
				target: "conviction-voting-precompile",
259
				"Removing vote from poll {:?} for track {:?}",
260
				index,
261
				track_id,
262
			);
263
			(
264
1
				log2(
265
1
					handle.context().address,
266
1
					SELECTOR_LOG_VOTE_REMOVED_FOR_TRACK,
267
1
					H256::from_low_u64_be(poll_index as u64),
268
1
					solidity::encode_event_data((track_id, Address(caller))),
269
1
				),
270
1
				Some(Self::u16_to_track_id(track_id).in_field("trackId")?),
271
			)
272
		} else {
273
2
			log::trace!(
274
				target: "conviction-voting-precompile",
275
				"Removing vote from poll {:?}",
276
				index,
277
			);
278
2
			(
279
2
				log2(
280
2
					handle.context().address,
281
2
					SELECTOR_LOG_VOTE_REMOVED,
282
2
					H256::from_low_u64_be(poll_index as u64),
283
2
					solidity::encode_event_data(Address(caller)),
284
2
				),
285
2
				None,
286
2
			)
287
		};
288

            
289
3
		let origin = Runtime::AddressMapping::into_account_id(caller);
290
3
		let call = ConvictionVotingCall::<Runtime>::remove_vote { class, index };
291
3

            
292
3
		RuntimeHelper::<Runtime>::try_dispatch(handle, Some(origin).into(), call, 0)?;
293

            
294
3
		event.record(handle)?;
295

            
296
3
		Ok(())
297
3
	}
298

            
299
	#[precompile::public("removeOtherVote(address,uint16,uint32)")]
300
1
	fn remove_other_vote(
301
1
		handle: &mut impl PrecompileHandle,
302
1
		target: Address,
303
1
		track_id: u16,
304
1
		poll_index: u32,
305
1
	) -> EvmResult {
306
1
		let caller = handle.context().caller;
307
1

            
308
1
		let event = log2(
309
1
			handle.context().address,
310
1
			SELECTOR_LOG_VOTE_REMOVED_OTHER,
311
1
			H256::from_low_u64_be(poll_index as u64), // poll index,
312
1
			solidity::encode_event_data((Address(caller), target, track_id)),
313
1
		);
314
1
		handle.record_log_costs(&[&event])?;
315

            
316
1
		let class = Self::u16_to_track_id(track_id).in_field("trackId")?;
317
1
		let index = Self::u32_to_index(poll_index).in_field("pollIndex")?;
318

            
319
1
		let target = Runtime::AddressMapping::into_account_id(target.into());
320
1
		let target: <Runtime::Lookup as StaticLookup>::Source =
321
1
			Runtime::Lookup::unlookup(target.clone());
322
1

            
323
1
		log::trace!(
324
			target: "conviction-voting-precompile",
325
			"Removing other vote from poll {:?}",
326
			index
327
		);
328

            
329
1
		let origin = Runtime::AddressMapping::into_account_id(caller);
330
1
		let call = ConvictionVotingCall::<Runtime>::remove_other_vote {
331
1
			target,
332
1
			class,
333
1
			index,
334
1
		};
335
1

            
336
1
		RuntimeHelper::<Runtime>::try_dispatch(handle, Some(origin).into(), call, 0)?;
337

            
338
1
		event.record(handle)?;
339

            
340
1
		Ok(())
341
1
	}
342

            
343
	#[precompile::public("delegate(uint16,address,uint8,uint256)")]
344
1
	fn delegate(
345
1
		handle: &mut impl PrecompileHandle,
346
1
		track_id: u16,
347
1
		representative: Address,
348
1
		conviction: u8,
349
1
		amount: U256,
350
1
	) -> EvmResult {
351
1
		let caller = handle.context().caller;
352
1

            
353
1
		let event = log2(
354
1
			handle.context().address,
355
1
			SELECTOR_LOG_DELEGATED,
356
1
			H256::from_low_u64_be(track_id as u64), // track id,
357
1
			solidity::encode_event_data((Address(caller), representative, amount, conviction)),
358
1
		);
359
1
		handle.record_log_costs(&[&event])?;
360

            
361
1
		let class = Self::u16_to_track_id(track_id).in_field("trackId")?;
362
1
		let amount = Self::u256_to_amount(amount).in_field("amount")?;
363
1
		let conviction = Self::u8_to_conviction(conviction).in_field("conviction")?;
364

            
365
1
		log::trace!(target: "conviction-voting-precompile",
366
			"Delegating vote to {:?} with balance {:?} and conviction {:?}",
367
			representative, amount, conviction
368
		);
369

            
370
1
		let representative = Runtime::AddressMapping::into_account_id(representative.into());
371
1
		let to: <Runtime::Lookup as StaticLookup>::Source =
372
1
			Runtime::Lookup::unlookup(representative.clone());
373
1
		let origin = Runtime::AddressMapping::into_account_id(caller);
374
1
		let call = ConvictionVotingCall::<Runtime>::delegate {
375
1
			class,
376
1
			to,
377
1
			conviction,
378
1
			balance: amount,
379
1
		};
380
1

            
381
1
		RuntimeHelper::<Runtime>::try_dispatch(
382
1
			handle,
383
1
			Some(origin).into(),
384
1
			call,
385
1
			SYSTEM_ACCOUNT_SIZE,
386
1
		)?;
387

            
388
1
		event.record(handle)?;
389

            
390
1
		Ok(())
391
1
	}
392

            
393
	#[precompile::public("undelegate(uint16)")]
394
1
	fn undelegate(handle: &mut impl PrecompileHandle, track_id: u16) -> EvmResult {
395
1
		let caller = handle.context().caller;
396
1

            
397
1
		let event = log2(
398
1
			handle.context().address,
399
1
			SELECTOR_LOG_UNDELEGATED,
400
1
			H256::from_low_u64_be(track_id as u64), // track id,
401
1
			solidity::encode_event_data(Address(caller)),
402
1
		);
403
1
		handle.record_log_costs(&[&event])?;
404

            
405
1
		let class = Self::u16_to_track_id(track_id).in_field("trackId")?;
406
1
		let origin = Runtime::AddressMapping::into_account_id(caller);
407
1
		let call = ConvictionVotingCall::<Runtime>::undelegate { class };
408
1

            
409
1
		RuntimeHelper::<Runtime>::try_dispatch(handle, Some(origin).into(), call, 0)?;
410

            
411
1
		event.record(handle)?;
412

            
413
1
		Ok(())
414
1
	}
415

            
416
	#[precompile::public("unlock(uint16,address)")]
417
1
	fn unlock(handle: &mut impl PrecompileHandle, track_id: u16, target: Address) -> EvmResult {
418
1
		let class = Self::u16_to_track_id(track_id).in_field("trackId")?;
419

            
420
1
		let event = log2(
421
1
			handle.context().address,
422
1
			SELECTOR_LOG_UNLOCKED,
423
1
			H256::from_low_u64_be(track_id as u64), // track id,
424
1
			solidity::encode_event_data(target),
425
1
		);
426
1
		handle.record_log_costs(&[&event])?;
427

            
428
1
		let target: H160 = target.into();
429
1
		let target = Runtime::AddressMapping::into_account_id(target);
430
1
		let target: <Runtime::Lookup as StaticLookup>::Source =
431
1
			Runtime::Lookup::unlookup(target.clone());
432
1

            
433
1
		log::trace!(
434
			target: "conviction-voting-precompile",
435
			"Unlocking conviction-voting tokens for {:?}", target
436
		);
437

            
438
1
		let origin = Runtime::AddressMapping::into_account_id(handle.context().caller);
439
1
		let call = ConvictionVotingCall::<Runtime>::unlock { class, target };
440
1

            
441
1
		RuntimeHelper::<Runtime>::try_dispatch(handle, Some(origin).into(), call, 0)?;
442

            
443
1
		event.record(handle)?;
444

            
445
1
		Ok(())
446
1
	}
447

            
448
	#[precompile::public("votingFor(address,uint16)")]
449
	#[precompile::view]
450
3
	fn voting_for(
451
3
		handle: &mut impl PrecompileHandle,
452
3
		who: Address,
453
3
		track_id: u16,
454
3
	) -> EvmResult<OutputVotingFor> {
455
3
		// VotingFor: Twox64Concat(8) + 20 + Twox64Concat(8) + TransInfo::Id(2) + VotingOf
456
3
		handle.record_db_read::<Runtime>(38 + VotingOf::<Runtime>::max_encoded_len())?;
457

            
458
3
		let who = Runtime::AddressMapping::into_account_id(who.into());
459
3
		let class = Self::u16_to_track_id(track_id).in_field("trackId")?;
460

            
461
3
		let voting = <VotingFor<Runtime>>::get(&who, &class);
462
3

            
463
3
		Ok(Self::voting_to_output(voting)?)
464
3
	}
465

            
466
	#[precompile::public("classLocksFor(address)")]
467
	#[precompile::view]
468
1
	fn class_locks_for(
469
1
		handle: &mut impl PrecompileHandle,
470
1
		who: Address,
471
1
	) -> EvmResult<Vec<OutputClassLock>> {
472
1
		// ClassLocksFor: Twox64Concat(8) + 20 + BoundedVec(TransInfo::Id(2) * ClassCountOf)
473
1
		handle.record_db_read::<Runtime>(
474
1
			28 + ((2 * frame_support::traits::ClassCountOf::<
475
1
				<Runtime as pallet_conviction_voting::Config>::Polls,
476
1
				Tally<
477
1
					<<Runtime as pallet_conviction_voting::Config>::Currency as Currency<
478
1
						<Runtime as frame_system::Config>::AccountId,
479
1
					>>::Balance,
480
1
					<Runtime as pallet_conviction_voting::Config>::MaxTurnout,
481
1
				>,
482
1
			>::get()) as usize),
483
1
		)?;
484

            
485
1
		let who = Runtime::AddressMapping::into_account_id(who.into());
486
1

            
487
1
		let class_locks_for = <ClassLocksFor<Runtime>>::get(&who);
488
1
		let mut output = Vec::new();
489
2
		for (track_id, amount) in class_locks_for {
490
1
			output.push(OutputClassLock {
491
1
				track: Self::track_id_to_u16(track_id)?,
492
1
				amount: amount.into(),
493
			});
494
		}
495

            
496
1
		Ok(output)
497
1
	}
498

            
499
9
	fn u8_to_conviction(conviction: u8) -> MayRevert<Conviction> {
500
9
		conviction
501
9
			.try_into()
502
9
			.map_err(|_| RevertReason::custom("Must be an integer between 0 and 6 included").into())
503
9
	}
504

            
505
16
	fn u32_to_index(index: u32) -> MayRevert<IndexOf<Runtime>> {
506
16
		index
507
16
			.try_into()
508
16
			.map_err(|_| RevertReason::value_is_too_large("index type").into())
509
16
	}
510

            
511
8
	fn u16_to_track_id(class: u16) -> MayRevert<ClassOf<Runtime>> {
512
8
		class
513
8
			.try_into()
514
8
			.map_err(|_| RevertReason::value_is_too_large("trackId type").into())
515
8
	}
516

            
517
1
	fn track_id_to_u16(class: ClassOf<Runtime>) -> MayRevert<u16> {
518
1
		class
519
1
			.try_into()
520
1
			.map_err(|_| RevertReason::value_is_too_large("trackId type").into())
521
1
	}
522

            
523
19
	fn u256_to_amount(value: U256) -> MayRevert<BalanceOf<Runtime>> {
524
19
		value
525
19
			.try_into()
526
19
			.map_err(|_| RevertReason::value_is_too_large("balance type").into())
527
19
	}
528

            
529
12
	fn log_vote_event(
530
12
		handle: &mut impl PrecompileHandle,
531
12
		poll_index: u32,
532
12
		vote: AccountVote<U256>,
533
12
	) -> EvmResult<(IndexOf<Runtime>, AccountVote<BalanceOf<Runtime>>, Log)> {
534
12
		let (contract_addr, caller) = (handle.context().address, handle.context().caller);
535
12
		let (vote, event) = match vote {
536
8
			AccountVote::Standard { vote, balance } => {
537
8
				let event = log2(
538
8
					contract_addr,
539
8
					SELECTOR_LOG_VOTED,
540
8
					H256::from_low_u64_be(poll_index as u64),
541
8
					solidity::encode_event_data((
542
8
						Address(caller),
543
8
						vote.aye,
544
8
						balance,
545
8
						u8::from(vote.conviction),
546
8
					)),
547
8
				);
548
8
				(
549
8
					AccountVote::Standard {
550
8
						vote,
551
8
						balance: Self::u256_to_amount(balance).in_field("voteAmount")?,
552
					},
553
8
					event,
554
				)
555
			}
556
2
			AccountVote::Split { aye, nay } => {
557
2
				let event = log2(
558
2
					contract_addr,
559
2
					SELECTOR_LOG_VOTE_SPLIT,
560
2
					H256::from_low_u64_be(poll_index as u64),
561
2
					solidity::encode_event_data((Address(caller), aye, nay)),
562
2
				);
563
2
				(
564
2
					AccountVote::Split {
565
2
						aye: Self::u256_to_amount(aye).in_field("aye")?,
566
2
						nay: Self::u256_to_amount(nay).in_field("nay")?,
567
					},
568
2
					event,
569
				)
570
			}
571
2
			AccountVote::SplitAbstain { aye, nay, abstain } => {
572
2
				let event = log2(
573
2
					contract_addr,
574
2
					SELECTOR_LOG_VOTE_SPLIT_ABSTAINED,
575
2
					H256::from_low_u64_be(poll_index as u64),
576
2
					solidity::encode_event_data((Address(caller), aye, nay, abstain)),
577
2
				);
578
2
				(
579
2
					AccountVote::SplitAbstain {
580
2
						aye: Self::u256_to_amount(aye).in_field("aye")?,
581
2
						nay: Self::u256_to_amount(nay).in_field("nay")?,
582
2
						abstain: Self::u256_to_amount(abstain).in_field("abstain")?,
583
					},
584
2
					event,
585
				)
586
			}
587
		};
588
12
		handle.record_log_costs(&[&event])?;
589
12
		Ok((Self::u32_to_index(poll_index)?, vote, event))
590
12
	}
591

            
592
3
	fn voting_to_output(voting: VotingOf<Runtime>) -> MayRevert<OutputVotingFor> {
593
3
		let output = match voting {
594
			Voting::Casting(Casting {
595
3
				votes,
596
3
				delegations,
597
3
				prior,
598
3
			}) => {
599
3
				let mut output_votes = Vec::new();
600
6
				for (poll_index, account_vote) in votes {
601
3
					let poll_index: u32 = poll_index
602
3
						.try_into()
603
3
						.map_err(|_| RevertReason::value_is_too_large("index type"))?;
604
3
					let account_vote = match account_vote {
605
1
						AccountVote::Standard { vote, balance } => OutputAccountVote {
606
1
							is_standard: true,
607
1
							standard: StandardVote {
608
1
								vote: OutputVote {
609
1
									aye: vote.aye,
610
1
									conviction: vote.conviction.into(),
611
1
								},
612
1
								balance: balance.into(),
613
1
							},
614
1
							..Default::default()
615
1
						},
616
1
						AccountVote::Split { aye, nay } => OutputAccountVote {
617
1
							is_split: true,
618
1
							split: SplitVote {
619
1
								aye: aye.into(),
620
1
								nay: nay.into(),
621
1
							},
622
1
							..Default::default()
623
1
						},
624
1
						AccountVote::SplitAbstain { aye, nay, abstain } => OutputAccountVote {
625
1
							is_split_abstain: true,
626
1
							split_abstain: SplitAbstainVote {
627
1
								aye: aye.into(),
628
1
								nay: nay.into(),
629
1
								abstain: abstain.into(),
630
1
							},
631
1
							..Default::default()
632
1
						},
633
					};
634

            
635
3
					output_votes.push(PollAccountVote {
636
3
						poll_index,
637
3
						account_vote,
638
3
					});
639
				}
640

            
641
3
				OutputVotingFor {
642
3
					is_casting: true,
643
3
					casting: OutputCasting {
644
3
						votes: output_votes,
645
3
						delegations: Delegations {
646
3
							votes: delegations.votes.into(),
647
3
							capital: delegations.capital.into(),
648
3
						},
649
3
						prior: PriorLock {
650
3
							balance: prior.locked().into(),
651
3
						},
652
3
					},
653
3
					..Default::default()
654
3
				}
655
			}
656
			Voting::Delegating(Delegating {
657
				balance,
658
				target,
659
				conviction,
660
				delegations,
661
				prior,
662
			}) => OutputVotingFor {
663
				is_delegating: true,
664
				delegating: OutputDelegating {
665
					balance: balance.into(),
666
					target: Address(target.into()),
667
					conviction: conviction.into(),
668
					delegations: Delegations {
669
						votes: delegations.votes.into(),
670
						capital: delegations.capital.into(),
671
					},
672
					prior: PriorLock {
673
						balance: prior.locked().into(),
674
					},
675
				},
676
				..Default::default()
677
			},
678
		};
679

            
680
3
		Ok(output)
681
3
	}
682
}
683

            
684
#[derive(Default, solidity::Codec)]
685
pub struct OutputClassLock {
686
	track: u16,
687
	amount: U256,
688
}
689

            
690
#[derive(Default, solidity::Codec)]
691
pub struct OutputVotingFor {
692
	is_casting: bool,
693
	is_delegating: bool,
694
	casting: OutputCasting,
695
	delegating: OutputDelegating,
696
}
697

            
698
#[derive(Default, solidity::Codec)]
699
pub struct OutputCasting {
700
	votes: Vec<PollAccountVote>,
701
	delegations: Delegations,
702
	prior: PriorLock,
703
}
704

            
705
#[derive(Default, solidity::Codec)]
706
pub struct PollAccountVote {
707
	poll_index: u32,
708
	account_vote: OutputAccountVote,
709
}
710

            
711
#[derive(Default, solidity::Codec)]
712
pub struct OutputDelegating {
713
	balance: U256,
714
	target: Address,
715
	conviction: u8,
716
	delegations: Delegations,
717
	prior: PriorLock,
718
}
719

            
720
#[derive(Default, solidity::Codec)]
721
pub struct OutputAccountVote {
722
	is_standard: bool,
723
	is_split: bool,
724
	is_split_abstain: bool,
725
	standard: StandardVote,
726
	split: SplitVote,
727
	split_abstain: SplitAbstainVote,
728
}
729

            
730
#[derive(Default, solidity::Codec)]
731
pub struct StandardVote {
732
	vote: OutputVote,
733
	balance: U256,
734
}
735

            
736
#[derive(Default, solidity::Codec)]
737
pub struct OutputVote {
738
	aye: bool,
739
	conviction: u8,
740
}
741

            
742
#[derive(Default, solidity::Codec)]
743
pub struct SplitVote {
744
	aye: U256,
745
	nay: U256,
746
}
747

            
748
#[derive(Default, solidity::Codec)]
749
pub struct SplitAbstainVote {
750
	aye: U256,
751
	nay: U256,
752
	abstain: U256,
753
}
754

            
755
#[derive(Default, solidity::Codec)]
756
pub struct Delegations {
757
	votes: U256,
758
	capital: U256,
759
}
760

            
761
#[derive(Default, solidity::Codec)]
762
pub struct PriorLock {
763
	balance: U256,
764
}