main.rs 19.8 KB
Newer Older
Kian Paimani's avatar
Kian Paimani committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Copyright 2021 Parity Technologies (UK) Ltd.
// 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/>.

//! # Polkadot Staking Miner.
//!
//! Simple bot capable of monitoring a polkadot (and cousins) chain and submitting solutions to the
Denis_P's avatar
Denis_P committed
20
//! `pallet-election-provider-multi-phase`. See `--help` for more details.
Kian Paimani's avatar
Kian Paimani committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//!
//! # Implementation Notes:
//!
//! - First draft: Be aware that this is the first draft and there might be bugs, or undefined
//!   behaviors. Don't attach this bot to an account with lots of funds.
//! - Quick to crash: The bot is written so that it only continues to work if everything goes well.
//!   In case of any failure (RPC, logic, IO), it will crash. This was a decision to simplify the
//!   development. It is intended to run this bot with a `restart = true` way, so that it reports it
//!   crash, but resumes work thereafter.

mod dry_run;
mod emergency_solution;
mod monitor;
mod prelude;
mod rpc_helpers;
mod signer;

pub(crate) use prelude::*;
pub(crate) use signer::get_account_info;

41
use frame_election_provider_support::NposSolver;
42
use frame_support::traits::Get;
Kian Paimani's avatar
Kian Paimani committed
43
44
use jsonrpsee_ws_client::{WsClient, WsClientBuilder};
use remote_externalities::{Builder, Mode, OnlineConfig};
45
use sp_npos_elections::ExtendedBalance;
Kian Paimani's avatar
Kian Paimani committed
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
use sp_runtime::traits::Block as BlockT;
use structopt::StructOpt;

pub(crate) enum AnyRuntime {
	Polkadot,
	Kusama,
	Westend,
}

pub(crate) static mut RUNTIME: AnyRuntime = AnyRuntime::Polkadot;

macro_rules! construct_runtime_prelude {
	($runtime:ident) => { paste::paste! {
		#[allow(unused_import)]
		pub(crate) mod [<$runtime _runtime_exports>] {
			pub(crate) use crate::prelude::EPM;
			pub(crate) use [<$runtime _runtime>]::*;
			pub(crate) use crate::monitor::[<monitor_cmd_ $runtime>] as monitor_cmd;
			pub(crate) use crate::dry_run::[<dry_run_cmd_ $runtime>] as dry_run_cmd;
			pub(crate) use crate::emergency_solution::[<emergency_solution_cmd_ $runtime>] as emergency_solution_cmd;
			pub(crate) use private::{[<create_uxt_ $runtime>] as create_uxt};

			mod private {
				use super::*;
				pub(crate) fn [<create_uxt_ $runtime>](
71
					raw_solution: EPM::RawSolution<EPM::SolutionOf<Runtime>>,
Kian Paimani's avatar
Kian Paimani committed
72
73
74
75
76
77
78
79
80
81
82
83
					witness: u32,
					signer: crate::signer::Signer,
					nonce: crate::prelude::Index,
					tip: crate::prelude::Balance,
					era: sp_runtime::generic::Era,
				) -> UncheckedExtrinsic {
					use codec::Encode as _;
					use sp_core::Pair as _;
					use sp_runtime::traits::StaticLookup as _;

					let crate::signer::Signer { account, pair, .. } = signer;

84
					let local_call = EPMCall::<Runtime>::submit { raw_solution: Box::new(raw_solution), num_signed_submissions: witness };
Kian Paimani's avatar
Kian Paimani committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
					let call: Call = <EPMCall<Runtime> as std::convert::TryInto<Call>>::try_into(local_call)
						.expect("election provider pallet must exist in the runtime, thus \
							inner call can be converted, qed."
						);

					let extra: SignedExtra = crate::[<signed_ext_builder_ $runtime>](nonce, tip, era);
					let raw_payload = SignedPayload::new(call, extra).expect("creating signed payload infallible; qed.");
					let signature = raw_payload.using_encoded(|payload| {
						pair.clone().sign(payload)
					});
					let (call, extra, _) = raw_payload.deconstruct();
					let address = <Runtime as frame_system::Config>::Lookup::unlookup(account.clone());
					let extrinsic = UncheckedExtrinsic::new_signed(call, address, signature.into(), extra);
					log::debug!(
99
100
101
						target: crate::LOG_TARGET, "constructed extrinsic {} with length {}",
						sp_core::hexdisplay::HexDisplay::from(&extrinsic.encode()),
						extrinsic.encode().len(),
Kian Paimani's avatar
Kian Paimani committed
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
					);
					extrinsic
				}
			}
		}}
	};
}

