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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
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
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
use std::{
	ops::{
		Mul,
		Sub,
	},
	sync::Arc,
};

use raiden_blockchain::{
	errors::ContractDefError,
	proxies::{
		Account,
		GasReserve,
		ProxyError,
	},
};
use raiden_pathfinding::{
	query_address_metadata,
	routing,
	RoutingError,
};
use raiden_primitives::{
	hashing::hash_secret,
	payments::{
		PaymentStatus,
		PaymentsRegistry,
	},
	traits::Checksum,
	types::{
		Address,
		BlockTimeout,
		Bytes,
		CanonicalIdentifier,
		ChannelIdentifier,
		PaymentIdentifier,
		RetryTimeout,
		RevealTimeout,
		Secret,
		SecretHash,
		SecretRegistryAddress,
		SettleTimeout,
		TokenAddress,
		TokenAmount,
		TokenNetworkAddress,
		TokenNetworkRegistryAddress,
		TransactionHash,
	},
};
use raiden_state_machine::{
	constants::{
		ABSENT_SECRET,
		DEFAULT_RETRY_TIMEOUT,
		MIN_REVEAL_TIMEOUT,
		SECRET_LENGTH,
	},
	errors::StateTransitionError,
	types::{
		ActionChannelClose,
		ActionChannelCoopSettle,
		ActionChannelSetRevealTimeout,
		ActionChannelWithdraw,
		ActionInitInitiator,
		ChannelState,
		ChannelStatus,
		RouteState,
		StateChange,
		TransferDescriptionWithSecretState,
	},
	views,
};
use raiden_transition::Transitioner;
use thiserror::Error;
use tokio::sync::RwLock;
use tracing::{
	debug,
	error,
	info,
};
use web3::transports::Http;

use crate::{
	raiden::Raiden,
	utils::{
		random_identifier,
		random_secret,
	},
	waiting,
};

/// API error type.
#[derive(Error, Debug)]
pub enum ApiError {
	#[error("Transition Error: `{0}`")]
	Transition(StateTransitionError),
	#[error("Contract definition error: `{0}`")]
	ContractSpec(ContractDefError),
	#[error("Contract error: `{0}`")]
	Contract(web3::contract::Error),
	#[error("Proxy error: `{0}`")]
	Proxy(ProxyError),
	#[error("Web3 error: `{0}`")]
	Web3(web3::Error),
	#[error("On-chain error: `{0}`")]
	OnChainCall(String),
	#[error("Invalid state: `{0}`")]
	State(String),
	#[error("Routing error: `{0}`")]
	Routing(RoutingError),
	#[error("Invalid parameter: `{0}`")]
	Param(String),
}

/// A pending payment
pub struct Payment {
	pub target: Address,
	pub payment_identifier: PaymentIdentifier,
	pub secret: Secret,
	pub secrethash: SecretHash,
}

/// The interface which enables initiating payments and interacting with contracts.
pub struct Api {
	pub raiden: Arc<Raiden>,
	transition_service: Arc<Transitioner>,
	payments_registry: Arc<RwLock<PaymentsRegistry>>,
}

impl Api {
	/// Creates a new instance of `Api`
	pub fn new(
		raiden: Arc<Raiden>,
		transition_service: Arc<Transitioner>,
		payments_registry: Arc<RwLock<PaymentsRegistry>>,
	) -> Self {
		Self { raiden, transition_service, payments_registry }
	}

