forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
eth.rs
5097 lines (4570 loc) · 207 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 super::eth::Action::{Call, Create};
#[cfg(feature = "enable-nft-integration")]
use crate::nft::nft_structs::{Chain, ContractType, TransactionNftDetails, WithdrawErc1155, WithdrawErc721};
use async_trait::async_trait;
use bitcrypto::{keccak256, ripemd160, sha256};
use common::custom_futures::repeatable::{Ready, Retry};
use common::custom_futures::timeout::FutureTimerExt;
use common::executor::{abortable_queue::AbortableQueue, AbortableSystem, AbortedError, Timer};
use common::log::{debug, error, info, warn};
use common::number_type_casting::SafeTypeCastingNumbers;
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};
use derive_more::Display;
use ethabi::{Contract, Function, 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, 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;
#[cfg(not(target_arch = "wasm32"))] 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, U64};
use web3::{self, Web3};
use web3_transport::{http_transport::HttpTransportNode, EthFeeHistoryNamespace, Web3Transport};
cfg_wasm32! {
use crypto::MetamaskArc;
use ethereum_types::{H264, H520};
use mm2_metamask::MetamaskError;
use web3::types::TransactionRequest;
}
use super::{coin_conf, AsyncMutex, BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner,
CoinProtocol, CoinTransportMetrics, CoinsContext, ConfirmPaymentInput, EthValidateFeeArgs, FeeApproxStage,
FoundSwapTxSpend, HistorySyncState, IguanaPrivKey, MakerSwapTakerCoin, MarketCoinOps, MmCoin,
MyAddressError, MyWalletAddress, NegotiateSwapContractAddrErr, NumConversError, NumConversResult,
PaymentInstructions, PaymentInstructionsErr, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed,
RawTransactionError, RawTransactionFut, RawTransactionRequest, RawTransactionRes, RawTransactionResult,
RefundError, RefundPaymentArgs, RefundResult, RpcClientType, RpcTransportEventHandler,
RpcTransportEventHandlerShared, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput,
SendPaymentArgs, SignatureError, SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradeFee,
TradePreimageError, TradePreimageFut, TradePreimageResult, TradePreimageValue, Transaction,
TransactionDetails, TransactionEnum, TransactionErr, TransactionFut, TxMarshalingErr,
UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr,
ValidateOtherPubKeyErr, ValidatePaymentError, ValidatePaymentFut, ValidatePaymentInput, VerificationError,
VerificationResult, WatcherOps, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest, WithdrawResult,
EARLY_CONFIRMATION_ERR_LOG, INSUFFICIENT_WATCHER_REWARD_ERR_LOG, INVALID_CONTRACT_ADDRESS_ERR_LOG,
INVALID_PAYMENT_STATE_ERR_LOG, INVALID_RECEIVER_ERR_LOG, INVALID_SENDER_ERR_LOG, INVALID_SWAP_ID_ERR_LOG};
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;
#[cfg(feature = "enable-nft-integration")]
use crate::nft::WithdrawNftResult;
#[cfg(feature = "enable-nft-integration")]
use crate::{lp_coinfind_or_err, MmCoinEnum, TransactionType};
use v2_activation::{build_address_and_priv_key_policy, EthActivationV2Error};
mod nonce;
use nonce::ParityNonce;
/// 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");
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
const ERC721_ABI: &str = include_str!("eth/erc721_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;
const ETH_GAS: u64 = 150_000;
/// 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 static ref ERC721_CONTRACT: Contract = Contract::load(ERC721_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 = "Timeout: {}", _0)]
Timeout(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 {
web3::Error::InvalidResponse(_) | web3::Error::Decoder(_) | web3::Error::Rpc(_) => {
Web3RpcError::InvalidResponse(error_str)
},
web3::Error::Unreachable | web3::Error::Transport(_) | web3::Error::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<Web3RpcError> for RawTransactionError {
fn from(e: Web3RpcError) -> Self {
match e {
Web3RpcError::Transport(tr) | Web3RpcError::InvalidResponse(tr) => RawTransactionError::Transport(tr),
Web3RpcError::Internal(internal) | Web3RpcError::Timeout(internal) => {
RawTransactionError::InternalError(internal)
},
}
}
}
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())
}
}
#[cfg(target_arch = "wasm32")]
impl From<MetamaskError> for Web3RpcError {
fn from(e: MetamaskError) -> Self {
match e {
MetamaskError::Internal(internal) => Web3RpcError::Internal(internal),
other => Web3RpcError::Transport(other.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) | Web3RpcError::Timeout(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) | Web3RpcError::Timeout(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::from(Web3RpcError::from(e)) }
}
impl From<Web3RpcError> for BalanceError {
fn from(e: Web3RpcError) -> Self {
match e {
Web3RpcError::Transport(tr) | Web3RpcError::InvalidResponse(tr) => BalanceError::Transport(tr),
Web3RpcError::Internal(internal) | Web3RpcError::Timeout(internal) => BalanceError::Internal(internal),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
struct SavedTraces {
/// ETH traces for my_address
traces: Vec<Trace>,
/// Earliest processed block
earliest_block: U64,
/// Latest processed block
latest_block: U64,
}
#[derive(Debug, Deserialize, Serialize)]
struct SavedErc20Events {
/// ERC20 events for my_address
events: Vec<Log>,
/// Earliest processed block
earliest_block: U64,
/// Latest processed block
latest_block: U64,
}
#[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(EthMetamaskPolicy),
}
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct EthMetamaskPolicy {
pub(crate) public_key: H264,
pub(crate) public_key_uncompressed: H520,
}
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>,
contract_supports_watchers: bool,
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)
}
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())
.compat()
.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())
.compat()
.map_err(|e| ERRL!("{}", e)),
)
}
#[cfg(not(target_arch = "wasm32"))]
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(not(target_arch = "wasm32"))]
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()
}
/// 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.into()))
.to_block(BlockNumber::Number(to_block.into()))
.address(vec![swap_contract_address])
.build();
Box::new(self.web3.eth().logs(filter).compat().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()))?;
get_tx_hex_by_hash_impl(coin, hash).await
}
async fn get_tx_hex_by_hash_impl(coin: EthCoin, tx_hash: H256) -> RawTransactionResult {
let web3_tx = coin
.web3
.eth()
.transaction(TransactionId::Hash(tx_hash))
.await?
.or_mm_err(|| RawTransactionError::HashNotExist(tx_hash.to_string()))?;
let raw = signed_tx_from_web3_tx(web3_tx).map_to_mm(RawTransactionError::InternalError)?;
Ok(RawTransactionRes {
tx_hex: BytesJson(rlp::encode(&raw).to_vec()),
})
}
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: Some(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),
..CallRequest::default()
};
// 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 (tx_hash, tx_hex) = match coin.priv_key_policy {
EthPrivKeyPolicy::KeyPair(ref key_pair) => {
let _nonce_lock = coin.nonce_lock.lock().await;
let nonce = get_addr_nonce(coin.my_address, coin.web3_instances.clone())
.compat()
.timeout_secs(30.)
.await?
.map_to_mm(WithdrawError::Transport)?;
let tx = UnSignedEthTx {
nonce,
value: eth_value,
action: Action::Call(call_addr),
data,
gas,
gas_price,
};
let signed = tx.sign(key_pair.secret(), coin.chain_id);
let bytes = rlp::encode(&signed);
(signed.hash, BytesJson::from(bytes.to_vec()))
},
#[cfg(target_arch = "wasm32")]
EthPrivKeyPolicy::Metamask(_) => {
if !req.broadcast {
let error = "Set 'broadcast' to generate, sign and broadcast a transaction with MetaMask".to_string();
return MmError::err(WithdrawError::BroadcastExpected(error));
}
let tx_to_send = TransactionRequest {
from: coin.my_address,
to: Some(to_addr),
gas: Some(gas),
gas_price: Some(gas_price),
value: Some(eth_value),
data: Some(data.clone().into()),
nonce: None,
..TransactionRequest::default()
};
// Wait for 10 seconds for the transaction to appear on the RPC node.
let wait_rpc_timeout = 10_000;
let check_every = 1.;
// Please note that this method may take a long time
// due to `wallet_switchEthereumChain` and `eth_sendTransaction` requests.
let tx_hash = coin.web3.eth().send_transaction(tx_to_send).await?;
let signed_tx = coin
.wait_for_tx_appears_on_rpc(tx_hash, wait_rpc_timeout, check_every)
.await?;
let tx_hex = signed_tx
.map(|tx| BytesJson::from(rlp::encode(&tx).to_vec()))
// Return an empty `tx_hex` if the transaction is still not appeared on the RPC node.
.unwrap_or_default();
(tx_hash, tx_hex)
},
};
let tx_hash_bytes = BytesJson::from(tx_hash.0.to_vec());
let tx_hash_str = format!("{:02x}", tx_hash_bytes);
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,
tx_hash: tx_hash_str,
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(),
memo: None,
})
}
#[cfg(feature = "enable-nft-integration")]
pub async fn withdraw_erc1155(ctx: MmArc, req: WithdrawErc1155) -> WithdrawNftResult {
let ticker = match req.chain {
Chain::Bsc => "BNB",
Chain::Eth => "ETH",
};
let _coin = lp_coinfind_or_err(&ctx, ticker).await?;
unimplemented!()
}
#[cfg(feature = "enable-nft-integration")]
pub async fn withdraw_erc721(ctx: MmArc, req: WithdrawErc721) -> WithdrawNftResult {
let ticker = match req.chain {
Chain::Bsc => "BNB",
Chain::Eth => "ETH",
};
let coin = lp_coinfind_or_err(&ctx, ticker).await?;
let eth_coin = match coin {
MmCoinEnum::EthCoin(eth_coin) => eth_coin,
_ => {
return MmError::err(WithdrawError::CoinDoesntSupportNftWithdraw {
coin: coin.ticker().to_owned(),
})
},
};
let from_addr = valid_addr_from_str(&req.from).map_to_mm(WithdrawError::InvalidAddress)?;
if eth_coin.my_address != from_addr {
return MmError::err(WithdrawError::AddressMismatchError {
my_address: eth_coin.my_address.to_string(),
from: req.from,
});
}
let to_addr = valid_addr_from_str(&req.to).map_to_mm(WithdrawError::InvalidAddress)?;
let token_addr = addr_from_str(&req.token_address).map_to_mm(WithdrawError::InvalidAddress)?;
let (eth_value, data, call_addr, fee_coin) = match eth_coin.coin_type {
EthCoinType::Eth => {
let function = ERC721_CONTRACT.function("safeTransferFrom")?;
let token_id_u256 = U256::from_dec_str(&req.token_id.to_string())
.map_err(|e| format!("{:?}", e))
.map_to_mm(NumConversError::new)?;
let data = function.encode_input(&[
Token::Address(from_addr),
Token::Address(to_addr),
Token::Uint(token_id_u256),
])?;
(0.into(), data, token_addr, eth_coin.ticker())
},
EthCoinType::Erc20 { .. } => {
return MmError::err(WithdrawError::InternalError(
"Erc20 coin type doesnt support withdraw nft".to_owned(),
))
},
};
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 = eth_coin.get_gas_price().compat().await?;
let estimate_gas_req = CallRequest {
value: Some(eth_value),
data: Some(data.clone().into()),
from: Some(eth_coin.my_address),
to: Some(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),
..CallRequest::default()
};
// Note if the wallet's balance is insufficient to withdraw, then `estimate_gas` may fail with the `Exception` error.
// Ideally we should determine the case when we have the insufficient balance and return `WithdrawError::NotSufficientBalance`.
let gas_limit = eth_coin.estimate_gas(estimate_gas_req).compat().await?;
(gas_limit, gas_price)
},
};
let _nonce_lock = eth_coin.nonce_lock.lock().await;
let nonce = get_addr_nonce(eth_coin.my_address, eth_coin.web3_instances.clone())
.compat()
.timeout_secs(30.)
.await?
.map_to_mm(WithdrawError::Transport)?;
let tx = UnSignedEthTx {
nonce,
value: eth_value,
action: Action::Call(call_addr),
data,
gas,
gas_price,
};
let secret = eth_coin.priv_key_policy.key_pair_or_err()?.secret();
let signed = tx.sign(secret, eth_coin.chain_id);
let signed_bytes = rlp::encode(&signed);
let fee_details = EthTxFeeDetails::new(gas, gas_price, fee_coin)?;
Ok(TransactionNftDetails {
tx_hex: BytesJson::from(signed_bytes.to_vec()),
tx_hash: format!("{:02x}", signed.tx_hash()),
from: vec![req.from],
to: vec![req.to],