// NOTE: we might be able to use some code from the bridges repo here.
fn signed_ext_builder_polkadot(
	nonce: Index,
	tip: Balance,
	era: sp_runtime::generic::Era,
) -> polkadot_runtime_exports::SignedExtra {
	use polkadot_runtime_exports::Runtime;
	(
		frame_system::CheckSpecVersion::<Runtime>::new(),
		frame_system::CheckTxVersion::<Runtime>::new(),
		frame_system::CheckGenesis::<Runtime>::new(),
		frame_system::CheckMortality::<Runtime>::from(era),
		frame_system::CheckNonce::<Runtime>::from(nonce),
		frame_system::CheckWeight::<Runtime>::new(),
		pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
		runtime_common::claims::PrevalidateAttests::<Runtime>::new(),
	)
}

fn signed_ext_builder_kusama(
	nonce: Index,
	tip: Balance,
	era: sp_runtime::generic::Era,
) -> kusama_runtime_exports::SignedExtra {
	use kusama_runtime_exports::Runtime;
	(
		frame_system::CheckSpecVersion::<Runtime>::new(),
		frame_system::CheckTxVersion::<Runtime>::new(),
		frame_system::CheckGenesis::<Runtime>::new(),
		frame_system::CheckMortality::<Runtime>::from(era),
		frame_system::CheckNonce::<Runtime>::from(nonce),
		frame_system::CheckWeight::<Runtime>::new(),
		pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
	)
}

fn signed_ext_builder_westend(
	nonce: Index,
	tip: Balance,
	era: sp_runtime::generic::Era,
) -> westend_runtime_exports::SignedExtra {
	use westend_runtime_exports::Runtime;
	(
		frame_system::CheckSpecVersion::<Runtime>::new(),
		frame_system::CheckTxVersion::<Runtime>::new(),
		frame_system::CheckGenesis::<Runtime>::new(),
		frame_system::CheckMortality::<Runtime>::from(era),
		frame_system::CheckNonce::<Runtime>::from(nonce),
		frame_system::CheckWeight::<Runtime>::new(),
		pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
	)
}

construct_runtime_prelude!(polkadot);
construct_runtime_prelude!(kusama);
construct_runtime_prelude!(westend);

// NOTE: this is no longer used extensively, most of the per-runtime stuff us delegated to
// `construct_runtime_prelude` and macro's the import directly from it. A part of the code is also
// still generic over `T`. My hope is to still make everything generic over a `Runtime`, but sadly
// that is not currently possible as each runtime has its unique `Call`, and all Calls are not
// sharing any generic trait. In other words, to create the `UncheckedExtrinsic` of each chain, you
// need the concrete `Call` of that chain as well.
#[macro_export]
macro_rules! any_runtime {
	($($code:tt)*) => {
		unsafe {
			match $crate::RUNTIME {
				$crate::AnyRuntime::Polkadot => {
179
					#[allow(unused)]
Kian Paimani's avatar
Kian Paimani committed
180
181
182
183
					use $crate::polkadot_runtime_exports::*;
					$($code)*
				},
				$crate::AnyRuntime::Kusama => {
184
					#[allow(unused)]
Kian Paimani's avatar
Kian Paimani committed
185
186
187
188
					use $crate::kusama_runtime_exports::*;
					$($code)*
				},
				$crate::AnyRuntime::Westend => {
189
					#[allow(unused)]
Kian Paimani's avatar
Kian Paimani committed
190
191
192
193
194
195
196
197
					use $crate::westend_runtime_exports::*;
					$($code)*
				}
			}
		}
	}
}

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
/// Same as [`any_runtime`], but instead of returning a `Result`, this simply returns `()`. Useful
/// for situations where the result is not useful and un-ergonomic to handle.
#[macro_export]
macro_rules! any_runtime_unit {
	($($code:tt)*) => {
		unsafe {
			match $crate::RUNTIME {
				$crate::AnyRuntime::Polkadot => {
					#[allow(unused)]
					use $crate::polkadot_runtime_exports::*;
					let _ = $($code)*;
				},
				$crate::AnyRuntime::Kusama => {
					#[allow(unused)]
					use $crate::kusama_runtime_exports::*;
					let _ = $($code)*;
				},
				$crate::AnyRuntime::Westend => {
					#[allow(unused)]
					use $crate::westend_runtime_exports::*;
					let _ = $($code)*;
				}
			}
		}
	}
}

