forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy patheth.rs
7019 lines (6308 loc) · 294 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 © 2023 Pampex LTD and TillyHK LTD *
* *
* 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 *
* Komodo DeFi Framework 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 © 2023 Pampex LTD and TillyHK LTD. All rights reserved.
//
use super::eth::Action::{Call, Create};
use super::watcher_common::{validate_watcher_reward, REWARD_GAS_AMOUNT};
use super::*;
use crate::coin_balance::{EnableCoinBalanceError, EnabledCoinBalanceParams, HDAccountBalance, HDAddressBalance,
HDBalanceAddress, HDWalletBalance, HDWalletBalanceOps};
use crate::eth::eth_rpc::ETH_RPC_REQUEST_TIMEOUT;
use crate::eth::web3_transport::websocket_transport::{WebsocketTransport, WebsocketTransportNode};
use crate::hd_wallet::{HDAccountOps, HDCoinAddress, HDCoinHDAccount, HDCoinHDAddress, HDCoinWithdrawOps,
HDConfirmAddress, HDPathAccountToAddressId, HDWalletCoinOps, HDXPubExtractor};
use crate::lp_price::get_base_price_in_rel;
use crate::nft::nft_errors::ParseContractTypeError;
use crate::nft::nft_structs::{ContractType, ConvertChain, NftInfo, TransactionNftDetails, WithdrawErc1155,
WithdrawErc721};
use crate::nft::WithdrawNftResult;
use crate::rpc_command::account_balance::{AccountBalanceParams, AccountBalanceRpcOps, HDAccountBalanceResponse};
use crate::rpc_command::get_new_address::{GetNewAddressParams, GetNewAddressResponse, GetNewAddressRpcError,
GetNewAddressRpcOps};
use crate::rpc_command::hd_account_balance_rpc_error::HDAccountBalanceRpcError;
use crate::rpc_command::init_account_balance::{InitAccountBalanceParams, InitAccountBalanceRpcOps};
use crate::rpc_command::init_create_account::{CreateAccountRpcError, CreateAccountState, CreateNewAccountParams,
InitCreateAccountRpcOps};
use crate::rpc_command::init_scan_for_new_addresses::{InitScanAddressesRpcOps, ScanAddressesParams,
ScanAddressesResponse};
use crate::rpc_command::init_withdraw::{InitWithdrawCoin, WithdrawTaskHandleShared};
use crate::rpc_command::{account_balance, get_new_address, init_account_balance, init_create_account,
init_scan_for_new_addresses};
use crate::{coin_balance, scan_for_new_addresses_impl, BalanceResult, CoinWithDerivationMethod, DerivationMethod,
DexFee, MakerNftSwapOpsV2, ParseCoinAssocTypes, ParseNftAssocTypes, PayForGasParams, PrivKeyPolicy,
RefundMakerPaymentArgs, RpcCommonOps, SendNftMakerPaymentArgs, SpendNftMakerPaymentArgs, ToBytes,
ValidateNftMakerPaymentArgs, ValidateWatcherSpendInput, WatcherSpendType};
use async_trait::async_trait;
use bitcrypto::{dhash160, keccak256, ripemd160, sha256};
use common::custom_futures::repeatable::{Ready, Retry, RetryOnError};
use common::custom_futures::timeout::FutureTimerExt;
use common::executor::{abortable_queue::AbortableQueue, AbortOnDropHandle, AbortSettings, AbortableSystem,
AbortedError, SpawnAbortable, Timer};
use common::log::{debug, error, info, warn};
use common::number_type_casting::SafeTypeCastingNumbers;
use common::{get_utc_timestamp, now_sec, small_rng, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::key_pair_from_secret;
use crypto::{Bip44Chain, CryptoCtx, CryptoCtxError, GlobalHDAccountArc, KeyPairPolicy};
use derive_more::Display;
use enum_derives::EnumFromStringify;
use ethabi::{Contract, Function, Token};
use ethcore_transaction::tx_builders::TxBuilderError;
use ethcore_transaction::{Action, TransactionWrapper, TransactionWrapperBuilder as UnSignedEthTxBuilder,
UnverifiedEip1559Transaction, UnverifiedEip2930Transaction, UnverifiedLegacyTransaction,
UnverifiedTransactionWrapper};
pub use ethcore_transaction::{SignedTransaction as SignedEthTx, TxType};
use ethereum_types::{Address, H160, H256, U256};
use ethkey::{public_to_address, sign, verify_address, KeyPair, Public, Signature};
use futures::compat::Future01CompatExt;
use futures::future::{join, join_all, select_ok, try_join_all, Either, FutureExt, TryFutureExt};
use futures01::Future;
use http::Uri;
use instant::Instant;
use keys::Public as HtlcPubKey;
use mm2_core::mm_ctx::{MmArc, MmWeak};
use mm2_event_stream::behaviour::{EventBehaviour, EventInitStatus};
use mm2_net::transport::{GuiAuthValidation, GuiAuthValidationGenerator};
use mm2_number::bigdecimal_custom::CheckedDivision;
use mm2_number::{BigDecimal, BigUint, MmNumber};
#[cfg(test)] use mocktopus::macros::*;
use rand::seq::SliceRandom;
use rlp::{DecoderError, Encodable, RlpStream};
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, TryInto};
use std::ops::Deref;
use std::str::from_utf8;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use web3::types::{Action as TraceAction, BlockId, BlockNumber, Bytes, CallRequest, FilterBuilder, Log, Trace,
TraceFilterBuilder, Transaction as Web3Transaction, TransactionId, U64};
use web3::{self, Web3};
cfg_wasm32! {
use common::{now_ms, wait_until_ms};
use crypto::MetamaskArc;
use ethereum_types::{H264, H520};
use mm2_metamask::MetamaskError;
use web3::types::TransactionRequest;
}
use super::{coin_conf, lp_coinfind_or_err, AsyncMutex, BalanceError, BalanceFut, CheckIfMyPaymentSentArgs,
CoinBalance, CoinFutSpawner, CoinProtocol, CoinTransportMetrics, CoinsContext, ConfirmPaymentInput,
EthValidateFeeArgs, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, IguanaPrivKey, MakerSwapTakerCoin,
MarketCoinOps, MmCoin, MmCoinEnum, MyAddressError, MyWalletAddress, NegotiateSwapContractAddrErr,
NumConversError, NumConversResult, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr,
PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed, RawTransactionError, RawTransactionFut,
RawTransactionRequest, RawTransactionRes, RawTransactionResult, RefundError, RefundPaymentArgs,
RefundResult, RewardTarget, RpcClientType, RpcTransportEventHandler, RpcTransportEventHandlerShared,
SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs, SignEthTransactionParams,
SignRawTransactionEnum, SignRawTransactionRequest, SignatureError, SignatureResult, SpendPaymentArgs,
SwapOps, SwapTxFeePolicy, TakerSwapMakerCoin, TradeFee, TradePreimageError, TradePreimageFut,
TradePreimageResult, TradePreimageValue, Transaction, TransactionDetails, TransactionEnum, TransactionErr,
TransactionFut, TransactionType, TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult,
ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError,
ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult, WaitForHTLCTxSpendArgs,
WatcherOps, WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput,
WatcherValidatePaymentInput, WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut,
WithdrawRequest, WithdrawResult, EARLY_CONFIRMATION_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_native! {
use std::path::PathBuf;
}
mod eth_balance_events;
mod eth_rpc;
#[cfg(test)] mod eth_tests;
#[cfg(target_arch = "wasm32")] mod eth_wasm_tests;
#[cfg(any(test, target_arch = "wasm32"))] mod for_tests;
pub(crate) mod nft_swap_v2;
mod web3_transport;
use web3_transport::{http_transport::HttpTransportNode, Web3Transport};
pub mod eth_hd_wallet;
use eth_hd_wallet::EthHDWallet;
#[path = "eth/v2_activation.rs"] pub mod v2_activation;
use v2_activation::{build_address_and_priv_key_policy, EthActivationV2Error};
mod eth_withdraw;
use eth_withdraw::{EthWithdraw, InitEthWithdraw, StandardEthWithdraw};
mod nonce;
use nonce::ParityNonce;
mod eip1559_gas_fee;
pub(crate) use eip1559_gas_fee::FeePerGasEstimated;
use eip1559_gas_fee::{BlocknativeGasApiCaller, FeePerGasSimpleEstimator, GasApiConfig, GasApiProvider,
InfuraGasApiCaller};
/// https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol
/// Dev chain (195.201.137.5:8565) contract address: 0x83965C539899cC0F918552e5A26915de40ee8852
/// Ropsten: https://ropsten.etherscan.io/address/0x7bc1bbdd6a0a722fc9bffc49c921b685ecb84b94
/// ETH mainnet: https://etherscan.io/address/0x8500AFc0bc5214728082163326C2FF0C73f4a871
pub const SWAP_CONTRACT_ABI: &str = include_str!("eth/swap_contract_abi.json");
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
pub 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");
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
const ERC1155_ABI: &str = include_str!("eth/erc1155_abi.json");
const NFT_SWAP_CONTRACT_ABI: &str = include_str!("eth/nft_swap_contract_abi.json");
/// Payment states from etomic swap smart contract: https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol#L5
pub enum PaymentState {
Uninitialized,
Sent,
Spent,
Refunded,
}
#[allow(dead_code)]
pub(crate) enum MakerPaymentStateV2 {
Uninitialized,
PaymentSent,
TakerSpent,
MakerRefunded,
}
#[allow(dead_code)]
pub(crate) enum TakerPaymentStateV2 {
Uninitialized,
PaymentSent,
TakerApproved,
MakerSpent,
TakerRefunded,
}
/// 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;
pub(crate) const ETH_DECIMALS: u8 = 18;
pub(crate) const ETH_GWEI_DECIMALS: u8 = 9;
/// 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;
/// Heuristic gas limits for withdraw and swap operations (for swaps also including extra margin value for possible changes in opcodes gas)
pub mod gas_limit {
/// Gas limit for sending coins
pub const ETH_SEND_COINS: u64 = 21_000;
/// Gas limit for transfer ERC20 tokens
/// TODO: maybe this is too much and 150K is okay
pub const ETH_SEND_ERC20: u64 = 210_000;
/// Gas limit for swap payment tx with coins
/// real values are approx 48,6K by etherscan
pub const ETH_PAYMENT: u64 = 65_000;
/// Gas limit for swap payment tx with ERC20 tokens
/// real values are 98,9K
pub const ERC20_PAYMENT: u64 = 120_000;
/// Gas limit for swap receiver spend tx with coins
/// real values are 40,7K
pub const ETH_RECEIVER_SPEND: u64 = 65_000;
/// Gas limit for swap receiver spend tx with ERC20 tokens
/// real values are 72,8K
pub const ERC20_RECEIVER_SPEND: u64 = 120_000;
/// Gas limit for swap refund tx with coins
pub const ETH_SENDER_REFUND: u64 = 100_000;
/// Gas limit for swap refund tx with with ERC20 tokens
pub const ERC20_SENDER_REFUND: u64 = 150_000;
/// Gas limit for other operations
pub const ETH_MAX_TRADE_GAS: u64 = 150_000;
}
/// Lifetime of generated signed message for gui-auth requests
const GUI_AUTH_SIGNED_MESSAGE_LIFETIME_SEC: i64 = 90;
/// Max transaction type according to EIP-2718
const ETH_MAX_TX_TYPE: u64 = 0x7f;
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 static ref ERC1155_CONTRACT: Contract = Contract::load(ERC1155_ABI.as_bytes()).unwrap();
pub static ref NFT_SWAP_CONTRACT: Contract = Contract::load(NFT_SWAP_CONTRACT_ABI.as_bytes()).unwrap();
}
pub type EthDerivationMethod = DerivationMethod<Address, EthHDWallet>;
pub type Web3RpcFut<T> = Box<dyn Future<Item = T, Error = MmError<Web3RpcError>> + Send>;
pub type Web3RpcResult<T> = Result<T, MmError<Web3RpcError>>;
type EthPrivKeyPolicy = PrivKeyPolicy<KeyPair>;
#[macro_export]
macro_rules! wei_from_gwei_decimal {
($big_decimal: expr) => {
$crate::eth::wei_from_big_decimal($big_decimal, $crate::eth::ETH_GWEI_DECIMALS)
};
}
#[macro_export]
macro_rules! wei_to_gwei_decimal {
($gwei: expr) => {
$crate::eth::u256_to_big_decimal($gwei, $crate::eth::ETH_GWEI_DECIMALS)
};
}
#[derive(Clone, Debug)]
pub(crate) struct LegacyGasPrice {
pub(crate) gas_price: U256,
}
#[derive(Clone, Debug)]
pub(crate) struct Eip1559FeePerGas {
pub(crate) max_fee_per_gas: U256,
pub(crate) max_priority_fee_per_gas: U256,
}
/// Internal structure describing how transaction pays for gas unit:
/// either legacy gas price or EIP-1559 fee per gas
#[derive(Clone, Debug)]
pub(crate) enum PayForGasOption {
Legacy(LegacyGasPrice),
Eip1559(Eip1559FeePerGas),
}
impl PayForGasOption {
fn get_gas_price(&self) -> Option<U256> {
match self {
PayForGasOption::Legacy(LegacyGasPrice { gas_price }) => Some(*gas_price),
PayForGasOption::Eip1559(..) => None,
}
}
fn get_fee_per_gas(&self) -> (Option<U256>, Option<U256>) {
match self {
PayForGasOption::Eip1559(Eip1559FeePerGas {
max_fee_per_gas,
max_priority_fee_per_gas,
}) => (Some(*max_fee_per_gas), Some(*max_priority_fee_per_gas)),
PayForGasOption::Legacy(..) => (None, None),
}
}
}
impl TryFrom<PayForGasParams> for PayForGasOption {
fn try_from(param: PayForGasParams) -> Result<Self, Self::Error> {
match param {
PayForGasParams::Legacy(legacy) => Ok(Self::Legacy(LegacyGasPrice {
gas_price: wei_from_gwei_decimal!(&legacy.gas_price)?,
})),
PayForGasParams::Eip1559(eip1559) => Ok(Self::Eip1559(Eip1559FeePerGas {
max_fee_per_gas: wei_from_gwei_decimal!(&eip1559.max_fee_per_gas)?,
max_priority_fee_per_gas: wei_from_gwei_decimal!(&eip1559.max_priority_fee_per_gas)?,
})),
}
}
type Error = MmError<NumConversError>;
}
type GasDetails = (U256, PayForGasOption);
#[derive(Debug, Display, EnumFromStringify)]
pub enum Web3RpcError {
#[display(fmt = "Transport: {}", _0)]
Transport(String),
#[from_stringify("serde_json::Error")]
#[display(fmt = "Invalid response: {}", _0)]
InvalidResponse(String),
#[display(fmt = "Timeout: {}", _0)]
Timeout(String),
#[display(fmt = "Internal: {}", _0)]
Internal(String),
#[display(fmt = "Invalid gas api provider config: {}", _0)]
InvalidGasApiConfig(String),
#[display(fmt = "Nft Protocol is not supported yet!")]
NftProtocolNotSupported,
#[display(fmt = "Number conversion: {}", _0)]
NumConversError(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<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)
| Web3RpcError::NumConversError(internal)
| Web3RpcError::InvalidGasApiConfig(internal) => RawTransactionError::InternalError(internal),
Web3RpcError::NftProtocolNotSupported => {
RawTransactionError::InternalError("Nft Protocol is not supported yet!".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<UnexpectedDerivationMethod> for Web3RpcError {
fn from(e: UnexpectedDerivationMethod) -> Self { 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<NumConversError> for Web3RpcError {
fn from(e: NumConversError) -> Self { Web3RpcError::NumConversError(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)
| Web3RpcError::Timeout(internal)
| Web3RpcError::NumConversError(internal)
| Web3RpcError::InvalidGasApiConfig(internal) => WithdrawError::InternalError(internal),
Web3RpcError::NftProtocolNotSupported => WithdrawError::NftProtocolNotSupported,
}
}
}
impl From<ethcore_transaction::Error> for WithdrawError {
fn from(e: ethcore_transaction::Error) -> Self { WithdrawError::SigningError(e.to_string()) }
}
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)
| Web3RpcError::NumConversError(internal)
| Web3RpcError::InvalidGasApiConfig(internal) => TradePreimageError::InternalError(internal),
Web3RpcError::NftProtocolNotSupported => TradePreimageError::NftProtocolNotSupported,
}
}
}
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)
| Web3RpcError::NumConversError(internal)
| Web3RpcError::InvalidGasApiConfig(internal) => BalanceError::Internal(internal),
Web3RpcError::NftProtocolNotSupported => {
BalanceError::Internal("Nft Protocol is not supported yet!".to_string())
},
}
}
}
impl From<TxBuilderError> for TransactionErr {
fn from(e: TxBuilderError) -> Self { TransactionErr::Plain(e.to_string()) }
}
impl From<ethcore_transaction::Error> for TransactionErr {
fn from(e: ethcore_transaction::Error) -> Self { TransactionErr::Plain(e.to_string()) }
}
#[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(Clone, 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,
},
Nft {
platform: String,
},
}
/// An alternative to `crate::PrivKeyBuildPolicy`, typical only for ETH coin.
pub enum EthPrivKeyBuildPolicy {
IguanaPrivKey(IguanaPrivKey),
GlobalHDAccount(GlobalHDAccountArc),
#[cfg(target_arch = "wasm32")]
Metamask(MetamaskArc),
Trezor,
}
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 From<PrivKeyBuildPolicy> for EthPrivKeyBuildPolicy {
fn from(policy: PrivKeyBuildPolicy) -> Self {
match policy {
PrivKeyBuildPolicy::IguanaPrivKey(iguana) => EthPrivKeyBuildPolicy::IguanaPrivKey(iguana),
PrivKeyBuildPolicy::GlobalHDAccount(global_hd) => EthPrivKeyBuildPolicy::GlobalHDAccount(global_hd),
PrivKeyBuildPolicy::Trezor => EthPrivKeyBuildPolicy::Trezor,
}
}
}
/// Gas fee estimator loop context, runs a loop to estimate max fee and max priority fee per gas according to EIP-1559 for the next block
///
/// This FeeEstimatorContext handles rpc requests which start and stop gas fee estimation loop and handles the loop itself.
/// FeeEstimatorContext keeps the latest estimated gas fees to return them on rpc request
pub(crate) struct FeeEstimatorContext {
/// Latest estimated gas fee values
pub(crate) estimated_fees: Arc<AsyncMutex<FeePerGasEstimated>>,
/// Handler for estimator loop graceful shutdown
pub(crate) abort_handler: AsyncMutex<Option<AbortOnDropHandle>>,
}
/// Gas fee estimator creation state
pub(crate) enum FeeEstimatorState {
/// Gas fee estimation not supported for this coin
CoinNotSupported,
/// Platform coin required to be enabled for gas fee estimation for this coin
PlatformCoinRequired,
/// Fee estimator created, use simple internal estimator
Simple(AsyncMutex<FeeEstimatorContext>),
/// Fee estimator created, use provider or simple internal estimator (if provider fails)
Provider(AsyncMutex<FeeEstimatorContext>),
}
/// pImpl idiom.
pub struct EthCoinImpl {
ticker: String,
pub coin_type: EthCoinType,
priv_key_policy: EthPrivKeyPolicy,
/// Either an Iguana address or a 'EthHDWallet' instance.
/// Arc is used to use the same hd wallet from platform coin if we need to.
/// This allows the reuse of the same derived accounts/addresses of the
/// platform coin for tokens and vice versa.
derivation_method: Arc<EthDerivationMethod>,
sign_message_prefix: Option<String>,
swap_contract_address: Address,
fallback_swap_contract: Option<Address>,
contract_supports_watchers: bool,
web3_instances: AsyncMutex<Vec<Web3Instance>>,
decimals: u8,
history_sync_state: Mutex<HistorySyncState>,
required_confirmations: AtomicU64,
swap_txfee_policy: Mutex<SwapTxFeePolicy>,
max_eth_tx_type: Option<u64>,
/// 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: u64,
/// The name of the coin with which Trezor wallet associates this asset.
trezor_coin: Option<String>,
/// the block range used for eth_getLogs
logs_block_range: u64,
/// A mapping of Ethereum addresses to their respective nonce locks.
/// This is used to ensure that only one transaction is sent at a time per address.
/// Each address is associated with an `AsyncMutex` which is locked when a transaction is being created and sent,
/// and unlocked once the transaction is confirmed. This prevents nonce conflicts when multiple transactions
/// are initiated concurrently from the same address.
address_nonce_locks: Arc<AsyncMutex<HashMap<String, Arc<AsyncMutex<()>>>>>,
erc20_tokens_infos: Arc<Mutex<HashMap<String, Erc20TokenInfo>>>,
/// Stores information about NFTs owned by the user. Each entry in the HashMap is uniquely identified by a composite key
/// consisting of the token address and token ID, separated by a comma. This field is essential for tracking the NFT assets
/// information (chain & contract type, amount etc.), where ownership and amount, in ERC1155 case, might change over time.
pub nfts_infos: Arc<AsyncMutex<HashMap<String, NftInfo>>>,
/// Context for eth fee per gas estimator loop. Created if coin supports fee per gas estimation
pub(crate) platform_fee_estimator_state: Arc<FeeEstimatorState>,
/// 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,
}
/// Information about a token that follows the ERC20 protocol on an EVM-based network.
#[derive(Clone, Debug)]
pub struct Erc20TokenInfo {
/// The contract address of the token on the EVM-based network.
pub token_address: Address,
/// The number of decimal places the token uses.
/// This represents the smallest unit that the token can be divided into.
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,
}
/// get tx type from pay_for_gas_option
/// currently only type2 and legacy supported
/// if for Eth Classic we also want support for type 1 then use a fn
#[macro_export]
macro_rules! tx_type_from_pay_for_gas_option {
($pay_for_gas_option: expr) => {
if matches!($pay_for_gas_option, PayForGasOption::Eip1559(..)) {
ethcore_transaction::TxType::Type2
} else {
ethcore_transaction::TxType::Legacy
}
};
}
impl EthCoinImpl {
#[cfg(not(target_arch = "wasm32"))]
fn eth_traces_path(&self, ctx: &MmArc, my_address: Address) -> PathBuf {
ctx.dbdir()
.join("TRANSACTIONS")
.join(format!("{}_{:#02x}_trace.json", self.ticker, my_address))
}
/// Load saved ETH traces from local DB
#[cfg(not(target_arch = "wasm32"))]
fn load_saved_traces(&self, ctx: &MmArc, my_address: Address) -> Option<SavedTraces> {
let content = gstuff::slurp(&self.eth_traces_path(ctx, my_address));
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, _my_address: Address) -> 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, my_address: Address, traces: &SavedTraces) {
let content = json::to_vec(traces).unwrap();
let tmp_file = format!("{}.tmp", self.eth_traces_path(ctx, my_address).display());
std::fs::write(&tmp_file, content).unwrap();
std::fs::rename(tmp_file, self.eth_traces_path(ctx, my_address)).unwrap();
}
/// Store ETH traces to local DB
#[cfg(target_arch = "wasm32")]
fn store_eth_traces(&self, _ctx: &MmArc, _my_address: Address, _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, my_address: Address) -> PathBuf {
ctx.dbdir()
.join("TRANSACTIONS")
.join(format!("{}_{:#02x}_events.json", self.ticker, my_address))
}
/// Store ERC20 events to local DB
#[cfg(not(target_arch = "wasm32"))]
fn store_erc20_events(&self, ctx: &MmArc, my_address: Address, events: &SavedErc20Events) {
let content = json::to_vec(events).unwrap();
let tmp_file = format!("{}.tmp", self.erc20_events_path(ctx, my_address).display());
std::fs::write(&tmp_file, content).unwrap();
std::fs::rename(tmp_file, self.erc20_events_path(ctx, my_address)).unwrap();
}
/// Store ERC20 events to local DB
#[cfg(target_arch = "wasm32")]
fn store_erc20_events(&self, _ctx: &MmArc, _my_address: Address, _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, my_address: Address) -> Option<SavedErc20Events> {
let content = gstuff::slurp(&self.erc20_events_path(ctx, my_address));
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, _my_address: Address) -> 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
pub(crate) fn etomic_swap_id(&self, time_lock: u32, secret_hash: &[u8]) -> Vec<u8> {
let timelock_bytes = time_lock.to_le_bytes();
let mut input = Vec::with_capacity(timelock_bytes.len() + secret_hash.len());
input.extend_from_slice(&timelock_bytes);
input.extend_from_slice(secret_hash);
sha256(&input).to_vec()
}
/// 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 | EthCoinType::Nft { .. } => 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
.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 {
StandardEthWithdraw::new(coin.clone(), req)?.build().await
}
#[async_trait]
impl InitWithdrawCoin for EthCoin {
async fn init_withdraw(
&self,
ctx: MmArc,
req: WithdrawRequest,
task_handle: WithdrawTaskHandleShared,
) -> Result<TransactionDetails, MmError<WithdrawError>> {
InitEthWithdraw::new(ctx, self.clone(), req, task_handle)?.build().await
}
}
/// `withdraw_erc1155` function returns details of `ERC-1155` transaction including tx hex,
/// which should be sent to`send_raw_transaction` RPC to broadcast the transaction.
pub async fn withdraw_erc1155(ctx: MmArc, withdraw_type: WithdrawErc1155) -> WithdrawNftResult {
let coin = lp_coinfind_or_err(&ctx, withdraw_type.chain.to_ticker()).await?;
let (to_addr, token_addr, eth_coin) =
get_valid_nft_addr_to_withdraw(coin, &withdraw_type.to, &withdraw_type.token_address)?;
let token_id_str = &withdraw_type.token_id.to_string();
let wallet_amount = eth_coin.erc1155_balance(token_addr, token_id_str).await?;
let amount_dec = if withdraw_type.max {
wallet_amount.clone()
} else {
withdraw_type.amount.unwrap_or_else(|| 1.into())
};
if amount_dec > wallet_amount {
return MmError::err(WithdrawError::NotEnoughNftsAmount {
token_address: withdraw_type.token_address,
token_id: withdraw_type.token_id.to_string(),
available: wallet_amount,
required: amount_dec,
});
}
let my_address = eth_coin.derivation_method.single_addr_or_err().await?;
let (eth_value, data, call_addr, fee_coin) = match eth_coin.coin_type {
EthCoinType::Eth => {
let function = ERC1155_CONTRACT.function("safeTransferFrom")?;
let token_id_u256 =
U256::from_dec_str(token_id_str).map_to_mm(|e| NumConversError::new(format!("{:?}", e)))?;
let amount_u256 =
U256::from_dec_str(&amount_dec.to_string()).map_to_mm(|e| NumConversError::new(format!("{:?}", e)))?;
let data = function.encode_input(&[
Token::Address(my_address),
Token::Address(to_addr),
Token::Uint(token_id_u256),
Token::Uint(amount_u256),
Token::Bytes("0x".into()),
])?;
(0.into(), data, token_addr, eth_coin.ticker())
},
EthCoinType::Erc20 { .. } => {
return MmError::err(WithdrawError::InternalError(
"Erc20 coin type doesnt support withdraw nft".to_owned(),
))
},
EthCoinType::Nft { .. } => return MmError::err(WithdrawError::NftProtocolNotSupported),
};
let (gas, pay_for_gas_option) = get_eth_gas_details_from_withdraw_fee(
ð_coin,
withdraw_type.fee,
eth_value,
data.clone().into(),
my_address,
call_addr,
false,
)
.await?;
let address_lock = eth_coin.get_address_lock(my_address.to_string()).await;
let _nonce_lock = address_lock.lock().await;
let (nonce, _) = eth_coin
.clone()
.get_addr_nonce(my_address)
.compat()
.timeout_secs(30.)
.await?
.map_to_mm(WithdrawError::Transport)?;
let tx_type = tx_type_from_pay_for_gas_option!(pay_for_gas_option);
if !eth_coin.is_tx_type_supported(&tx_type) {
return MmError::err(WithdrawError::TxTypeNotSupported);
}
let tx_builder = UnSignedEthTxBuilder::new(tx_type, nonce, gas, Action::Call(call_addr), eth_value, data);
let tx_builder = tx_builder_with_pay_for_gas_option(ð_coin, tx_builder, &pay_for_gas_option)?;
let tx = tx_builder
.build()
.map_to_mm(|e| WithdrawError::InternalError(e.to_string()))?;
let secret = eth_coin.priv_key_policy.activated_key_or_err()?.secret();
let signed = tx.sign(secret, Some(eth_coin.chain_id))?;
let signed_bytes = rlp::encode(&signed);
let fee_details = EthTxFeeDetails::new(gas, pay_for_gas_option, fee_coin)?;
Ok(TransactionNftDetails {
tx_hex: BytesJson::from(signed_bytes.to_vec()),
tx_hash: format!("{:02x}", signed.tx_hash_as_bytes()),
from: vec![eth_coin.my_address()?],
to: vec![withdraw_type.to],
contract_type: ContractType::Erc1155,
token_address: withdraw_type.token_address,
token_id: withdraw_type.token_id,
amount: amount_dec,
fee_details: Some(fee_details.into()),
coin: eth_coin.ticker.clone(),
block_height: 0,
timestamp: now_sec(),
internal_id: 0,
transaction_type: TransactionType::NftTransfer,
})
}
/// `withdraw_erc721` function returns details of `ERC-721` transaction including tx hex,
/// which should be sent to`send_raw_transaction` RPC to broadcast the transaction.
pub async fn withdraw_erc721(ctx: MmArc, withdraw_type: WithdrawErc721) -> WithdrawNftResult {
let coin = lp_coinfind_or_err(&ctx, withdraw_type.chain.to_ticker()).await?;
let (to_addr, token_addr, eth_coin) =
get_valid_nft_addr_to_withdraw(coin, &withdraw_type.to, &withdraw_type.token_address)?;
let token_id_str = &withdraw_type.token_id.to_string();
let token_owner = eth_coin.erc721_owner(token_addr, token_id_str).await?;
let my_address = eth_coin.derivation_method.single_addr_or_err().await?;
if token_owner != my_address {
return MmError::err(WithdrawError::MyAddressNotNftOwner {
my_address: eth_addr_to_hex(&my_address),
token_owner: eth_addr_to_hex(&token_owner),
});
}
let my_address = eth_coin.derivation_method.single_addr_or_err().await?;
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(&withdraw_type.token_id.to_string())
.map_to_mm(|e| NumConversError::new(format!("{:?}", e)))?;
let data = function.encode_input(&[
Token::Address(my_address),
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(),
))
},
// TODO: start to use NFT GLOBAL TOKEN for withdraw
EthCoinType::Nft { .. } => return MmError::err(WithdrawError::NftProtocolNotSupported),
};
let (gas, pay_for_gas_option) = get_eth_gas_details_from_withdraw_fee(
ð_coin,
withdraw_type.fee,
eth_value,
data.clone().into(),
my_address,
call_addr,
false,
)
.await?;
let address_lock = eth_coin.get_address_lock(my_address.to_string()).await;
let _nonce_lock = address_lock.lock().await;
let (nonce, _) = eth_coin
.clone()
.get_addr_nonce(my_address)
.compat()