	/// Creates a new channel with the current account being one participant.
	#[allow(clippy::too_many_arguments)]
	pub async fn create_channel(
		&self,
		account: Account<Http>,
		registry_address: Address,
		token_address: TokenAddress,
		partner_address: Address,
		settle_timeout: Option<SettleTimeout>,
		reveal_timeout: Option<RevealTimeout>,
		retry_timeout: Option<RetryTimeout>,
	) -> Result<ChannelIdentifier, ApiError> {
		let current_state = &self.raiden.state_manager.read().current_state.clone();

		info!(
			message = "Opening channel.",
			registry_address = registry_address.checksum(),
			partner_address = partner_address.checksum(),
			token_address = token_address.checksum(),
			settle_timeout = settle_timeout.map(|t| t.to_string()),
			reveal_timeout = reveal_timeout.map(|t| t.to_string()),
		);
		let settle_timeout = settle_timeout.unwrap_or(self.raiden.config.default_settle_timeout);
		let reveal_timeout = reveal_timeout.unwrap_or(self.raiden.config.default_reveal_timeout);

		self.check_invalid_channel_timeouts(settle_timeout, reveal_timeout)?;

		let confirmed_block_identifier = current_state.block_hash;
		let registry = self
			.raiden
			.proxy_manager
			.token_network_registry(registry_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let settlement_timeout_min = registry
			.settlement_timeout_min(confirmed_block_identifier)
			.await
			.map_err(ApiError::Proxy)?;
		let settlement_timeout_max = registry
			.settlement_timeout_max(confirmed_block_identifier)
			.await
			.map_err(ApiError::Proxy)?;

		if settle_timeout < settlement_timeout_min {
			return Err(ApiError::Param(format!(
				"Settlement timeout should be at least {}",
				settlement_timeout_min,
			)))
		}

		if settle_timeout > settlement_timeout_max {
			return Err(ApiError::Param(format!(
				"Settlement timeout exceeds max of {}",
				settlement_timeout_max,
			)))
		}

		let token_network_address = registry
			.get_token_network(token_address, confirmed_block_identifier)
			.await
			.map_err(ApiError::Proxy)?;

		if token_network_address.is_zero() {
			return Err(ApiError::Param(format!(
				"Token network for token {} does not exist",
				token_address,
			)))
		}

		let mut token_network = self
			.raiden
			.proxy_manager
			.token_network(token_address, token_network_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let safety_deprecation_switch = token_network
			.safety_deprecation_switch(confirmed_block_identifier)
			.await
			.map_err(ApiError::Proxy)?;

		if safety_deprecation_switch {
			return Err(ApiError::OnChainCall(
				"This token_network has been deprecated. New channels cannot be
                open for this network, usage of the newly deployed token
                network contract is highly encouraged."
					.to_owned(),
			))
		}

		let duplicated_channel = token_network
			.get_channel_identifier(
				token_network_address,
				partner_address,
				Some(confirmed_block_identifier),
			)
			.await
			.map_err(ApiError::Proxy)?;

		if duplicated_channel.is_some() {
			return Err(ApiError::OnChainCall(format!(
				"A channel with {} for token
                {} already exists.
                (At blockhash: {})",
				partner_address, token_address, confirmed_block_identifier,
			)))
		}

		let chain_state = &self.raiden.state_manager.read().current_state.clone();
		let gas_reserve = GasReserve::new(self.raiden.proxy_manager.clone(), registry_address);
		let (has_enough_reserve, estimated_required_reserve) = gas_reserve
			.has_enough(account.clone(), chain_state, 1)
			.await
			.map_err(ApiError::Proxy)?;

		if !has_enough_reserve {
			return Err(ApiError::OnChainCall(format!(
				"The account balance is below the estimated amount necessary to \
                finish the lifecycles of all active channels. A balance of at \
                least {} wei is required.",
				estimated_required_reserve,
			)))
		}

		let channel_identifier = match token_network
			.new_channel(
				account.clone(),
				partner_address,
				settle_timeout,
				confirmed_block_identifier,
			)
			.await
		{
			Ok(channel_identifier) => channel_identifier,
			Err(e) => {
				// Check if channel has already been created by partner
				if let Ok(Some(channel_ideitifier)) = token_network
					.get_channel_identifier(account.address(), partner_address, None)
					.await
				{
					channel_ideitifier
				} else {
					return Err(ApiError::Proxy(e))
				}
			},
		};

		waiting::wait_for_new_channel(
			self.raiden.state_manager.clone(),
			registry_address,
			token_address,
			partner_address,
			retry_timeout,
		)
		.await?;

		let chain_state = &self.raiden.state_manager.read().current_state.clone();
		let channel_state = match views::get_channel_state_for(
			chain_state,
			registry_address,
			token_address,
			partner_address,
		) {
			Some(channel_state) => channel_state,
			None => return Err(ApiError::State(format!("Channel was not found"))),
		};

		debug!(
			message = "Channel opened",
			channel_identifier = channel_state.canonical_identifier.channel_identifier.to_string()
		);

		if let Err(e) = self
			.transition_service
			.transition(vec![ActionChannelSetRevealTimeout {
				canonical_identifier: channel_state.canonical_identifier.clone(),
				reveal_timeout,
			}
			.into()])
			.await
		{
			return Err(ApiError::State(e))
		}

		Ok(channel_identifier)
	}

	/// Updates a channel state on-chain depending on the parameters passed.
	///
	/// Only one optional parameter is allowed to be set in a single call to determine what the call
	/// will do.
	///
	/// `reveal_timeout`: Sets the reveal timeout of a channel.
	/// `total_deposit`: Deposit the defined amount into the channel.
	/// `total_withdraw`: Initiates a withdraw with partner.
	/// `state`: Alters the state of the channel. For example: closed.
	#[allow(clippy::too_many_arguments)]
	pub async fn update_channel(
		&self,
		account: Account<Http>,
		registry_address: Address,
		token_address: TokenAddress,
		partner_address: Address,
		reveal_timeout: Option<RevealTimeout>,
		total_deposit: Option<TokenAmount>,
		total_withdraw: Option<TokenAmount>,
		state: Option<ChannelStatus>,
		retry_timeout: Option<RetryTimeout>,
	) -> Result<(), ApiError> {
		info!(
			message = "Patching channel.",
			registry_address = registry_address.checksum(),
			partner_address = partner_address.checksum(),
			token_address = token_address.checksum(),
			reveal_timeout = reveal_timeout.map(|t| t.to_string()),
			total_deposit = total_deposit.map(|t| t.to_string()),
			total_withdraw = total_withdraw.map(|t| t.to_string()),
			state = state.map(|t| t.to_string()),
		);

		if reveal_timeout.is_some() && state.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's reveal timeout and state at the same time",
			)))
		}

		if total_deposit.is_some() && state.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's total deposit and state at the same time",
			)))
		}

		if total_withdraw.is_some() && state.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's total withdraw and state at the same time",
			)))
		}

		if total_withdraw.is_some() && total_deposit.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's total withdraw and total deposit at the same time",
			)))
		}

		if reveal_timeout.is_some() && total_deposit.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's reveal timeout and total deposit at the same time",
			)))
		}

		if reveal_timeout.is_some() && total_withdraw.is_some() {
			return Err(ApiError::Param(format!(
				"Can not update a channel's reveal timeout and total withdraw at the same time",
			)))
		}

		if let Some(total_deposit) = total_deposit {
			if total_deposit < TokenAmount::zero() {
				return Err(ApiError::Param(format!("Amount to deposit must not be negative")))
			}
		}

		if let Some(total_withdraw) = total_withdraw {
			if total_withdraw < TokenAmount::zero() {
				return Err(ApiError::Param(format!("Amount to withdraw must not be negative")))
			}
		}

		let empty_request = total_deposit.is_none() &&
			state.is_none() &&
			total_withdraw.is_none() &&
			reveal_timeout.is_none();

		if empty_request {
			return Err(ApiError::Param(format!(
				"Nothing to do. Should either provide \
                `total_deposit, `total_withdraw`, `reveal_timeout` or `state` argument"
			)))
		}

		let current_state = &self.raiden.state_manager.read().current_state.clone();
		let channel_state = match views::get_channel_state_for(
			current_state,
			registry_address,
			token_address,
			partner_address,
		) {
			Some(channel_state) => channel_state,
			None =>
				return Err(ApiError::State(format!(
					"Requested channel for token {} and partner {} not found",
					token_address, partner_address,
				))),
		};

		if let Some(total_deposit) = total_deposit {
			self.channel_deposit(account, channel_state, total_deposit, retry_timeout).await
		} else if let Some(total_withdraw) = total_withdraw {
			self.channel_withdraw(channel_state, total_withdraw).await
		} else if let Some(reveal_timeout) = reveal_timeout {
			self.channel_reveal_timeout(channel_state, reveal_timeout).await
		} else if let Some(state) = state {
			if state == ChannelStatus::Closed {
				return self.channel_close(registry_address, channel_state).await
			}
			return Err(ApiError::Param(format!("Unreachable")))
		} else {
			return Err(ApiError::Param(format!("Unreachable")))
		}
	}

	pub async fn channel_deposit(
		&self,
		account: Account<Http>,
		channel_state: &ChannelState,
		total_deposit: TokenAmount,
		retry_timeout: Option<RetryTimeout>,
	) -> Result<(), ApiError> {
		info!(
			message = "Depositing to channel.",
			channel_identifier = channel_state.canonical_identifier.channel_identifier.to_string(),
			total_deposit = total_deposit.to_string(),
		);

		if channel_state.status() != ChannelStatus::Opened {
			return Err(ApiError::State(format!("Can't set total deposit on a closed channel")))
		}

		let chain_state = &self.raiden.state_manager.read().current_state.clone();
		let confirmed_block_identifier = chain_state.block_hash;
		let token = self
			.raiden
			.proxy_manager
			.token(channel_state.token_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let token_network_registry = self
			.raiden
			.proxy_manager
			.token_network_registry(channel_state.token_network_registry_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let token_network_address = token_network_registry
			.get_token_network(channel_state.token_address, confirmed_block_identifier)
			.await
			.map_err(ApiError::Proxy)?;

		let token_network_proxy = self
			.raiden
			.proxy_manager
			.token_network(channel_state.token_address, token_network_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let channel_proxy = self
			.raiden
			.proxy_manager
			.payment_channel(channel_state)
			.await
			.map_err(ApiError::ContractSpec)?;

		let blockhash = chain_state.block_hash;

		let safety_deprecation_switch = token_network_proxy
			.safety_deprecation_switch(blockhash)
			.await
			.map_err(ApiError::Proxy)?;

		let balance = token
			.balance_of(chain_state.our_address, Some(blockhash))
			.await
			.map_err(ApiError::Proxy)?;

		let network_balance = token
			.balance_of(token_network_address, Some(blockhash))
			.await
			.map_err(ApiError::Proxy)?;

		let token_network_deposit_limit = token_network_proxy
			.token_network_deposit_limit(blockhash)
			.await
			.map_err(ApiError::Proxy)?;

		let channel_participant_deposit_limit = token_network_proxy
			.channel_participant_deposit_limit(blockhash)
			.await
			.map_err(ApiError::Proxy)?;

		let (_, total_channel_deposit_overflow) =
			total_deposit.overflowing_add(channel_state.partner_state.contract_balance);

		if safety_deprecation_switch {
			return Err(ApiError::State(format!(
				"This token_network has been deprecated. \
                All channels in this network should be closed and \
                the usage of the newly deployed token network contract \
                is highly encouraged."
			)))
		}

		if total_deposit <= channel_state.our_state.contract_balance {
			return Err(ApiError::State(format!("Total deposit did not increase.")))
		}

		if total_deposit < channel_state.our_state.contract_balance {
			return Err(ApiError::State(format!(
				"The new total deposit {:?} is less than the current total deposit {:?}",
				total_deposit, channel_state.our_state.contract_balance,
			)))
		}

		let deposit_increase = total_deposit - channel_state.our_state.contract_balance;
		// If this check succeeds it does not imply the `deposit` will
		// succeed, since the `deposit` transaction may race with another
		// transaction.
		if balance < deposit_increase {
			return Err(ApiError::State(format!(
				"Not enough balance to deposit. Available={} Needed={}",
				balance, deposit_increase,
			)))
		}

		if network_balance + deposit_increase > token_network_deposit_limit {
			return Err(ApiError::State(format!(
				"Deposit of {} would have exceeded \
                the token network deposit limit.",
				deposit_increase,
			)))
		}

		if total_deposit > channel_participant_deposit_limit {
			return Err(ApiError::State(format!(
				"Deposit of {} is larger than the \
                channel participant deposit limit",
				total_deposit,
			)))
		}

		if total_channel_deposit_overflow {
			return Err(ApiError::State(format!("Deposit overflow",)))
		}

		channel_proxy
			.approve_and_set_total_deposit(
				account.clone(),
				channel_state.canonical_identifier.channel_identifier,
				channel_state.partner_state.address,
				total_deposit,
				blockhash,
			)
			.await
			.map_err(ApiError::Proxy)?;

		waiting::wait_for_participant_deposit(
			self.raiden.state_manager.clone(),
			channel_state.token_network_registry_address,
			channel_state.token_address,
			channel_state.partner_state.address,
			channel_state.our_state.address,
			total_deposit,
			retry_timeout,
		)
		.await?;

		Ok(())
	}

	/// Initiate a withdraw from channel's balance.
	pub async fn channel_withdraw(
		&self,
		channel_state: &ChannelState,
		total_withdraw: TokenAmount,
	) -> Result<(), ApiError> {
		info!(
			message = "Withdraw from channel.",
			channel_identifier = channel_state.canonical_identifier.channel_identifier.to_string(),
			total_withdraw = total_withdraw.to_string(),
		);
		if channel_state.status() != ChannelStatus::Opened {
			return Err(ApiError::State(format!("Can't withdraw from a closed channel")))
		}

		let current_balance =
			views::channel_balance(&channel_state.our_state, &channel_state.partner_state);
		let amount_to_withdraw = total_withdraw.sub(channel_state.our_total_withdraw());
		if amount_to_withdraw > current_balance {
			return Err(ApiError::State(format!(
				"The withdraw of {} is bigger than the current balance of {}",
				amount_to_withdraw, current_balance
			)))
		}

		let recipient_address = channel_state.partner_state.address;
		let recipient_metadata = match query_address_metadata(
			self.raiden.config.pfs_config.url.clone(),
			recipient_address,
		)
		.await
		{
			Ok(metadata) => metadata,
			Err(e) => {
				error!(
					message = "Could not retrieve partner's address metadata",
					address = recipient_address.checksum(),
					error = format!("{:?}", e),
				);
				return Err(ApiError::State(format!(
					"Could not retrieve partner's address metadata"
				)))
			},
		};

		let state_change = ActionChannelWithdraw {
			canonical_identifier: channel_state.canonical_identifier.clone(),
			total_withdraw,
			recipient_metadata: Some(recipient_metadata),
		};

		if let Err(e) = self.transition_service.transition(vec![state_change.into()]).await {
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		if let Err(e) = waiting::wait_for_withdraw_complete(
			self.raiden.state_manager.clone(),
			channel_state.canonical_identifier.clone(),
			total_withdraw,
			Some(DEFAULT_RETRY_TIMEOUT),
		)
		.await
		{
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		Ok(())
	}

	/// Set the channel's reveal timeout.
	pub async fn channel_reveal_timeout(
		&self,
		channel_state: &ChannelState,
		reveal_timeout: RevealTimeout,
	) -> Result<(), ApiError> {
		info!(
			message = "Set reveal timeout for channel.",
			channel_identifier = channel_state.canonical_identifier.channel_identifier.to_string(),
			reveal_timeout = reveal_timeout.to_string(),
		);
		if channel_state.status() != ChannelStatus::Opened {
			return Err(ApiError::State(format!(
				"Can't update the reveal timeout of a closed channel"
			)))
		}

		if channel_state.settle_timeout < reveal_timeout.mul(2) {
			return Err(ApiError::State(format!(
				"`settle_timeout` can not be smaller than double the \
                `reveal_timeout`.\n \
                The setting `reveal_timeout` determines the maximum number of \
                blocks it should take a transaction to be mined when the \
                blockchain is under congestion. This setting determines the \
                when a node must go on-chain to register a secret, and it is \
                therefore the lower bound of the lock expiration. The \
                `settle_timeout` determines when a channel can be settled \
                on-chain, for this operation to be safe all locks must have \
                been resolved, for this reason the `settle_timeout` has to be \
                larger than `reveal_timeout`."
			)))
		}

		let state_change = ActionChannelSetRevealTimeout {
			canonical_identifier: channel_state.canonical_identifier.clone(),
			reveal_timeout,
		};

		if let Err(e) = self.transition_service.transition(vec![state_change.into()]).await {
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		Ok(())
	}

	/// Close a channel.
	pub async fn channel_close(
		&self,
		registry_address: Address,
		channel_state: &ChannelState,
	) -> Result<(), ApiError> {
		info!(
			message = "Close channel.",
			channel_identifier = channel_state.canonical_identifier.channel_identifier.to_string(),
		);
		if channel_state.status() != ChannelStatus::Opened {
			return Err(ApiError::State(format!("Attempted to close an already closed channel")))
		}
		self.channel_batch_close(
			registry_address,
			channel_state.token_address,
			vec![channel_state.partner_state.address],
			Some(DEFAULT_RETRY_TIMEOUT),
			true,
		)
		.await
	}

	/// Register a new token network.
	pub async fn token_network_register(
		&self,
		registry_address: Address,
		token_address: TokenAddress,
	) -> Result<TokenNetworkAddress, ApiError> {
		info!(
			message = "Register token network.",
			registry_address = registry_address.checksum(),
			token_address = token_address.checksum(),
		);
		if token_address == TokenAddress::zero() {
			return Err(ApiError::Param(format!("Token address must be non-zero")))
		}

		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let tokens_list = views::get_token_identifiers(&chain_state, registry_address);
		if tokens_list.contains(&token_address) {
			return Err(ApiError::Param(format!("Token already registered")))
		}

		let token_proxy = self
			.raiden
			.proxy_manager
			.token(token_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let token_network_registry = self
			.raiden
			.proxy_manager
			.token_network_registry(registry_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let (_, token_network_address) = token_network_registry
			.add_token(
				self.raiden.config.account.clone(),
				token_proxy,
				token_address,
				chain_state.block_hash,
			)
			.await
			.map_err(ApiError::Proxy)?;

		if let Err(e) = waiting::wait_for_token_network(
			self.raiden.state_manager.clone(),
			token_network_address,
			token_address,
			Some(DEFAULT_RETRY_TIMEOUT),
		)
		.await
		{
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}
		Ok(token_network_address)
	}

	/// Leave token network by token address.
	pub async fn token_network_leave(
		&self,
		registry_address: Address,
		token_address: TokenAddress,
	) -> Result<Vec<ChannelState>, ApiError> {
		info!(
			message = "Leave token network.",
			registry_address = registry_address.checksum(),
			token_address = token_address.checksum(),
		);
		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let channels: Vec<ChannelState> = match views::get_token_network_by_token_address(
			&chain_state,
			registry_address,
			token_address,
		)
		.map(|t| t.channelidentifiers_to_channels.values().cloned().collect())
		{
			Some(channels) => channels,
			None =>
				return Err(ApiError::State(format!(
					"Token {} is not registered with network {}",
					token_address.checksum(),
					registry_address.checksum()
				))),
		};

		self.channel_batch_close(
			registry_address,
			token_address,
			channels.iter().map(|c| c.partner_state.address).collect(),
			Some(DEFAULT_RETRY_TIMEOUT),
			true,
		)
		.await?;
		Ok(channels)
	}

	/// Batch close channels.
	///
	/// This will attempt to cooperatively settle a channel and then close it.
	pub async fn channel_batch_close(
		&self,
		registry_address: Address,
		token_address: TokenAddress,
		partners: Vec<Address>,
		retry_timeout: Option<RetryTimeout>,
		coop_settle: bool,
	) -> Result<(), ApiError> {
		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let valid_tokens = views::get_token_identifiers(&chain_state, registry_address);
		if !valid_tokens.contains(&token_address) {
			return Err(ApiError::State("Token address is not known".to_owned()))
		}
		let channels_to_close = views::filter_channels_by_partner_address(
			&chain_state,
			registry_address,
			token_address,
			partners,
		);

		if coop_settle {
			if let Err(e) = self.batch_coop_settle(channels_to_close.clone(), retry_timeout).await {
				error!(message = format!("{:?}.. skipping cooperative settle", e));
			}
		}

		let canonical_ids =
			channels_to_close.iter().map(|c| c.canonical_identifier.clone()).collect();

		let close_state_changes = channels_to_close
			.iter()
			.map(|c| {
				ActionChannelClose { canonical_identifier: c.canonical_identifier.clone() }.into()
			})
			.collect();

		if let Err(e) = self.transition_service.transition(close_state_changes).await {
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		if let Err(e) =
			waiting::wait_for_close(self.raiden.state_manager.clone(), canonical_ids, retry_timeout)
				.await
		{
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		Ok(())
	}

	/// Batch cooperative settle
	pub async fn batch_coop_settle(
		&self,
		channels: Vec<&ChannelState>,
		retry_timeout: Option<RetryTimeout>,
	) -> Result<Vec<ChannelState>, ApiError> {
		let mut coop_settle_state_changes: Vec<StateChange> = vec![];
		for channel in channels.iter() {
			let recipient_address = channel.partner_state.address;
			let recipient_metadata = match query_address_metadata(
				self.raiden.config.pfs_config.url.clone(),
				recipient_address,
			)
			.await
			{
				Ok(metadata) => metadata,
				Err(e) => {
					error!(
						message = "Partner is offline, coop settle is not possible",
						address = recipient_address.checksum(),
						error = format!("{:?}", e),
					);
					continue
				},
			};
			coop_settle_state_changes.push(
				ActionChannelCoopSettle {
					canonical_identifier: channel.canonical_identifier.clone(),
					recipient_metadata: Some(recipient_metadata),
				}
				.into(),
			);
		}

		if coop_settle_state_changes.is_empty() {
			return Ok(vec![])
		}

		if let Err(e) = self.transition_service.transition(coop_settle_state_changes).await {
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		let settling_channel_ids: Vec<CanonicalIdentifier> =
			channels.iter().map(|c| c.canonical_identifier.clone()).collect();

		let chain_state = self.raiden.state_manager.read().current_state.clone();

		let mut channels_to_settle: Vec<CanonicalIdentifier> = vec![];
		for channel_canonical_id in settling_channel_ids {
			if let Some(channel_to_settle) =
				views::get_channel_by_canonical_identifier(&chain_state, channel_canonical_id)
			{
				if channel_to_settle.our_state.initiated_coop_settle.is_none() {
					continue
				}

				channels_to_settle.push(channel_to_settle.canonical_identifier.clone());
			};
		}

		if let Err(e) = waiting::wait_for_coop_settle(
			self.raiden.web3.clone(),
			self.raiden.state_manager.clone(),
			channels_to_settle.clone(),
			retry_timeout,
		)
		.await
		{
			error!(message = format!("{:?}", e));
			return Err(ApiError::State(format!("{:?}", e)))
		}

		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let mut unsuccessful_channels: Vec<ChannelState> = vec![];
		for canonical_identifier in channels_to_settle {
			if let Some(new_channel_state) =
				views::get_channel_by_canonical_identifier(&chain_state, canonical_identifier)
			{
				if new_channel_state.status() != ChannelStatus::Settled {
					unsuccessful_channels.push(new_channel_state.clone());
				}
			}
		}
		Ok(unsuccessful_channels)
	}

	/// Deposit some amount to the UserDeposit contract.
	pub async fn deposit_to_udc(
		&self,
		user_deposit_address: Address,
		new_total_deposit: TokenAmount,
	) -> Result<(), ApiError> {
		info!(
			message = "Deposit to UDC",
			user_deposit_address = user_deposit_address.checksum(),
			new_total_deposit = new_total_deposit.to_string(),
		);
		let user_deposit_proxy = self
			.raiden
			.proxy_manager
			.user_deposit(user_deposit_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let confirmed_block_identifier = self.raiden.state_manager.read().current_state.block_hash;

		let current_total_deposit = user_deposit_proxy
			.total_deposit(self.raiden.config.account.address(), Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		let deposit_increase = new_total_deposit - current_total_deposit;

		let whole_balance = user_deposit_proxy
			.whole_balance(Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		let whole_balance_limit = user_deposit_proxy
			.whole_balance_limit(Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		let token_address = user_deposit_proxy
			.token_address(Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		let token_proxy = self
			.raiden
			.proxy_manager
			.token(token_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let balance = token_proxy
			.balance_of(self.raiden.config.account.address(), Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		if new_total_deposit <= current_total_deposit {
			return Err(ApiError::Param(format!("Total deposit did not increase")))
		}

		if whole_balance.checked_add(deposit_increase).is_none() {
			return Err(ApiError::Param(format!("Deposit overflow")))
		}

		if whole_balance.saturating_add(deposit_increase) > whole_balance_limit {
			return Err(ApiError::Param(format!(
				"Deposit of {:?} would have exceeded the UDC balance limit",
				deposit_increase
			)))
		}

		if balance < deposit_increase {
			return Err(ApiError::Param(format!(
				"Not enough balance to deposit. Available: {:?}, Needed: {:?}",
				balance, deposit_increase
			)))
		}

		if let Err(e) = user_deposit_proxy
			.deposit(
				self.raiden.config.account.clone(),
				token_proxy,
				new_total_deposit,
				confirmed_block_identifier,
			)
			.await
		{
			error!("Failed to set a new total deposit for UDC: {:?}", e);
			return Err(ApiError::Proxy(e))
		}
		Ok(())
	}

	/// Register desire to withdraw from the UserDeposit contract.
	///
	/// The amount stated will be withdrawable after certain blocks have passed.
	pub async fn plan_withdraw_from_udc(
		&self,
		user_deposit_address: Address,
		planned_withdraw_amount: TokenAmount,
	) -> Result<(), ApiError> {
		info!(
			message = "Plan withdraw from UDC",
			user_deposit_address = user_deposit_address.checksum(),
			planned_withdraw_amount = planned_withdraw_amount.to_string(),
		);
		let user_deposit_proxy = self
			.raiden
			.proxy_manager
			.user_deposit(user_deposit_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let confirmed_block_identifier = self.raiden.state_manager.read().current_state.block_hash;

		let balance = user_deposit_proxy
			.balance(self.raiden.config.account.address(), Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		if planned_withdraw_amount == TokenAmount::zero() {
			return Err(ApiError::Param(format!("Withdraw amount must be greater than zero")))
		}

		if planned_withdraw_amount > balance {
			return Err(ApiError::State(format!(
				"The withdraw amount of {} is bigger than the current balance of {}",
				planned_withdraw_amount, balance
			)))
		}

		if let Err(e) = user_deposit_proxy
			.plan_withdraw(
				self.raiden.config.account.clone(),
				planned_withdraw_amount,
				confirmed_block_identifier,
			)
			.await
		{
			error!("Failed to set a new total deposit for UDC: {:?}", e);
			return Err(ApiError::Proxy(e))
		}

		Ok(())
	}

	/// Actually perform the previously planned withdraw from the UserDeposit contract.
	pub async fn withdraw_from_udc(
		&self,
		user_deposit_address: Address,
		withdraw_amount: TokenAmount,
	) -> Result<(), ApiError> {
		info!(
			message = "Withdraw from UDC",
			user_deposit_address = user_deposit_address.checksum(),
			withdraw_amount = withdraw_amount.to_string(),
		);
		let user_deposit_proxy = self
			.raiden
			.proxy_manager
			.user_deposit(user_deposit_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let confirmed_block_identifier = chain_state.block_hash;
		let block_number = chain_state.block_number;
		drop(chain_state);

		let withdraw_plan = user_deposit_proxy
			.withdraw_plan(self.raiden.config.account.address(), Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		let whole_balance = user_deposit_proxy
			.whole_balance(Some(confirmed_block_identifier))
			.await
			.map_err(ApiError::Proxy)?;

		if withdraw_amount.is_zero() {
			return Err(ApiError::Param(format!("Withdraw amount must be greater than zero",)))
		}

		if withdraw_amount > withdraw_plan.withdraw_amount {
			return Err(ApiError::Param(format!("Withdraw more than planned")))
		}

		if block_number < withdraw_plan.withdraw_block {
			return Err(ApiError::Param(format!(
				"Withdrawing too early. Planned withdraw at block: {}, current_block {}",
				withdraw_plan.withdraw_block, confirmed_block_identifier
			)))
		}

		if whole_balance.checked_sub(withdraw_amount).is_none() {
			return Err(ApiError::Param(format!("Whole balance underflow")))
		}

		if let Err(e) = user_deposit_proxy
			.withdraw(
				self.raiden.config.account.clone(),
				withdraw_amount,
				confirmed_block_identifier,
			)
			.await
		{
			error!("Failed to set a new total deposit for UDC: {:?}", e);
			return Err(ApiError::Proxy(e))
		}

		Ok(())
	}

	/// Initiate a payment to partner.
	#[allow(clippy::too_many_arguments)]
	pub async fn initiate_payment(
		&self,
		account: Account<Http>,
		token_network_registry_address: TokenNetworkRegistryAddress,
		secret_registry_address: SecretRegistryAddress,
		token_address: TokenAddress,
		partner_address: Address,
		amount: TokenAmount,
		payment_identifier: Option<PaymentIdentifier>,
		secret: Option<String>,
		secret_hash: Option<SecretHash>,
		lock_timeout: Option<BlockTimeout>,
	) -> Result<Payment, ApiError> {
		info!(
			message = "Initiate payment",
			token_address = token_address.checksum(),
			partner_address = partner_address.checksum(),
			amount = amount.to_string(),
		);
		if account.address() == partner_address {
			return Err(ApiError::Param(format!("Address must be different for partner")))
		}

		if amount == TokenAmount::zero() {
			return Err(ApiError::Param(format!("Amount should not be zero")))
		}

		let chain_state = &self.raiden.state_manager.read().current_state.clone();
		let valid_tokens =
			views::get_token_identifiers(chain_state, token_network_registry_address);
		if !valid_tokens.contains(&token_address) {
			return Err(ApiError::Param(format!("Token address is not known")))
		}

		let payment_identifier = match payment_identifier {
			Some(identifier) => identifier,
			None => random_identifier(),
		};

		let token_network = views::get_token_network_by_token_address(
			chain_state,
			token_network_registry_address,
			token_address,
		)
		.ok_or(ApiError::Param(format!(
			"Token {} is not registered with network {}",
			token_address, token_network_registry_address
		)))?;
		let token_network_address = token_network.address;

		let secret = match secret {
			Some(secret) => Bytes(secret.as_bytes().to_vec()),
			None =>
				if secret_hash.is_none() {
					Bytes(random_secret().as_bytes().to_vec())
				} else {
					ABSENT_SECRET
				},
		};

		let secret_hash = match secret_hash {
			Some(hash) => hash,
			None => SecretHash::from_slice(&hash_secret(&secret.0)),
		};

		if !secret.0.is_empty() {
			let secrethash_from_secret = SecretHash::from_slice(&hash_secret(&secret.0));
			if secret_hash != secrethash_from_secret {
				return Err(ApiError::Param(format!("Provided secret and secret_hash do not match")))
			}
		}

		if secret.0.len() != SECRET_LENGTH as usize {
			return Err(ApiError::Param(format!("Secret of invalid length")))
		}

		let secret_registry_proxy = self
			.raiden
			.proxy_manager
			.secret_registry(secret_registry_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let secret_registered = secret_registry_proxy
			.is_secret_registered(secret_hash, None)
			.await
			.map_err(ApiError::Proxy)?;

		if secret_registered {
			return Err(ApiError::Param(format!(
				"Attempted to initiate a locked transfer with secrethash
                `{}`. That secret is already registered onchain",
				secret_hash,
			)))
		}

		if let Some(payment) =
			self.payments_registry.read().await.get(partner_address, payment_identifier)
		{
			let matches =
				payment.token_network_address == token_network_address && payment.amount == amount;
			if matches {
				return Err(ApiError::Param(format!(
					"Another payment with the same id is in flight"
				)))
			}
		}

		let payment_completed = self.payments_registry.write().await.register(
			token_network_address,
			partner_address,
			payment_identifier,
			amount,
		);

		let action_initiator_init = self
			.initiator_init(
				payment_identifier,
				amount,
				secret.clone(),
				secret_hash,
				token_network_registry_address,
				token_network_address,
				partner_address,
				lock_timeout,
				None,
			)
			.await;

		match action_initiator_init {
			Ok(action_init_initiator) => {
				if let Err(e) =
					self.transition_service.transition(vec![action_init_initiator.into()]).await
				{
					error!("{}", e);
					return Err(ApiError::State(e))
				}
			},
			Err(e) => {
				self.payments_registry.write().await.complete(PaymentStatus::Error(
					partner_address,
					payment_identifier,
					e.to_string(),
				));
				return Err(e)
			},
		}

		match payment_completed.await {
			Ok(status) => match status {
				PaymentStatus::Success(target, identifier) => Ok(Payment {
					target,
					payment_identifier: identifier,
					secret,
					secrethash: secret_hash,
				}),
				PaymentStatus::Error(_target, _identifier, error) => Err(ApiError::State(error)),
			},
			Err(e) => Err(ApiError::State(format!("Could not receive payment status: {:?}", e))),
		}
	}

	/// Mint a certain amount of tokens to a specific address.
	pub async fn mint_token_for(
		&self,
		token_address: TokenAddress,
		to: Address,
		value: TokenAmount,
	) -> Result<TransactionHash, ApiError> {
		info!(
			message = "Mint token",
			token_address = token_address.checksum(),
			to = to.checksum(),
			value = value.to_string()
		);
		let token_proxy = self
			.raiden
			.proxy_manager
			.token(token_address)
			.await
			.map_err(ApiError::ContractSpec)?;

		let transaction_hash = token_proxy
			.mint_for(self.raiden.config.account.clone(), to, value)
			.await
			.map_err(ApiError::Proxy)?;

		Ok(transaction_hash)
	}

	/// Check if settle timeout ratio with reveal timeout is correct.
	fn check_invalid_channel_timeouts(
		&self,
		settle_timeout: SettleTimeout,
		reveal_timeout: RevealTimeout,
	) -> Result<(), ApiError> {
		if reveal_timeout < RevealTimeout::from(MIN_REVEAL_TIMEOUT) {
			if reveal_timeout <= RevealTimeout::from(0) {
				return Err(ApiError::Param("reveal_timeout should be larger than zero.".to_owned()))
			} else {
				return Err(ApiError::Param(format!(
					"reveal_timeout is lower than the required minimum value of {}",
					MIN_REVEAL_TIMEOUT,
				)))
			}
		}

		if settle_timeout < SettleTimeout::from(reveal_timeout * 2) {
			return Err(ApiError::Param(
				"`settle_timeout` can not be smaller than double the `reveal_timeout`.\n\n
                The setting `reveal_timeout` determines the maximum number of
                blocks it should take a transaction to be mined when the
                blockchain is under congestion. This setting determines the
                when a node must go on-chain to register a secret, and it is
                therefore the lower bound of the lock expiration. The
                `settle_timeout` determines when a channel can be settled
                on-chain, for this operation to be safe all locks must have
                been resolved, for this reason the `settle_timeout` has to be
                larger than `reveal_timeout`."
					.to_owned(),
			))
		}

		Ok(())
	}

	/// Dispatch `ActionInitInitiator` to start a payment.
	#[allow(clippy::too_many_arguments)]
	async fn initiator_init(
		&self,
		transfer_identifier: PaymentIdentifier,
		transfer_amount: TokenAmount,
		transfer_secret: Secret,
		transfer_secrethash: SecretHash,
		token_network_registry_address: TokenNetworkRegistryAddress,
		token_network_address: TokenNetworkAddress,
		target_address: Address,
		lock_timeout: Option<BlockTimeout>,
		route_states: Option<Vec<RouteState>>,
	) -> Result<ActionInitInitiator, ApiError> {
		let chain_state = self.raiden.state_manager.read().current_state.clone();
		let our_address = chain_state.our_address;
		let transfer_state = TransferDescriptionWithSecretState {
			token_network_registry_address,
			token_network_address,
			lock_timeout,
			payment_identifier: transfer_identifier,
			amount: transfer_amount,
			initiator: our_address,
			target: target_address,
			secret: transfer_secret,
			secrethash: transfer_secrethash,
		};

		let our_address_metadata = self.raiden.config.metadata.clone();
		let one_to_n_address = self.raiden.config.addresses.one_to_n;
		let from_address = self.raiden.config.account.address();

		let route_states = if let Some(route_states) = route_states {
			route_states
		} else {
			let (routes, _feedback_token) = routing::get_best_routes(
				self.raiden.pfs.clone(),
				chain_state,
				our_address_metadata,
				token_network_address,
				Some(one_to_n_address),
				from_address,
				target_address,
				transfer_amount,
				None,
			)
			.await
			.map_err(ApiError::Routing)?;

			routes
		};

		Ok(ActionInitInitiator { transfer: transfer_state, routes: route_states })
	}
}