#[derive(frame_support::DebugNoBound, thiserror::Error)]
enum Error<T: EPM::Config> {
Kian Paimani's avatar
Kian Paimani committed
227
	Io(#[from] std::io::Error),
228
229
	JsonRpsee(#[from] jsonrpsee_ws_client::types::Error),
	RpcHelperError(#[from] rpc_helpers::RpcHelperError),
Kian Paimani's avatar
Kian Paimani committed
230
231
232
	Codec(#[from] codec::Error),
	Crypto(sp_core::crypto::SecretStringError),
	RemoteExternalities(&'static str),
233
234
	PalletMiner(EPM::unsigned::MinerError<T>),
	PalletElection(EPM::ElectionError<T>),
Kian Paimani's avatar
Kian Paimani committed
235
236
237
238
	PalletFeasibility(EPM::FeasibilityError),
	AccountDoesNotExists,
	IncorrectPhase,
	AlreadySubmitted,
239
	VersionMismatch,
Kian Paimani's avatar
Kian Paimani committed
240
241
}

242
243
impl<T: EPM::Config> From<sp_core::crypto::SecretStringError> for Error<T> {
	fn from(e: sp_core::crypto::SecretStringError) -> Error<T> {
Kian Paimani's avatar
Kian Paimani committed
244
245
246
247
		Error::Crypto(e)
	}
}

248
249
impl<T: EPM::Config> From<EPM::unsigned::MinerError<T>> for Error<T> {
	fn from(e: EPM::unsigned::MinerError<T>) -> Error<T> {
Kian Paimani's avatar
Kian Paimani committed
250
251
252
253
		Error::PalletMiner(e)
	}
}

254
255
impl<T: EPM::Config> From<EPM::ElectionError<T>> for Error<T> {
	fn from(e: EPM::ElectionError<T>) -> Error<T> {
Kian Paimani's avatar
Kian Paimani committed
256
257
258
259
		Error::PalletElection(e)
	}
}

260
261
impl<T: EPM::Config> From<EPM::FeasibilityError> for Error<T> {
	fn from(e: EPM::FeasibilityError) -> Error<T> {
Kian Paimani's avatar
Kian Paimani committed
262
263
264
265
		Error::PalletFeasibility(e)
	}
}

266
impl<T: EPM::Config> std::fmt::Display for Error<T> {
Kian Paimani's avatar
Kian Paimani committed
267
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268
		<Error<T> as std::fmt::Debug>::fmt(self, f)
Kian Paimani's avatar
Kian Paimani committed
269
270
271
272
273
274
275
276
277
	}
}

#[derive(Debug, Clone, StructOpt)]
enum Command {
	/// Monitor for the phase being signed, then compute.
	Monitor(MonitorConfig),
	/// Just compute a solution now, and don't submit it.
	DryRun(DryRunConfig),
Denis_P's avatar
Denis_P committed
278
	/// Provide a solution that can be submitted to the chain as an emergency response.
279
	EmergencySolution(EmergencySolutionConfig),
Kian Paimani's avatar
Kian Paimani committed
280
281
}

282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#[derive(Debug, Clone, StructOpt)]
enum Solvers {
	SeqPhragmen {
		#[structopt(long, default_value = "10")]
		iterations: usize,
	},
	PhragMMS {
		#[structopt(long, default_value = "10")]
		iterations: usize,
	},
}

frame_support::parameter_types! {
	/// Number of balancing iterations for a solution algorithm. Set based on the [`Solvers`] CLI
	/// config.
	pub static BalanceIterations: usize = 10;
	pub static Balancing: Option<(usize, ExtendedBalance)> = Some((BalanceIterations::get(), 0));
}

Kian Paimani's avatar
Kian Paimani committed
301
302
303
304
305
306
307
308
309
310
#[derive(Debug, Clone, StructOpt)]
struct MonitorConfig {
	/// They type of event to listen to.
	///
	/// Typically, finalized is safer and there is no chance of anything going wrong, but it can be
	/// slower. It is recommended to use finalized, if the duration of the signed phase is longer
	/// than the the finality delay.
	#[structopt(long, default_value = "head", possible_values = &["head", "finalized"])]
	listen: String,

311
	/// The solver algorithm to use.
312
313
	#[structopt(subcommand)]
	solver: Solvers,
Kian Paimani's avatar
Kian Paimani committed
314
315
}

316
317
318
319
320
321
322
323
324
325
326
327
328
329
#[derive(Debug, Clone, StructOpt)]
struct EmergencySolutionConfig {
	/// The block hash at which scraping happens. If none is provided, the latest head is used.
	#[structopt(long)]
	at: Option<Hash>,

	/// The solver algorithm to use.
	#[structopt(subcommand)]
	solver: Solvers,

	/// The number of top backed winners to take. All are taken, if not provided.
	take: Option<usize>,
}

Kian Paimani's avatar
Kian Paimani committed
330
331
332
333
334
335
#[derive(Debug, Clone, StructOpt)]
struct DryRunConfig {
	/// The block hash at which scraping happens. If none is provided, the latest head is used.
	#[structopt(long)]
	at: Option<Hash>,

336
	/// The solver algorithm to use.
337
338
	#[structopt(subcommand)]
	solver: Solvers,
Kian Paimani's avatar
Kian Paimani committed
339
340
341
342
}

#[derive(Debug, Clone, StructOpt)]
struct SharedConfig {
Denis_P's avatar
Denis_P committed
343
	/// The `ws` node to connect to.
344
	#[structopt(long, short, default_value = DEFAULT_URI, env = "URI")]
Kian Paimani's avatar
Kian Paimani committed
345
346
	uri: String,

347
	/// The seed of a funded account in hex.
Kian Paimani's avatar
Kian Paimani committed
348
	///
349
350
351
352
	/// WARNING: Don't use an account with a large stash for this. Based on how the bot is
	/// configured, it might re-try and lose funds through transaction fees/deposits.
	#[structopt(long, short, env = "SEED")]
	seed: String,
Kian Paimani's avatar
Kian Paimani committed
353
354
355
356
}

#[derive(Debug, Clone, StructOpt)]
struct Opt {
Denis_P's avatar
Denis_P committed
357
	/// The `ws` node to connect to.
Kian Paimani's avatar
Kian Paimani committed
358
359
360
361
362
363
364
	#[structopt(flatten)]
	shared: SharedConfig,

	#[structopt(subcommand)]
	command: Command,
}

365
366
/// Build the Ext at hash with all the data of `ElectionProviderMultiPhase` and any additional
/// pallets.
Kian Paimani's avatar
Kian Paimani committed
367
368
369
async fn create_election_ext<T: EPM::Config, B: BlockT>(
	uri: String,
	at: Option<B::Hash>,
370
	additional: Vec<String>,
371
) -> Result<Ext, Error<T>> {
Kian Paimani's avatar
Kian Paimani committed
372
	use frame_support::{storage::generator::StorageMap, traits::PalletInfo};
373
	use sp_core::hashing::twox_128;
Kian Paimani's avatar
Kian Paimani committed
374

375
	let mut pallets = vec![<T as frame_system::Config>::PalletInfo::name::<EPM::Pallet<T>>()
376
377
		.expect("Pallet always has name; qed.")
		.to_string()];
378
	pallets.extend(additional);
Kian Paimani's avatar
Kian Paimani committed
379
380
381
382
	Builder::<B>::new()
		.mode(Mode::Online(OnlineConfig {
			transport: uri.into(),
			at,
383
			pallets,
Kian Paimani's avatar
Kian Paimani committed
384
385
			..Default::default()
		}))
386
387
		.inject_hashed_prefix(&<frame_system::BlockHash<T>>::prefix_hash())
		.inject_hashed_key(&[twox_128(b"System"), twox_128(b"Number")].concat())
Kian Paimani's avatar
Kian Paimani committed
388
389
390
391
392
		.build()
		.await
		.map_err(|why| Error::RemoteExternalities(why))
}

393
394
395
/// Compute the election. It expects to NOT be `Phase::Off`. In other words, the snapshot must
/// exists on the given externalities.
fn mine_solution<T, S>(
Kian Paimani's avatar
Kian Paimani committed
396
397
	ext: &mut Ext,
	do_feasibility: bool,
398
399
400
401
402
403
404
405
) -> Result<(EPM::RawSolution<EPM::SolutionOf<T>>, u32), Error<T>>
where
	T: EPM::Config,
	S: NposSolver<
		Error = <<T as EPM::Config>::Solver as NposSolver>::Error,
		AccountId = <<T as EPM::Config>::Solver as NposSolver>::AccountId,
	>,
{
Kian Paimani's avatar
Kian Paimani committed
406
	ext.execute_with(|| {
407
408
		let (solution, _) =
			<EPM::Pallet<T>>::mine_solution::<S>().map_err::<Error<T>, _>(Into::into)?;
Kian Paimani's avatar
Kian Paimani committed
409
		if do_feasibility {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
410
411
412
413
			let _ = <EPM::Pallet<T>>::feasibility_check(
				solution.clone(),
				EPM::ElectionCompute::Signed,
			)?;
Kian Paimani's avatar
Kian Paimani committed
414
415
416
417
418
419
		}
		let witness = <EPM::SignedSubmissions<T>>::decode_len().unwrap_or_default();
		Ok((solution, witness as u32))
	})
}

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
/// Mine a solution with the given `solver`.
fn mine_with<T>(
	solver: &Solvers,
	ext: &mut Ext,
	do_feasibility: bool,
) -> Result<(EPM::RawSolution<EPM::SolutionOf<T>>, u32), Error<T>>
where
	T: EPM::Config,
	T::Solver: NposSolver<Error = sp_npos_elections::Error>,
{
	use frame_election_provider_support::{PhragMMS, SequentialPhragmen};

	match solver {
		Solvers::SeqPhragmen { iterations } => {
			BalanceIterations::set(*iterations);
			mine_solution::<
				T,
				SequentialPhragmen<
					<T as frame_system::Config>::AccountId,
					sp_runtime::Perbill,
					Balancing,
				>,
			>(ext, do_feasibility)
		},
		Solvers::PhragMMS { iterations } => {
			BalanceIterations::set(*iterations);
			mine_solution::<
				T,
				PhragMMS<<T as frame_system::Config>::AccountId, sp_runtime::Perbill, Balancing>,
			>(ext, do_feasibility)
		},
	}
}

Kian Paimani's avatar
Kian Paimani committed
454
#[allow(unused)]
455
fn mine_dpos<T: EPM::Config>(ext: &mut Ext) -> Result<(), Error<T>> {
Kian Paimani's avatar
Kian Paimani committed
456
457
458
459
460
461
462
	ext.execute_with(|| {
		use std::collections::BTreeMap;
		use EPM::RoundSnapshot;
		let RoundSnapshot { voters, .. } = EPM::Snapshot::<T>::get().unwrap();
		let desired_targets = EPM::DesiredTargets::<T>::get().unwrap();
		let mut candidates_and_backing = BTreeMap::<T::AccountId, u128>::new();
		voters.into_iter().for_each(|(who, stake, targets)| {
463
			if targets.is_empty() {
Kian Paimani's avatar
Kian Paimani committed
464
				println!("target = {:?}", (who, stake, targets));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
465
				return
Kian Paimani's avatar
Kian Paimani committed
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
			}
			let share: u128 = (stake as u128) / (targets.len() as u128);
			for target in targets {
				*candidates_and_backing.entry(target.clone()).or_default() += share
			}
		});

		let mut candidates_and_backing =
			candidates_and_backing.into_iter().collect::<Vec<(_, _)>>();
		candidates_and_backing.sort_by_key(|(_, total_stake)| *total_stake);
		let winners = candidates_and_backing
			.into_iter()
			.rev()
			.take(desired_targets as usize)
			.collect::<Vec<_>>();
		let score = {
			let min_staker = *winners.last().map(|(_, stake)| stake).unwrap();
			let sum_stake = winners.iter().fold(0u128, |acc, (_, stake)| acc + stake);
			let sum_squared = winners.iter().fold(0u128, |acc, (_, stake)| acc + stake);
			[min_staker, sum_stake, sum_squared]
		};
		println!("mined a dpos-like solution with score = {:?}", score);
		Ok(())
	})
}

492
pub(crate) async fn check_versions<T: frame_system::Config + EPM::Config>(
493
	client: &WsClient,
494
) -> Result<(), Error<T>> {
495
496
497
498
499
500
501
502
503
	let linked_version = T::Version::get();
	let on_chain_version = rpc_helpers::rpc::<sp_version::RuntimeVersion>(
		client,
		"state_getRuntimeVersion",
		params! {},
	)
	.await
	.expect("runtime version RPC should always work; qed");

504
505
506
	log::debug!(target: LOG_TARGET, "linked version {:?}", linked_version);
	log::debug!(target: LOG_TARGET, "on-chain version {:?}", on_chain_version);

507
508
509
510
511
512
513
514
515
516
517
	if linked_version != on_chain_version {
		log::error!(
			target: LOG_TARGET,
			"VERSION MISMATCH: any transaction will fail with bad-proof"
		);
		Err(Error::VersionMismatch)
	} else {
		Ok(())
	}
}

Kian Paimani's avatar
Kian Paimani committed
518
519
#[tokio::main]
async fn main() {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
520
521
522
523
	env_logger::Builder::from_default_env()
		.format_module_path(true)
		.format_level(true)
		.init();
Kian Paimani's avatar
Kian Paimani committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
	let Opt { shared, command } = Opt::from_args();
	log::debug!(target: LOG_TARGET, "attempting to connect to {:?}", shared.uri);

	let client = loop {
		let maybe_client = WsClientBuilder::default()
			.connection_timeout(std::time::Duration::new(20, 0))
			.max_request_body_size(u32::MAX)
			.build(&shared.uri)
			.await;
		match maybe_client {
			Ok(client) => break client,
			Err(why) => {
				log::warn!(
					target: LOG_TARGET,
					"failed to connect to client due to {:?}, retrying soon..",
					why
				);
				std::thread::sleep(std::time::Duration::from_millis(2500));
Shawn Tabrizi's avatar
Shawn Tabrizi committed
542
			},
Kian Paimani's avatar
Kian Paimani committed
543
544
545
546
547
548
549
550
551
		}
	};

	let chain = rpc_helpers::rpc::<String>(&client, "system_chain", params! {})
		.await
		.expect("system_chain infallible; qed.");
	match chain.to_lowercase().as_str() {
		"polkadot" | "development" => {
			sp_core::crypto::set_default_ss58_version(
Squirrel's avatar
Squirrel committed
552
				sp_core::crypto::Ss58AddressFormatRegistry::PolkadotAccount.into(),
Kian Paimani's avatar
Kian Paimani committed
553
			);
554
555
			sub_tokens::dynamic::set_name("DOT");
			sub_tokens::dynamic::set_decimal_points(10_000_000_000);
Kian Paimani's avatar
Kian Paimani committed
556
557
558
559
560
			// safety: this program will always be single threaded, thus accessing global static is
			// safe.
			unsafe {
				RUNTIME = AnyRuntime::Polkadot;
			}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
561
		},
Kian Paimani's avatar
Kian Paimani committed
562
563
		"kusama" | "kusama-dev" => {
			sp_core::crypto::set_default_ss58_version(
Squirrel's avatar
Squirrel committed
564
				sp_core::crypto::Ss58AddressFormatRegistry::KusamaAccount.into(),
Kian Paimani's avatar
Kian Paimani committed
565
			);
566
567
			sub_tokens::dynamic::set_name("KSM");
			sub_tokens::dynamic::set_decimal_points(1_000_000_000_000);
Kian Paimani's avatar
Kian Paimani committed
568
569
570
571
572
			// safety: this program will always be single threaded, thus accessing global static is
			// safe.
			unsafe {
				RUNTIME = AnyRuntime::Kusama;
			}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
573
		},
Kian Paimani's avatar
Kian Paimani committed
574
575
		"westend" => {
			sp_core::crypto::set_default_ss58_version(
Squirrel's avatar
Squirrel committed
576
				sp_core::crypto::Ss58AddressFormatRegistry::PolkadotAccount.into(),
Kian Paimani's avatar
Kian Paimani committed
577
			);
578
579
			sub_tokens::dynamic::set_name("WND");
			sub_tokens::dynamic::set_decimal_points(1_000_000_000_000);
Kian Paimani's avatar
Kian Paimani committed
580
581
582
583
584
			// safety: this program will always be single threaded, thus accessing global static is
			// safe.
			unsafe {
				RUNTIME = AnyRuntime::Westend;
			}
Shawn Tabrizi's avatar
Shawn Tabrizi committed
585
		},
Kian Paimani's avatar
Kian Paimani committed
586
587
		_ => {
			eprintln!("unexpected chain: {:?}", chain);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
588
589
			return
		},
Kian Paimani's avatar
Kian Paimani committed
590
591
592
	}
	log::info!(target: LOG_TARGET, "connected to chain {:?}", chain);

593
	any_runtime_unit! {
594
		check_versions::<Runtime>(&client).await
595
596
	};

Kian Paimani's avatar
Kian Paimani committed
597
	let signer_account = any_runtime! {
598
		signer::signer_uri_from_string::<Runtime>(&shared.seed, &client)
Kian Paimani's avatar
Kian Paimani committed
599
600
601
602
603
604
			.await
			.expect("Provided account is invalid, terminating.")
	};

	let outcome = any_runtime! {
		match command.clone() {
605
606
607
608
609
610
611
612
			Command::Monitor(c) => monitor_cmd(&client, shared, c, signer_account).await
				.map_err(|e| {
					log::error!(target: LOG_TARGET, "Monitor error: {:?}", e);
				}),
			Command::DryRun(c) => dry_run_cmd(&client, shared, c, signer_account).await
				.map_err(|e| {
					log::error!(target: LOG_TARGET, "DryRun error: {:?}", e);
				}),
613
			Command::EmergencySolution(c) => emergency_solution_cmd(shared.clone(), c).await
614
615
616
				.map_err(|e| {
					log::error!(target: LOG_TARGET, "EmergencySolution error: {:?}", e);
				}),
Kian Paimani's avatar
Kian Paimani committed
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
		}
	};
	log::info!(target: LOG_TARGET, "round of execution finished. outcome = {:?}", outcome);
}

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

	fn get_version<T: frame_system::Config>() -> sp_version::RuntimeVersion {
		T::Version::get()
	}

	#[test]
	fn any_runtime_works() {
		unsafe {
			RUNTIME = AnyRuntime::Polkadot;
		}
		let polkadot_version = any_runtime! { get_version::<Runtime>() };

		unsafe {
			RUNTIME = AnyRuntime::Kusama;
		}
		let kusama_version = any_runtime! { get_version::<Runtime>() };

		assert_eq!(polkadot_version.spec_name, "polkadot".into());
		assert_eq!(kusama_version.spec_name, "kusama".into());
	}
}