forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
eth.rs
3599 lines (3258 loc) · 144 KB
/
eth.rs
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
/******************************************************************************
* Copyright © 2022 Atomic Private Limited and its contributors *
* *
* See the CONTRIBUTOR-LICENSE-AGREEMENT, COPYING, LICENSE-COPYRIGHT-NOTICE *
* and DEVELOPER-CERTIFICATE-OF-ORIGIN files in the LEGAL directory in *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* AtomicDEX software, including this file may be copied, modified, propagated*
* or distributed except according to the terms contained in the *
* LICENSE-COPYRIGHT-NOTICE file. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
//
// eth.rs
// marketmaker
//
// Copyright © 2022 AtomicDEX. All rights reserved.
//
use async_trait::async_trait;
use bitcrypto::{keccak256, sha256};
use common::executor::Timer;
use common::log::{error, info, warn};
use common::{now_ms, small_rng, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::key_pair_from_secret;
use derive_more::Display;
use ethabi::{Contract, Token};
pub use ethcore_transaction::SignedTransaction as SignedEthTx;
use ethcore_transaction::{Action, Transaction as UnSignedEthTx, UnverifiedTransaction};
use ethereum_types::{Address, H160, H256, U256};
use ethkey::{public_to_address, KeyPair, Public, Signature};
use ethkey::{sign, verify_address};
use futures::compat::Future01CompatExt;
use futures::future::{join_all, select, Either, FutureExt, TryFutureExt};
use futures01::Future;
use http::StatusCode;
use mm2_core::mm_ctx::{MmArc, MmWeak};
use mm2_err_handle::prelude::*;
use mm2_net::transport::{slurp_url, SlurpError};
use mm2_number::{BigDecimal, MmNumber};
#[cfg(test)] use mocktopus::macros::*;
use rand::seq::SliceRandom;
use rpc::v1::types::Bytes as BytesJson;
use secp256k1::PublicKey;
use serde_json::{self as json, Value as Json};
use serialization::{CompactInteger, Serializable, Stream};
use sha3::{Digest, Keccak256};
use std::collections::HashMap;
use std::ops::Deref;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::{Arc, Mutex};
use web3::types::{Action as TraceAction, BlockId, BlockNumber, Bytes, CallRequest, FilterBuilder, Log, Trace,
TraceFilterBuilder, Transaction as Web3Transaction, TransactionId};
use web3::{self, Web3};
use web3_transport::{EthFeeHistoryNamespace, Web3Transport};
use super::{AsyncMutex, BalanceError, BalanceFut, CoinBalance, CoinProtocol, CoinTransportMetrics, CoinsContext,
FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MarketCoinOps, MmCoin, NegotiateSwapContractAddrErr,
NumConversError, NumConversResult, RawTransactionError, RawTransactionFut, RawTransactionRequest,
RawTransactionRes, RawTransactionResult, RpcClientType, RpcTransportEventHandler,
RpcTransportEventHandlerShared, SearchForSwapTxSpendInput, SignatureError, SignatureResult, SwapOps,
TradeFee, TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction,
TransactionDetails, TransactionEnum, TransactionErr, TransactionFut, UnexpectedDerivationMethod,
ValidateAddressResult, ValidatePaymentInput, VerificationError, VerificationResult, WithdrawError,
WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult};
pub use rlp;
#[cfg(test)] mod eth_tests;
#[cfg(target_arch = "wasm32")] mod eth_wasm_tests;
mod web3_transport;
/// https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol
/// Dev chain (195.201.0.6:8565) contract address: 0xa09ad3cd7e96586ebd05a2607ee56b56fb2db8fd
/// Ropsten: https://ropsten.etherscan.io/address/0x7bc1bbdd6a0a722fc9bffc49c921b685ecb84b94
/// ETH mainnet: https://etherscan.io/address/0x8500AFc0bc5214728082163326C2FF0C73f4a871
const SWAP_CONTRACT_ABI: &str = r#"[{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_amount","type":"uint256"},{"name":"_secret","type":"bytes32"},{"name":"_tokenAddress","type":"address"},{"name":"_sender","type":"address"}],"name":"receiverSpend","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"payments","outputs":[{"name":"paymentHash","type":"bytes20"},{"name":"lockTime","type":"uint64"},{"name":"state","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_receiver","type":"address"},{"name":"_secretHash","type":"bytes20"},{"name":"_lockTime","type":"uint64"}],"name":"ethPayment","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_amount","type":"uint256"},{"name":"_paymentHash","type":"bytes20"},{"name":"_tokenAddress","type":"address"},{"name":"_receiver","type":"address"}],"name":"senderRefund","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_id","type":"bytes32"},{"name":"_amount","type":"uint256"},{"name":"_tokenAddress","type":"address"},{"name":"_receiver","type":"address"},{"name":"_secretHash","type":"bytes20"},{"name":"_lockTime","type":"uint64"}],"name":"erc20Payment","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"bytes32"}],"name":"PaymentSent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"bytes32"},{"indexed":false,"name":"secret","type":"bytes32"}],"name":"ReceiverSpent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"id","type":"bytes32"}],"name":"SenderRefunded","type":"event"}]"#;
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
const ERC20_ABI: &str = r#"[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]"#;
/// Payment states from etomic swap smart contract: https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol#L5
pub const PAYMENT_STATE_UNINITIALIZED: u8 = 0;
pub const PAYMENT_STATE_SENT: u8 = 1;
const _PAYMENT_STATE_SPENT: u8 = 2;
const _PAYMENT_STATE_REFUNDED: u8 = 3;
// Ethgasstation API returns response in 10^8 wei units. So 10 from their API mean 1 gwei
const ETH_GAS_STATION_DECIMALS: u8 = 8;
const GAS_PRICE_PERCENT: u64 = 10;
/// It can change 12.5% max each block according to https://www.blocknative.com/blog/eip-1559-fees
const BASE_BLOCK_FEE_DIFF_PCT: u64 = 13;
const DEFAULT_LOGS_BLOCK_RANGE: u64 = 1000;
/// Take into account that the dynamic fee may increase by 3% during the swap.
const GAS_PRICE_APPROXIMATION_PERCENT_ON_START_SWAP: u64 = 3;
/// Take into account that the dynamic fee may increase at each of the following stages:
/// - it may increase by 2% until a swap is started;
/// - it may increase by 3% during the swap.
const GAS_PRICE_APPROXIMATION_PERCENT_ON_ORDER_ISSUE: u64 = 5;
/// Take into account that the dynamic fee may increase at each of the following stages:
/// - it may increase by 2% until an order is issued;
/// - it may increase by 2% until a swap is started;
/// - it may increase by 3% during the swap.
const GAS_PRICE_APPROXIMATION_PERCENT_ON_TRADE_PREIMAGE: u64 = 7;
lazy_static! {
pub static ref SWAP_CONTRACT: Contract = Contract::load(SWAP_CONTRACT_ABI.as_bytes()).unwrap();
pub static ref ERC20_CONTRACT: Contract = Contract::load(ERC20_ABI.as_bytes()).unwrap();
}
pub type Web3RpcFut<T> = Box<dyn Future<Item = T, Error = MmError<Web3RpcError>> + Send>;
pub type Web3RpcResult<T> = Result<T, MmError<Web3RpcError>>;
pub type GasStationResult = Result<GasStationData, MmError<GasStationReqErr>>;
#[derive(Debug, Display)]
pub enum GasStationReqErr {
#[display(fmt = "Transport '{}' error: {}", uri, error)]
Transport {
uri: String,
error: String,
},
#[display(fmt = "Invalid response: {}", _0)]
InvalidResponse(String),
Internal(String),
}
impl From<serde_json::Error> for GasStationReqErr {
fn from(e: serde_json::Error) -> Self { GasStationReqErr::InvalidResponse(e.to_string()) }
}
impl From<SlurpError> for GasStationReqErr {
fn from(e: SlurpError) -> Self {
let error = e.to_string();
match e {
SlurpError::ErrorDeserializing { .. } => GasStationReqErr::InvalidResponse(error),
SlurpError::Transport { uri, .. } | SlurpError::Timeout { uri, .. } => {
GasStationReqErr::Transport { uri, error }
},
SlurpError::Internal(_) | SlurpError::InvalidRequest(_) => GasStationReqErr::Internal(error),
}
}
}
#[derive(Debug, Display)]
pub enum Web3RpcError {
#[display(fmt = "Transport: {}", _0)]
Transport(String),
#[display(fmt = "Invalid response: {}", _0)]
InvalidResponse(String),
#[display(fmt = "Internal: {}", _0)]
Internal(String),
}
impl From<GasStationReqErr> for Web3RpcError {
fn from(err: GasStationReqErr) -> Self {
match err {
GasStationReqErr::Transport { .. } => Web3RpcError::Transport(err.to_string()),
GasStationReqErr::InvalidResponse(err) => Web3RpcError::InvalidResponse(err),
GasStationReqErr::Internal(err) => Web3RpcError::Internal(err),
}
}
}
impl From<serde_json::Error> for Web3RpcError {
fn from(e: serde_json::Error) -> Self { Web3RpcError::InvalidResponse(e.to_string()) }
}
impl From<web3::Error> for Web3RpcError {
fn from(e: web3::Error) -> Self {
let error_str = e.to_string();
match e.kind() {
web3::ErrorKind::InvalidResponse(_)
| web3::ErrorKind::Decoder(_)
| web3::ErrorKind::Msg(_)
| web3::ErrorKind::Rpc(_) => Web3RpcError::InvalidResponse(error_str),
web3::ErrorKind::Transport(_) | web3::ErrorKind::Io(_) => Web3RpcError::Transport(error_str),
_ => Web3RpcError::Internal(error_str),
}
}
}
impl From<web3::Error> for RawTransactionError {
fn from(e: web3::Error) -> Self { RawTransactionError::Transport(e.to_string()) }
}
impl From<ethabi::Error> for Web3RpcError {
fn from(e: ethabi::Error) -> Web3RpcError {
// Currently, we use the `ethabi` crate to work with a smart contract ABI known at compile time.
// It's an internal error if there are any issues during working with a smart contract ABI.
Web3RpcError::Internal(e.to_string())
}
}
impl From<ethabi::Error> for WithdrawError {
fn from(e: ethabi::Error) -> Self {
// Currently, we use the `ethabi` crate to work with a smart contract ABI known at compile time.
// It's an internal error if there are any issues during working with a smart contract ABI.
WithdrawError::InternalError(e.to_string())
}
}
impl From<web3::Error> for WithdrawError {
fn from(e: web3::Error) -> Self { WithdrawError::Transport(e.to_string()) }
}
impl From<Web3RpcError> for WithdrawError {
fn from(e: Web3RpcError) -> Self {
match e {
Web3RpcError::Transport(err) | Web3RpcError::InvalidResponse(err) => WithdrawError::Transport(err),
Web3RpcError::Internal(internal) => WithdrawError::InternalError(internal),
}
}
}
impl From<web3::Error> for TradePreimageError {
fn from(e: web3::Error) -> Self { TradePreimageError::Transport(e.to_string()) }
}
impl From<Web3RpcError> for TradePreimageError {
fn from(e: Web3RpcError) -> Self {
match e {
Web3RpcError::Transport(err) | Web3RpcError::InvalidResponse(err) => TradePreimageError::Transport(err),
Web3RpcError::Internal(internal) => TradePreimageError::InternalError(internal),
}
}
}
impl From<ethabi::Error> for TradePreimageError {
fn from(e: ethabi::Error) -> Self {
// Currently, we use the `ethabi` crate to work with a smart contract ABI known at compile time.
// It's an internal error if there are any issues during working with a smart contract ABI.
TradePreimageError::InternalError(e.to_string())
}
}
impl From<ethabi::Error> for BalanceError {
fn from(e: ethabi::Error) -> Self {
// Currently, we use the `ethabi` crate to work with a smart contract ABI known at compile time.
// It's an internal error if there are any issues during working with a smart contract ABI.
BalanceError::Internal(e.to_string())
}
}
impl From<web3::Error> for BalanceError {
fn from(e: web3::Error) -> Self { BalanceError::Transport(e.to_string()) }
}
#[derive(Debug, Deserialize, Serialize)]
struct SavedTraces {
/// ETH traces for my_address
traces: Vec<Trace>,
/// Earliest processed block
earliest_block: U256,
/// Latest processed block
latest_block: U256,
}
#[derive(Debug, Deserialize, Serialize)]
struct SavedErc20Events {
/// ERC20 events for my_address
events: Vec<Log>,
/// Earliest processed block
earliest_block: U256,
/// Latest processed block
latest_block: U256,
}
#[derive(Debug, PartialEq, Eq)]
enum EthCoinType {
/// Ethereum itself or it's forks: ETC/others
Eth,
/// ERC20 token with smart contract address
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
Erc20 { platform: String, token_addr: Address },
}
/// pImpl idiom.
#[derive(Debug)]
pub struct EthCoinImpl {
ticker: String,
coin_type: EthCoinType,
key_pair: KeyPair,
my_address: Address,
sign_message_prefix: Option<String>,
swap_contract_address: Address,
fallback_swap_contract: Option<Address>,
web3: Web3<Web3Transport>,
/// The separate web3 instances kept to get nonce, will replace the web3 completely soon
web3_instances: Vec<Web3Instance>,
decimals: u8,
gas_station_url: Option<String>,
gas_station_decimals: u8,
gas_station_policy: GasStationPricePolicy,
history_sync_state: Mutex<HistorySyncState>,
required_confirmations: AtomicU64,
/// Coin needs access to the context in order to reuse the logging and shutdown facilities.
/// Using a weak reference by default in order to avoid circular references and leaks.
ctx: MmWeak,
chain_id: Option<u64>,
/// the block range used for eth_getLogs
logs_block_range: u64,
nonce_lock: Arc<AsyncMutex<()>>,
}
#[derive(Clone, Debug)]
pub struct Web3Instance {
web3: Web3<Web3Transport>,
is_parity: bool,
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "format")]
pub enum EthAddressFormat {
/// Single-case address (lowercase)
#[serde(rename = "singlecase")]
SingleCase,
/// Mixed-case address.
/// https://eips.ethereum.org/EIPS/eip-55
#[serde(rename = "mixedcase")]
MixedCase,
}
#[cfg_attr(test, mockable)]
async fn make_gas_station_request(url: &str) -> GasStationResult {
let resp = slurp_url(url).await?;
if resp.0 != StatusCode::OK {
let error = format!("Gas price request failed with status code {}", resp.0);
return MmError::err(GasStationReqErr::Transport {
uri: url.to_owned(),
error,
});
}
let result: GasStationData = json::from_slice(&resp.2)?;
Ok(result)
}
#[cfg_attr(test, mockable)]
impl EthCoinImpl {
/// Gets Transfer events from ERC20 smart contract `addr` between `from_block` and `to_block`
fn erc20_transfer_events(
&self,
contract: Address,
from_addr: Option<Address>,
to_addr: Option<Address>,
from_block: BlockNumber,
to_block: BlockNumber,
limit: Option<usize>,
) -> Box<dyn Future<Item = Vec<Log>, Error = String> + Send> {
let contract_event = try_fus!(ERC20_CONTRACT.event("Transfer"));
let topic0 = Some(vec![contract_event.signature()]);
let topic1 = from_addr.map(|addr| vec![addr.into()]);
let topic2 = to_addr.map(|addr| vec![addr.into()]);
let mut filter = FilterBuilder::default()
.topics(topic0, topic1, topic2, None)
.from_block(from_block)
.to_block(to_block)
.address(vec![contract]);
if let Some(l) = limit {
filter = filter.limit(l);
}
Box::new(self.web3.eth().logs(filter.build()).map_err(|e| ERRL!("{}", e)))
}
/// Gets ETH traces from ETH node between addresses in `from_block` and `to_block`
fn eth_traces(
&self,
from_addr: Vec<Address>,
to_addr: Vec<Address>,
from_block: BlockNumber,
to_block: BlockNumber,
limit: Option<usize>,
) -> Box<dyn Future<Item = Vec<Trace>, Error = String> + Send> {
let mut filter = TraceFilterBuilder::default()
.from_address(from_addr)
.to_address(to_addr)
.from_block(from_block)
.to_block(to_block);
if let Some(l) = limit {
filter = filter.count(l);
}
Box::new(self.web3.trace().filter(filter.build()).map_err(|e| ERRL!("{}", e)))
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn eth_traces_path(&self, ctx: &MmArc) -> PathBuf {
ctx.dbdir()
.join("TRANSACTIONS")
.join(format!("{}_{:#02x}_trace.json", self.ticker, self.my_address))
}
/// Load saved ETH traces from local DB
#[cfg(not(target_arch = "wasm32"))]
fn load_saved_traces(&self, ctx: &MmArc) -> Option<SavedTraces> {
let content = gstuff::slurp(&self.eth_traces_path(ctx));
if content.is_empty() {
None
} else {
match json::from_slice(&content) {
Ok(t) => Some(t),
Err(_) => None,
}
}
}
/// Load saved ETH traces from local DB
#[cfg(target_arch = "wasm32")]
fn load_saved_traces(&self, _ctx: &MmArc) -> Option<SavedTraces> {
common::panic_w("'load_saved_traces' is not implemented in WASM");
unreachable!()
}
/// Store ETH traces to local DB
#[cfg(not(target_arch = "wasm32"))]
fn store_eth_traces(&self, ctx: &MmArc, traces: &SavedTraces) {
let content = json::to_vec(traces).unwrap();
let tmp_file = format!("{}.tmp", self.eth_traces_path(ctx).display());
std::fs::write(&tmp_file, content).unwrap();
std::fs::rename(tmp_file, self.eth_traces_path(ctx)).unwrap();
}
/// Store ETH traces to local DB
#[cfg(target_arch = "wasm32")]
fn store_eth_traces(&self, _ctx: &MmArc, _traces: &SavedTraces) {
common::panic_w("'store_eth_traces' is not implemented in WASM");
unreachable!()
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn erc20_events_path(&self, ctx: &MmArc) -> PathBuf {
ctx.dbdir()
.join("TRANSACTIONS")
.join(format!("{}_{:#02x}_events.json", self.ticker, self.my_address))
}
/// Store ERC20 events to local DB
#[cfg(not(target_arch = "wasm32"))]
fn store_erc20_events(&self, ctx: &MmArc, events: &SavedErc20Events) {
let content = json::to_vec(events).unwrap();
let tmp_file = format!("{}.tmp", self.erc20_events_path(ctx).display());
std::fs::write(&tmp_file, content).unwrap();
std::fs::rename(tmp_file, self.erc20_events_path(ctx)).unwrap();
}
/// Store ERC20 events to local DB
#[cfg(target_arch = "wasm32")]
fn store_erc20_events(&self, _ctx: &MmArc, _events: &SavedErc20Events) {
common::panic_w("'store_erc20_events' is not implemented in WASM");
unreachable!()
}
/// Load saved ERC20 events from local DB
#[cfg(not(target_arch = "wasm32"))]
fn load_saved_erc20_events(&self, ctx: &MmArc) -> Option<SavedErc20Events> {
let content = gstuff::slurp(&self.erc20_events_path(ctx));
if content.is_empty() {
None
} else {
match json::from_slice(&content) {
Ok(t) => Some(t),
Err(_) => None,
}
}
}
/// Load saved ERC20 events from local DB
#[cfg(target_arch = "wasm32")]
fn load_saved_erc20_events(&self, _ctx: &MmArc) -> Option<SavedErc20Events> {
common::panic_w("'load_saved_erc20_events' is not implemented in WASM");
unreachable!()
}
/// The id used to differentiate payments on Etomic swap smart contract
fn etomic_swap_id(&self, time_lock: u32, secret_hash: &[u8]) -> Vec<u8> {
let mut input = vec![];
input.extend_from_slice(&time_lock.to_le_bytes());
input.extend_from_slice(secret_hash);
sha256(&input).to_vec()
}
fn estimate_gas(&self, req: CallRequest) -> Box<dyn Future<Item = U256, Error = web3::Error> + Send> {
// always using None block number as old Geth version accept only single argument in this RPC
Box::new(self.web3.eth().estimate_gas(req, None))
}
/// Gets `ReceiverSpent` events from etomic swap smart contract since `from_block`
fn spend_events(
&self,
swap_contract_address: Address,
from_block: u64,
to_block: u64,
) -> Box<dyn Future<Item = Vec<Log>, Error = String> + Send> {
let contract_event = try_fus!(SWAP_CONTRACT.event("ReceiverSpent"));
let filter = FilterBuilder::default()
.topics(Some(vec![contract_event.signature()]), None, None, None)
.from_block(BlockNumber::Number(from_block))
.to_block(BlockNumber::Number(to_block))
.address(vec![swap_contract_address])
.build();
Box::new(self.web3.eth().logs(filter).map_err(|e| ERRL!("{}", e)))
}
/// Gets `SenderRefunded` events from etomic swap smart contract since `from_block`
fn refund_events(
&self,
swap_contract_address: Address,
from_block: u64,
to_block: u64,
) -> Box<dyn Future<Item = Vec<Log>, Error = String> + Send> {
let contract_event = try_fus!(SWAP_CONTRACT.event("SenderRefunded"));
let filter = FilterBuilder::default()
.topics(Some(vec![contract_event.signature()]), None, None, None)
.from_block(BlockNumber::Number(from_block))
.to_block(BlockNumber::Number(to_block))
.address(vec![swap_contract_address])
.build();
Box::new(self.web3.eth().logs(filter).map_err(|e| ERRL!("{}", e)))
}
/// Try to parse address from string.
pub fn address_from_str(&self, address: &str) -> Result<Address, String> {
Ok(try_s!(valid_addr_from_str(address)))
}
}
async fn get_raw_transaction_impl(coin: EthCoin, req: RawTransactionRequest) -> RawTransactionResult {
let tx = match req.tx_hash.strip_prefix("0x") {
Some(tx) => tx,
None => &req.tx_hash,
};
let hash = H256::from_str(tx).map_to_mm(|e| RawTransactionError::InvalidHashError(e.to_string()))?;
let web3_tx = coin.web3.eth().transaction(TransactionId::Hash(hash)).compat().await?;
let web3_tx = web3_tx.or_mm_err(|| RawTransactionError::HashNotExist(req.tx_hash))?;
let raw = signed_tx_from_web3_tx(web3_tx).map_to_mm(RawTransactionError::InternalError)?;
Ok(RawTransactionRes {
tx_hex: BytesJson(rlp::encode(&raw)),
})
}
async fn withdraw_impl(coin: EthCoin, req: WithdrawRequest) -> WithdrawResult {
let to_addr = coin
.address_from_str(&req.to)
.map_to_mm(WithdrawError::InvalidAddress)?;
let my_balance = coin.my_balance().compat().await?;
let my_balance_dec = u256_to_big_decimal(my_balance, coin.decimals)?;
let (mut wei_amount, dec_amount) = if req.max {
(my_balance, my_balance_dec.clone())
} else {
let wei_amount = wei_from_big_decimal(&req.amount, coin.decimals)?;
(wei_amount, req.amount.clone())
};
if wei_amount > my_balance {
return MmError::err(WithdrawError::NotSufficientBalance {
coin: coin.ticker.clone(),
available: my_balance_dec.clone(),
required: dec_amount,
});
};
let (mut eth_value, data, call_addr, fee_coin) = match &coin.coin_type {
EthCoinType::Eth => (wei_amount, vec![], to_addr, coin.ticker()),
EthCoinType::Erc20 { platform, token_addr } => {
let function = ERC20_CONTRACT.function("transfer")?;
let data = function.encode_input(&[Token::Address(to_addr), Token::Uint(wei_amount)])?;
(0.into(), data, *token_addr, platform.as_str())
},
};
let eth_value_dec = u256_to_big_decimal(eth_value, coin.decimals)?;
let (gas, gas_price) = match req.fee {
Some(WithdrawFee::EthGas { gas_price, gas }) => {
let gas_price = wei_from_big_decimal(&gas_price, 9)?;
(gas.into(), gas_price)
},
Some(fee_policy) => {
let error = format!("Expected 'EthGas' fee type, found {:?}", fee_policy);
return MmError::err(WithdrawError::InvalidFeePolicy(error));
},
None => {
let gas_price = coin.get_gas_price().compat().await?;
// covering edge case by deducting the standard transfer fee when we want to max withdraw ETH
let eth_value_for_estimate = if req.max && coin.coin_type == EthCoinType::Eth {
eth_value - gas_price * U256::from(21000)
} else {
eth_value
};
let estimate_gas_req = CallRequest {
value: Some(eth_value_for_estimate),
data: Some(data.clone().into()),
from: Some(coin.my_address),
to: call_addr,
gas: None,
// gas price must be supplied because some smart contracts base their
// logic on gas price, e.g. TUSD: https://github.com/KomodoPlatform/atomicDEX-API/issues/643
gas_price: Some(gas_price),
};
// TODO Note if the wallet's balance is insufficient to withdraw, then `estimate_gas` may fail with the `Exception` error.
// TODO Ideally we should determine the case when we have the insufficient balance and return `WithdrawError::NotSufficientBalance`.
let gas_limit = coin.estimate_gas(estimate_gas_req).compat().await?;
(gas_limit, gas_price)
},
};
let total_fee = gas * gas_price;
let total_fee_dec = u256_to_big_decimal(total_fee, coin.decimals)?;
if req.max && coin.coin_type == EthCoinType::Eth {
if eth_value < total_fee || wei_amount < total_fee {
return MmError::err(WithdrawError::AmountTooLow {
amount: eth_value_dec,
threshold: total_fee_dec,
});
}
eth_value -= total_fee;
wei_amount -= total_fee;
};
let _nonce_lock = coin.nonce_lock.lock().await;
let nonce_fut = get_addr_nonce(coin.my_address, coin.web3_instances.clone()).compat();
let nonce = match select(nonce_fut, Timer::sleep(30.)).await {
Either::Left((nonce_res, _)) => nonce_res.map_to_mm(WithdrawError::Transport)?,
Either::Right(_) => return MmError::err(WithdrawError::Transport("Get address nonce timed out".to_owned())),
};
let tx = UnSignedEthTx {
nonce,
value: eth_value,
action: Action::Call(call_addr),
data,
gas,
gas_price,
};
let signed = tx.sign(coin.key_pair.secret(), coin.chain_id);
let bytes = rlp::encode(&signed);
let amount_decimal = u256_to_big_decimal(wei_amount, coin.decimals)?;
let mut spent_by_me = amount_decimal.clone();
let received_by_me = if to_addr == coin.my_address {
amount_decimal.clone()
} else {
0.into()
};
let fee_details = EthTxFeeDetails::new(gas, gas_price, fee_coin)?;
if coin.coin_type == EthCoinType::Eth {
spent_by_me += &fee_details.total_fee;
}
let my_address = coin.my_address().map_to_mm(WithdrawError::InternalError)?;
Ok(TransactionDetails {
to: vec![checksum_address(&format!("{:#02x}", to_addr))],
from: vec![my_address],
total_amount: amount_decimal,
my_balance_change: &received_by_me - &spent_by_me,
spent_by_me,
received_by_me,
tx_hex: bytes.into(),
tx_hash: format!("{:02x}", signed.tx_hash()),
block_height: 0,
fee_details: Some(fee_details.into()),
coin: coin.ticker.clone(),
internal_id: vec![].into(),
timestamp: now_ms() / 1000,
kmd_rewards: None,
transaction_type: Default::default(),
})
}
#[derive(Clone, Debug)]
pub struct EthCoin(Arc<EthCoinImpl>);
impl Deref for EthCoin {
type Target = EthCoinImpl;
fn deref(&self) -> &EthCoinImpl { &*self.0 }
}
#[async_trait]
impl SwapOps for EthCoin {
fn send_taker_fee(&self, fee_addr: &[u8], amount: BigDecimal, _uuid: &[u8]) -> TransactionFut {
let address = try_tx_fus!(addr_from_raw_pubkey(fee_addr));
Box::new(
self.send_to_address(address, try_tx_fus!(wei_from_big_decimal(&amount, self.decimals)))
.map(TransactionEnum::from),
)
}
fn send_maker_payment(
&self,
time_lock: u32,
taker_pub: &[u8],
secret_hash: &[u8],
amount: BigDecimal,
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let taker_addr = try_tx_fus!(addr_from_raw_pubkey(taker_pub));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address());
Box::new(
self.send_hash_time_locked_payment(
self.etomic_swap_id(time_lock, secret_hash),
try_tx_fus!(wei_from_big_decimal(&amount, self.decimals)),
time_lock,
secret_hash,
taker_addr,
swap_contract_address,
)
.map(TransactionEnum::from),
)
}
fn send_taker_payment(
&self,
time_lock: u32,
maker_pub: &[u8],
secret_hash: &[u8],
amount: BigDecimal,
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let maker_addr = try_tx_fus!(addr_from_raw_pubkey(maker_pub));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address());
Box::new(
self.send_hash_time_locked_payment(
self.etomic_swap_id(time_lock, secret_hash),
try_tx_fus!(wei_from_big_decimal(&amount, self.decimals)),
time_lock,
secret_hash,
maker_addr,
swap_contract_address,
)
.map(TransactionEnum::from),
)
}
fn send_maker_spends_taker_payment(
&self,
taker_payment_tx: &[u8],
_time_lock: u32,
_taker_pub: &[u8],
secret: &[u8],
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(taker_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address(), signed);
Box::new(
self.spend_hash_time_locked_payment(signed, swap_contract_address, secret)
.map(TransactionEnum::from),
)
}
fn send_taker_spends_maker_payment(
&self,
maker_payment_tx: &[u8],
_time_lock: u32,
_maker_pub: &[u8],
secret: &[u8],
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(maker_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address());
Box::new(
self.spend_hash_time_locked_payment(signed, swap_contract_address, secret)
.map(TransactionEnum::from),
)
}
fn send_taker_refunds_payment(
&self,
taker_payment_tx: &[u8],
_time_lock: u32,
_maker_pub: &[u8],
_secret_hash: &[u8],
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(taker_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address());
Box::new(
self.refund_hash_time_locked_payment(swap_contract_address, signed)
.map(TransactionEnum::from),
)
}
fn send_maker_refunds_payment(
&self,
maker_payment_tx: &[u8],
_time_lock: u32,
_taker_pub: &[u8],
_secret_hash: &[u8],
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(maker_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(swap_contract_address.try_to_address());
Box::new(
self.refund_hash_time_locked_payment(swap_contract_address, signed)
.map(TransactionEnum::from),
)
}
fn validate_fee(
&self,
fee_tx: &TransactionEnum,
expected_sender: &[u8],
fee_addr: &[u8],
amount: &BigDecimal,
min_block_number: u64,
_uuid: &[u8],
) -> Box<dyn Future<Item = (), Error = String> + Send> {
let selfi = self.clone();
let tx = match fee_tx {
TransactionEnum::SignedEthTx(t) => t.clone(),
_ => panic!(),
};
let sender_addr = try_fus!(addr_from_raw_pubkey(expected_sender));
let fee_addr = try_fus!(addr_from_raw_pubkey(fee_addr));
let amount = amount.clone();
let fut = async move {
let expected_value = try_s!(wei_from_big_decimal(&amount, selfi.decimals));
let tx_from_rpc = try_s!(
selfi
.web3
.eth()
.transaction(TransactionId::Hash(tx.hash))
.compat()
.await
);
let tx_from_rpc = match tx_from_rpc {
Some(t) => t,
None => return ERR!("Didn't find provided tx {:?} on ETH node", tx),
};
if tx_from_rpc.from != sender_addr {
return ERR!(
"Fee tx {:?} was sent from wrong address, expected {:?}",
tx_from_rpc,
sender_addr
);
}
if let Some(block_number) = tx_from_rpc.block_number {
if block_number <= min_block_number.into() {
return ERR!(
"Fee tx {:?} confirmed before min_block {}",
tx_from_rpc,
min_block_number,
);
}
}
match &selfi.coin_type {
EthCoinType::Eth => {
if tx_from_rpc.to != Some(fee_addr) {
return ERR!(
"Fee tx {:?} was sent to wrong address, expected {:?}",
tx_from_rpc,
fee_addr
);
}
if tx_from_rpc.value < expected_value {
return ERR!(
"Fee tx {:?} value is less than expected {:?}",
tx_from_rpc,
expected_value
);
}
},
EthCoinType::Erc20 {
platform: _,
token_addr,
} => {
if tx_from_rpc.to != Some(*token_addr) {
return ERR!(
"ERC20 Fee tx {:?} called wrong smart contract, expected {:?}",
tx_from_rpc,
token_addr
);
}
let function = try_s!(ERC20_CONTRACT.function("transfer"));
let decoded_input = try_s!(function.decode_input(&tx_from_rpc.input.0));
if decoded_input[0] != Token::Address(fee_addr) {
return ERR!(
"ERC20 Fee tx was sent to wrong address {:?}, expected {:?}",
decoded_input[0],
fee_addr
);
}
match decoded_input[1] {
Token::Uint(value) => {
if value < expected_value {
return ERR!("ERC20 Fee tx value {} is less than expected {}", value, expected_value);
}
},
_ => return ERR!("Should have got uint token but got {:?}", decoded_input[1]),
}
},
}
Ok(())
};
Box::new(fut.boxed().compat())
}
fn validate_maker_payment(&self, input: ValidatePaymentInput) -> Box<dyn Future<Item = (), Error = String> + Send> {
let swap_contract_address = try_fus!(input.swap_contract_address.try_to_address());
self.validate_payment(
&input.payment_tx,
input.time_lock,
&input.other_pub,
&input.secret_hash,
input.amount,
swap_contract_address,
)
}
fn validate_taker_payment(&self, input: ValidatePaymentInput) -> Box<dyn Future<Item = (), Error = String> + Send> {
let swap_contract_address = try_fus!(input.swap_contract_address.try_to_address());
self.validate_payment(
&input.payment_tx,
input.time_lock,
&input.other_pub,
&input.secret_hash,
input.amount,
swap_contract_address,
)
}
fn check_if_my_payment_sent(
&self,
time_lock: u32,
_other_pub: &[u8],
secret_hash: &[u8],
from_block: u64,
swap_contract_address: &Option<BytesJson>,
_swap_unique_data: &[u8],
) -> Box<dyn Future<Item = Option<TransactionEnum>, Error = String> + Send> {
let id = self.etomic_swap_id(time_lock, secret_hash);
let swap_contract_address = try_fus!(swap_contract_address.try_to_address());
let selfi = self.clone();
let fut = async move {
let status = try_s!(
selfi
.payment_status(swap_contract_address, Token::FixedBytes(id.clone()))
.compat()
.await
);
if status == PAYMENT_STATE_UNINITIALIZED.into() {
return Ok(None);
};
let mut current_block = try_s!(selfi.current_block().compat().await);
if current_block < from_block {
current_block = from_block;
}
let mut from_block = from_block;
loop {
let to_block = current_block.min(from_block + selfi.logs_block_range);
let events = try_s!(
selfi
.payment_sent_events(swap_contract_address, from_block, to_block)
.compat()
.await
);
let found = events.iter().find(|event| &event.data.0[..32] == id.as_slice());
match found {
Some(event) => {
let transaction = try_s!(
selfi
.web3
.eth()
.transaction(TransactionId::Hash(event.transaction_hash.unwrap()))
.compat()
.await
);
match transaction {