forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
eth.rs
3936 lines (3549 loc) · 155 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, ripemd160, sha256};
use common::executor::{abortable_queue::AbortableQueue, AbortableSystem, AbortedError, Timer};
use common::log::{error, info, warn};
use common::{get_utc_timestamp, now_ms, small_rng, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::key_pair_from_secret;
use crypto::{CryptoCtx, CryptoCtxError, GlobalHDAccountArc, KeyPairPolicy};
#[cfg(target_arch = "wasm32")]
use crypto::{MetamaskArc, MetamaskWeak};
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, GuiAuthValidation, GuiAuthValidationGenerator, 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::convert::TryFrom;
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::{http_transport::HttpTransportNode, EthFeeHistoryNamespace, Web3Transport};
use super::{coin_conf, AsyncMutex, BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner,
CoinProtocol, CoinTransportMetrics, CoinsContext, FeeApproxStage, FoundSwapTxSpend, HistorySyncState,
IguanaPrivKey, MarketCoinOps, MmCoin, MyAddressError, NegotiateSwapContractAddrErr, NumConversError,
NumConversResult, PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy,
PrivKeyPolicyNotAllowed, RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionRes,
RawTransactionResult, RpcClientType, RpcTransportEventHandler, RpcTransportEventHandlerShared,
SearchForSwapTxSpendInput, SendMakerPaymentArgs, SendMakerRefundsPaymentArgs,
SendMakerSpendsTakerPaymentArgs, SendTakerPaymentArgs, SendTakerRefundsPaymentArgs,
SendTakerSpendsMakerPaymentArgs, SignatureError, SignatureResult, SwapOps, TradeFee, TradePreimageError,
TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction, TransactionDetails,
TransactionEnum, TransactionErr, TransactionFut, TxMarshalingErr, UnexpectedDerivationMethod,
ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr,
ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult,
WatcherOps, WatcherValidatePaymentInput, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest,
WithdrawResult};
pub use rlp;
#[cfg(test)] mod eth_tests;
#[cfg(target_arch = "wasm32")] mod eth_wasm_tests;
mod web3_transport;
#[path = "eth/v2_activation.rs"] pub mod v2_activation;
use v2_activation::build_address_and_priv_key_policy;
/// 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 = include_str!("eth/swap_contract_abi.json");
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
const ERC20_ABI: &str = include_str!("eth/erc20_abi.json");
/// 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;
const DEFAULT_REQUIRED_CONFIRMATIONS: u8 = 1;
const ETH_DECIMALS: u8 = 18;
/// 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 until the locktime is expired
const GAS_PRICE_APPROXIMATION_PERCENT_ON_WATCHER_PREIMAGE: 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;
/// Lifetime of generated signed message for gui-auth requests
const GUI_AUTH_SIGNED_MESSAGE_LIFETIME_SEC: i64 = 90;
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)]
pub 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 },
}
/// An alternative to `crate::PrivKeyBuildPolicy`, typical only for ETH coin.
pub enum EthPrivKeyBuildPolicy {
IguanaPrivKey(IguanaPrivKey),
GlobalHDAccount(GlobalHDAccountArc),
#[cfg(target_arch = "wasm32")]
Metamask(MetamaskArc),
}
impl EthPrivKeyBuildPolicy {
/// Detects the `EthPrivKeyBuildPolicy` with which the given `MmArc` is initialized.
pub fn detect_priv_key_policy(ctx: &MmArc) -> MmResult<EthPrivKeyBuildPolicy, CryptoCtxError> {
let crypto_ctx = CryptoCtx::from_ctx(ctx)?;
match crypto_ctx.key_pair_policy() {
KeyPairPolicy::Iguana => {
// Use an internal private key as the coin secret.
let priv_key = crypto_ctx.mm2_internal_privkey_secret();
Ok(EthPrivKeyBuildPolicy::IguanaPrivKey(priv_key))
},
KeyPairPolicy::GlobalHDAccount(global_hd) => Ok(EthPrivKeyBuildPolicy::GlobalHDAccount(global_hd.clone())),
}
}
}
impl TryFrom<PrivKeyBuildPolicy> for EthPrivKeyBuildPolicy {
type Error = PrivKeyPolicyNotAllowed;
/// Converts `PrivKeyBuildPolicy` to `EthPrivKeyBuildPolicy`
/// taking into account that ETH doesn't support `Trezor` yet.
fn try_from(policy: PrivKeyBuildPolicy) -> Result<Self, Self::Error> {
match policy {
PrivKeyBuildPolicy::IguanaPrivKey(iguana) => Ok(EthPrivKeyBuildPolicy::IguanaPrivKey(iguana)),
PrivKeyBuildPolicy::GlobalHDAccount(global_hd) => Ok(EthPrivKeyBuildPolicy::GlobalHDAccount(global_hd)),
PrivKeyBuildPolicy::Trezor => Err(PrivKeyPolicyNotAllowed::HardwareWalletNotSupported),
}
}
}
/// An alternative to `crate::PrivKeyPolicy`, typical only for ETH coin.
#[derive(Clone)]
pub enum EthPrivKeyPolicy {
KeyPair(KeyPair),
#[cfg(target_arch = "wasm32")]
Metamask(MetamaskWeak),
}
impl From<KeyPair> for EthPrivKeyPolicy {
fn from(key_pair: KeyPair) -> Self { EthPrivKeyPolicy::KeyPair(key_pair) }
}
impl EthPrivKeyPolicy {
pub fn key_pair_or_err(&self) -> MmResult<&KeyPair, PrivKeyPolicyNotAllowed> {
match self {
EthPrivKeyPolicy::KeyPair(key_pair) => Ok(key_pair),
#[cfg(target_arch = "wasm32")]
EthPrivKeyPolicy::Metamask(_) => MmError::err(PrivKeyPolicyNotAllowed::HardwareWalletNotSupported),
}
}
}
/// pImpl idiom.
pub struct EthCoinImpl {
ticker: String,
coin_type: EthCoinType,
priv_key_policy: EthPrivKeyPolicy,
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.
pub ctx: MmWeak,
chain_id: Option<u64>,
/// the block range used for eth_getLogs
logs_block_range: u64,
nonce_lock: Arc<AsyncMutex<()>>,
erc20_tokens_infos: Arc<Mutex<HashMap<String, Erc20TokenInfo>>>,
/// This spawner is used to spawn coin's related futures that should be aborted on coin deactivation
/// and on [`MmArc::stop`].
pub abortable_system: AbortableQueue,
}
#[derive(Clone, Debug)]
pub struct Web3Instance {
web3: Web3<Web3Transport>,
is_parity: bool,
}
#[derive(Clone, Debug)]
pub struct Erc20TokenInfo {
pub token_address: Address,
pub decimals: u8,
}
#[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)))
}
pub fn erc20_token_address(&self) -> Option<Address> {
match self.coin_type {
EthCoinType::Erc20 { token_addr, .. } => Some(token_addr),
EthCoinType::Eth => None,
}
}
pub fn add_erc_token_info(&self, ticker: String, info: Erc20TokenInfo) {
self.erc20_tokens_infos.lock().unwrap().insert(ticker, info);
}
/// ### WARNING
/// Be very careful using this function since it returns dereferenced clone
/// of value behind the MutexGuard and makes it non-thread-safe.
pub fn get_erc_tokens_infos(&self) -> HashMap<String, Erc20TokenInfo> {
let guard = self.erc20_tokens_infos.lock().unwrap();
(*guard).clone()
}
}
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 secret = coin.priv_key_policy.key_pair_or_err()?.secret();
let signed = tx.sign(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()?;
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)]
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, maker_payment: SendMakerPaymentArgs) -> TransactionFut {
let taker_addr = try_tx_fus!(addr_from_raw_pubkey(maker_payment.other_pubkey));
let swap_contract_address = try_tx_fus!(maker_payment.swap_contract_address.try_to_address());
Box::new(
self.send_hash_time_locked_payment(
self.etomic_swap_id(maker_payment.time_lock, maker_payment.secret_hash),
try_tx_fus!(wei_from_big_decimal(&maker_payment.amount, self.decimals)),
maker_payment.time_lock,
maker_payment.secret_hash,
taker_addr,
swap_contract_address,
)
.map(TransactionEnum::from),
)
}
fn send_taker_payment(&self, taker_payment: SendTakerPaymentArgs) -> TransactionFut {
let maker_addr = try_tx_fus!(addr_from_raw_pubkey(taker_payment.other_pubkey));
let swap_contract_address = try_tx_fus!(taker_payment.swap_contract_address.try_to_address());
Box::new(
self.send_hash_time_locked_payment(
self.etomic_swap_id(taker_payment.time_lock, taker_payment.secret_hash),
try_tx_fus!(wei_from_big_decimal(&taker_payment.amount, self.decimals)),
taker_payment.time_lock,
taker_payment.secret_hash,
maker_addr,
swap_contract_address,
)
.map(TransactionEnum::from),
)
}
fn send_maker_spends_taker_payment(
&self,
maker_spends_payment_args: SendMakerSpendsTakerPaymentArgs,
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(maker_spends_payment_args.other_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address =
try_tx_fus!(maker_spends_payment_args.swap_contract_address.try_to_address(), signed);
Box::new(
self.spend_hash_time_locked_payment(
signed,
maker_spends_payment_args.secret_hash,
swap_contract_address,
maker_spends_payment_args.secret,
)
.map(TransactionEnum::from),
)
}
fn send_taker_spends_maker_payment(
&self,
taker_spends_payment_args: SendTakerSpendsMakerPaymentArgs,
) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(taker_spends_payment_args.other_payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(taker_spends_payment_args.swap_contract_address.try_to_address());
Box::new(
self.spend_hash_time_locked_payment(
signed,
taker_spends_payment_args.secret_hash,
swap_contract_address,
taker_spends_payment_args.secret,
)
.map(TransactionEnum::from),
)
}
fn send_taker_refunds_payment(&self, taker_refunds_payment_args: SendTakerRefundsPaymentArgs) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(taker_refunds_payment_args.payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(taker_refunds_payment_args.swap_contract_address.try_to_address());
Box::new(
self.refund_hash_time_locked_payment(swap_contract_address, signed, taker_refunds_payment_args.secret_hash)
.map(TransactionEnum::from),
)
}
fn send_maker_refunds_payment(&self, maker_refunds_payment_args: SendMakerRefundsPaymentArgs) -> TransactionFut {
let tx: UnverifiedTransaction = try_tx_fus!(rlp::decode(maker_refunds_payment_args.payment_tx));
let signed = try_tx_fus!(SignedEthTx::new(tx));
let swap_contract_address = try_tx_fus!(maker_refunds_payment_args.swap_contract_address.try_to_address());
Box::new(
self.refund_hash_time_locked_payment(swap_contract_address, signed, maker_refunds_payment_args.secret_hash)
.map(TransactionEnum::from),
)
}
fn validate_fee(
&self,
validate_fee_args: ValidateFeeArgs<'_>,
) -> Box<dyn Future<Item = (), Error = String> + Send> {
let selfi = self.clone();
let tx = match validate_fee_args.fee_tx {
TransactionEnum::SignedEthTx(t) => t.clone(),
_ => panic!(),
};
let sender_addr = try_fus!(addr_from_raw_pubkey(validate_fee_args.expected_sender));
let fee_addr = try_fus!(addr_from_raw_pubkey(validate_fee_args.fee_addr));
let amount = validate_fee_args.amount.clone();
let min_block_number = validate_fee_args.min_block_number;
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) -> ValidatePaymentFut<()> {
let swap_contract_address = try_f!(input
.swap_contract_address