Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nft-swap): complete refund methods #2129

Merged
merged 121 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 102 commits
Commits
Show all changes
121 commits
Select commit Hold shift + click to select a range
394fe4d
use NFT_MAKER_SWAP_V2 in nft_swap_v2 mod and in spend erc721 test
laruh Apr 18, 2024
44f542d
deploy contracts before tokens, add constructor to EtomicSwapMakerNft…
laruh Apr 18, 2024
ff1006a
use Sepolia in dockerized nft tests
laruh Apr 22, 2024
aebf756
global variables and send nft back to maker
laruh Apr 23, 2024
1966fcf
add web3 HTTPS support in mm2_main tests
laruh Apr 23, 2024
1922bff
wait for send_back_tx confirmation
laruh Apr 23, 2024
c07e8e2
call contract addresses with functions
laruh Apr 23, 2024
ebac6e6
impl check_token_uri and make chains field in ClearNftDbReq optional …
laruh Apr 4, 2024
f9f4eab
doc comms
laruh Apr 24, 2024
ad0ce31
Merge remote-tracking branch 'origin/dev' into standalone-nft-maker-s…
laruh Apr 25, 2024
4a4dfc0
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh Apr 26, 2024
c703913
fix merge conflicts
laruh Apr 26, 2024
fe498fa
impl wait_pending_transactions
laruh Apr 26, 2024
18fa53e
increase max nonce by 1
laruh Apr 26, 2024
b9a6719
Revert "increase max nonce by 1"
laruh Apr 26, 2024
9a23f20
Merge remote-tracking branch 'origin/dev' into standalone-nft-maker-s…
laruh Apr 29, 2024
998708b
impl get_or_create_nft function
laruh Apr 29, 2024
364d795
additional logs, ignore erc1155
laruh Apr 29, 2024
cb187c7
deploy new SEPOLIA_ERC721_CONTRACT
laruh Apr 29, 2024
9d4e3ee
fix linter
laruh Apr 29, 2024
495e7a9
run both nft send payment tests
laruh Apr 29, 2024
e917b0b
proxy: send nft reqs with payload data in body to satisfy proxy HttpG…
laruh May 6, 2024
f868a50
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh May 8, 2024
e94fac7
provide UrlSignWrapper structure
laruh May 9, 2024
2e8c662
additionally include chain field into UrlSignWrapper
laruh May 9, 2024
0fbf75d
increase erc721 tx confirmation time to 150, add more logs
laruh May 9, 2024
03860e1
review: use map_err for generate_gui_auth_signed_validation, doc comm…
laruh May 10, 2024
b8b05d1
proxy: send regular http post request to proxy for nft feature
laruh May 12, 2024
3de2b92
make erc721 and erc1155 time locks different in tests
laruh May 12, 2024
f2625fd
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh May 13, 2024
930a593
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh May 14, 2024
350abd6
review: impl lock_coins() to keep coins field in CoinsContext private
laruh May 14, 2024
36eaf38
review: rename Gui-Auth types to align with new names in the KomodoDe…
laruh May 15, 2024
4478ccb
review: use "http-rustls-tls" feature in web3 crate for tests
laruh May 15, 2024
7882e6e
review: send Http GET request to activate NFT
laruh May 16, 2024
d03b6d1
review: support GET requests to KomodoDeFi Proxy layer and to 3rd API…
laruh May 17, 2024
ff92a20
impl build_and_send_request func to avoid code repetition
laruh May 17, 2024
a2c47f8
review: panic in wait_for_geth_node_ready if Deth node is not ready a…
laruh May 17, 2024
d6cbfd8
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh May 21, 2024
9c3ff07
merge: fmt, log tx_hash() in NFT payments instead of bytes, import et…
laruh May 21, 2024
0bedba3
send only signed message as header in nft
laruh May 23, 2024
7976761
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh May 24, 2024
a6ad6fc
wip: refund_nft_maker_payment_v2
laruh May 26, 2024
5daf723
wip: refund_nft_maker_payment_v2_secret
laruh May 27, 2024
2daec7a
test send_send_and_refund_erc721_maker_payment_timelock ignoring ERC1155
laruh May 27, 2024
6992931
log info in send_send_and_refund_erc721_maker_payment_timelock
laruh May 27, 2024
3f07f1f
log token_id=2 send_send_and_refund_erc721_maker_payment_timelock
laruh May 27, 2024
0079362
test only refund_nft_maker_payment_v2_timelock
laruh May 28, 2024
0c164fb
test only refund_nft_maker_payment_v2_timelock
laruh May 28, 2024
63af2bc
use global_nft_with_random_privkey in send_send_and_refund_erc721_mak…
laruh May 28, 2024
e2f8ccf
call maker_global_nft.refund_nft_maker_payment_v2_timelock
laruh May 28, 2024
dad6988
use get_erc712_owner func in refund erc721 test
laruh May 28, 2024
9b1a700
add geth_ prefix to Address functions in eth tests
laruh May 28, 2024
fc4d6e4
impl [test] send_send_and_refund_erc1155_maker_payment_timelock
laruh May 28, 2024
cc8e78e
test the refund payment with taker secret
laruh May 29, 2024
87b297a
use Geth node for swap tests
laruh May 29, 2024
780b1e8
reduce code duplication
laruh May 30, 2024
f789e91
provide NftSwapInfo type
laruh May 30, 2024
aa1d70f
use coins config file for NFT activation
laruh May 31, 2024
b9f2a98
reduce code duplication using `validate_state` func
laruh Jun 2, 2024
ece5152
refactor Quicknode HTTP request: move `signed_message` to header
laruh Jun 4, 2024
920861e
tests: increase wait for confirm time and add sleep duration
laruh Jun 5, 2024
e478711
eth tpu v2: deploy maker and taker swap v2 contracts in tests. add ma…
laruh Jun 7, 2024
9803fd5
eth tpu v2: dont include "nft_maker_swap_v2_contract" in eth/erc20 ac…
laruh Jun 8, 2024
2828be0
eth tpu v2: provide init_watchers_swap_contract in swap_watcher_tests.rs
laruh Jun 8, 2024
04d99e4
eth tpu v2: impl TakerCoinSwapOpsV2 for EthCoin, send_taker_funding WIP
laruh Jun 10, 2024
d31566d
eth_docker_tests.rs change sleep Duration in some tests
laruh Jun 10, 2024
4064999
eth tpu v2: impl TakerCoinSwapOpsV2 for EthCoin WIP
laruh Jun 14, 2024
b986279
Merge remote-tracking branch 'refs/remotes/origin/dev' into nft-refun…
laruh Jun 17, 2024
e636da1
avoid code duplication in input_tokens vector
laruh Jun 17, 2024
40ffb65
review: rename validate_state fnc, use extend plus chain in etomic_sw…
laruh Jun 17, 2024
888108c
review: move contract bytes strings to txt files, remove "the"
laruh Jun 18, 2024
8143cc2
review: move code to EthCoinType::Nft arm
laruh Jun 20, 2024
b391a16
state machine: fix log info text related to sign_and_send_taker_fundi…
laruh Jun 22, 2024
5f34f1c
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh Jun 22, 2024
e672485
review: provide log!, instead println! in tests
laruh Jun 22, 2024
986c5e7
Merge remote-tracking branch 'refs/remotes/origin/standalone-nft-make…
laruh Jun 22, 2024
d998062
review: swap part of ERC1155 nfts in eth_docker_tests.rs
laruh Jun 23, 2024
ff4d306
eth tpu v2: leave comms about preimages
laruh Jun 26, 2024
2ae0b04
eth tpu v2: use Public from ethereum_types in impl ParseCoinAssocType…
laruh Jun 28, 2024
0d54567
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh Jun 28, 2024
602206d
Merge remote-tracking branch 'refs/remotes/origin/standalone-nft-make…
laruh Jun 28, 2024
604d182
change sleep duration in send_and_spend_erc721_maker_payment
laruh Jun 28, 2024
36d94b9
change sleep duration in send_and_refund_erc721_maker_payment_timeloc…
laruh Jun 28, 2024
ce6673b
change sleep duration in send_and_refund_erc721_maker_payment_timelock
laruh Jun 28, 2024
933d4b9
change sleep duration in send_and_refund_erc1155_maker_payment_timelock
laruh Jun 28, 2024
1e90600
eth tpu v2: add swap_v2_contracts Opt param in EthActivationV2Request…
laruh Jul 1, 2024
b9049bf
state machine: change doc comment related to sign_and_send_taker_fund…
laruh Jul 3, 2024
8e4cd71
eth tpu v2: send_taker_funding Erc20 WIP (need to optimize code)
laruh Jul 3, 2024
4e9f902
change sleep duration in send_and_refund_erc721_maker_payment_timelock
laruh Jul 3, 2024
801a688
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh Jul 8, 2024
1e050d2
fmt code after merge
laruh Jul 8, 2024
2447763
Merge remote-tracking branch 'refs/remotes/origin/standalone-nft-make…
laruh Jul 8, 2024
fa3f553
fix merge conflicts
laruh Jul 8, 2024
eddeb1a
make "proxy_auth" Optional
laruh Jul 10, 2024
7cbb941
Merge remote-tracking branch 'refs/remotes/origin/dev' into standalon…
laruh Jul 10, 2024
87cc404
Merge remote-tracking branch 'refs/remotes/origin/standalone-nft-make…
laruh Jul 10, 2024
191b5f0
Merge remote-tracking branch 'origin/dev' into standalone-nft-maker-s…
laruh Jul 18, 2024
734edbc
Merge remote-tracking branch 'origin/standalone-nft-maker-swap-contra…
laruh Jul 18, 2024
7b69886
fmt and clippy
laruh Jul 18, 2024
b13ab34
Merge remote-tracking branch 'origin/dev' into nft-refund-payment-geth
laruh Jul 19, 2024
dab5bd9
fmt, clippy
laruh Jul 19, 2024
cac2d0d
review: remove gas_limit module from eth_swap_v2.rs
laruh Jul 21, 2024
071a1f6
review: use `etomic_swap_id` function
laruh Jul 21, 2024
439243a
review: use fixed size arrays
laruh Jul 22, 2024
c629d7a
review: provide eth total payment to sign_and_send_transaction
laruh Jul 25, 2024
ed08df9
review: fix typo
laruh Jul 25, 2024
89e543f
review: update log to "Sent taker funding spend (taker payment)"
laruh Jul 25, 2024
28bc18a
review: remove legacy "derive_htlc_pubkey" function from swap_v2, use…
laruh Jul 25, 2024
69a07a8
Merge remote-tracking branch 'origin/dev' into nft-refund-payment-geth
laruh Jul 26, 2024
7570df7
gas limit: TODO about new consts and params for v2 calls
laruh Jul 26, 2024
3042e60
todo burnFee support
laruh Jul 26, 2024
e1e2242
review: update doc comments for taker and maker secret hashes in Send…
laruh Jul 26, 2024
fcd394d
review: specify timelock doc comments for UTXO and smart contracts in…
laruh Jul 26, 2024
6a231a3
review: remove wait_for_confirmation_until and use funding_time_lock …
laruh Jul 26, 2024
c58808a
review: use Public::from_slice directly in parse_pubkey
laruh Jul 29, 2024
1a5bf73
review: use public_to_address to get address from pubkey
laruh Jul 29, 2024
5d6f943
review: use dex_fee plus payment_amount for eth_total_payment
laruh Jul 29, 2024
2007a70
review: extract sign_and_send_transaction outside the if/else
laruh Jul 29, 2024
9aca0d7
review: minify json
laruh Jul 29, 2024
fe730fa
review: drop variables, return result value directly
laruh Aug 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 182 additions & 19 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ use crate::rpc_command::{account_balance, get_new_address, init_account_balance,
init_scan_for_new_addresses};
use crate::{coin_balance, scan_for_new_addresses_impl, BalanceResult, CoinWithDerivationMethod, DerivationMethod,
DexFee, Eip1559Ops, MakerNftSwapOpsV2, ParseCoinAssocTypes, ParseNftAssocTypes, PayForGasParams,
PrivKeyPolicy, RefundMakerPaymentArgs, RpcCommonOps, SendNftMakerPaymentArgs, SpendNftMakerPaymentArgs,
ToBytes, ValidateNftMakerPaymentArgs, ValidateWatcherSpendInput, WatcherSpendType};
PrivKeyPolicy, 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};
Expand All @@ -76,7 +76,6 @@ use futures::future::{join, join_all, select_ok, try_join_all, Either, FutureExt
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::{KomodefiProxyAuthValidation, ProxyAuthValidationGenerator};
Expand Down Expand Up @@ -159,6 +158,7 @@ mod eip1559_gas_fee;
pub(crate) use eip1559_gas_fee::FeePerGasEstimated;
use eip1559_gas_fee::{BlocknativeGasApiCaller, FeePerGasSimpleEstimator, GasApiConfig, GasApiProvider,
InfuraGasApiCaller};
mod eth_swap_v2;

/// https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol
/// Dev chain (195.201.137.5:8565) contract address: 0x83965C539899cC0F918552e5A26915de40ee8852
Expand All @@ -173,6 +173,8 @@ const ERC721_ABI: &str = include_str!("eth/erc721_abi.json");
const ERC1155_ABI: &str = include_str!("eth/erc1155_abi.json");
const NFT_SWAP_CONTRACT_ABI: &str = include_str!("eth/nft_swap_contract_abi.json");
const NFT_MAKER_SWAP_V2_ABI: &str = include_str!("eth/nft_maker_swap_v2_abi.json");
const MAKER_SWAP_V2_ABI: &str = include_str!("eth/maker_swap_v2_abi.json");
const TAKER_SWAP_V2_ABI: &str = include_str!("eth/taker_swap_v2_abi.json");

/// Payment states from etomic swap smart contract: https://github.com/artemii235/etomic-swap/blob/master/contracts/EtomicSwap.sol#L5
pub enum PaymentState {
Expand Down Expand Up @@ -298,6 +300,8 @@ 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 MAKER_SWAP_V2: Contract = Contract::load(MAKER_SWAP_V2_ABI.as_bytes()).unwrap();
pub static ref TAKER_SWAP_V2: Contract = Contract::load(TAKER_SWAP_V2_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();
Expand Down Expand Up @@ -384,11 +388,11 @@ type GasDetails = (U256, PayForGasOption);
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),
#[from_stringify("serde_json::Error")]
#[display(fmt = "Internal: {}", _0)]
Internal(String),
#[display(fmt = "Invalid gas api provider config: {}", _0)]
Expand Down Expand Up @@ -649,6 +653,7 @@ pub struct EthCoinImpl {
derivation_method: Arc<EthDerivationMethod>,
sign_message_prefix: Option<String>,
swap_contract_address: Address,
swap_v2_contracts: Option<SwapV2Contracts>,
fallback_swap_contract: Option<Address>,
contract_supports_watchers: bool,
web3_instances: AsyncMutex<Vec<Web3Instance>>,
Expand Down Expand Up @@ -701,6 +706,13 @@ pub struct Erc20TokenInfo {
pub decimals: u8,
}

#[derive(Copy, Clone, Deserialize)]
pub struct SwapV2Contracts {
pub maker_swap_v2_contract: Address,
pub taker_swap_v2_contract: Address,
pub nft_maker_swap_v2_contract: Address,
}

#[derive(Deserialize, Serialize)]
#[serde(tag = "format")]
pub enum EthAddressFormat {
Expand Down Expand Up @@ -826,6 +838,28 @@ impl EthCoinImpl {
sha256(&input).to_vec()
}

/// The id used to differentiate payments on Etomic swap smart contract.
/// For Taker Etomic Swap contract taker_secret_hash should be provided.
pub(crate) fn etomic_swap_v2_id(
&self,
funding_time_lock: u32,
payment_time_lock: u32,
secret_hash: &[u8],
) -> Vec<u8> {
let funding_timelock_bytes = funding_time_lock.to_le_bytes();
let payment_timelock_bytes = payment_time_lock.to_le_bytes();

let mut input =
Vec::with_capacity(funding_timelock_bytes.len() + payment_timelock_bytes.len() + secret_hash.len());
input.extend(
funding_timelock_bytes
.iter()
.chain(payment_timelock_bytes.iter())
.chain(secret_hash.iter()),
);
sha256(&input).to_vec()
}
shamardy marked this conversation as resolved.
Show resolved Hide resolved

/// 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)))
Expand Down Expand Up @@ -6400,6 +6434,7 @@ pub async fn eth_coin_from_conf_and_request(
coin_type,
sign_message_prefix,
swap_contract_address,
swap_v2_contracts: None,
fallback_swap_contract,
contract_supports_watchers,
decimals,
Expand Down Expand Up @@ -6780,20 +6815,14 @@ impl ToBytes for SignedEthTx {
}
}

#[derive(Debug, Display)]
#[derive(Debug, Display, EnumFromStringify)]
pub enum EthAssocTypesError {
InvalidHexString(String),
#[from_stringify("DecoderError")]
TxParseError(String),
ParseSignatureError(String),
KeysError(keys::Error),
}

impl From<DecoderError> for EthAssocTypesError {
fn from(e: DecoderError) -> Self { EthAssocTypesError::TxParseError(e.to_string()) }
}

impl From<keys::Error> for EthAssocTypesError {
fn from(e: keys::Error) -> Self { EthAssocTypesError::KeysError(e) }
#[from_stringify("secp256k1::Error")]
ParsePublicKeyError(String),
}

#[derive(Debug, Display)]
Expand All @@ -6811,7 +6840,7 @@ impl From<ParseContractTypeError> for EthNftAssocTypesError {
impl ParseCoinAssocTypes for EthCoin {
type Address = Address;
type AddressParseError = MmError<EthAssocTypesError>;
type Pubkey = HtlcPubKey;
type Pubkey = Public;
type PubkeyParseError = MmError<EthAssocTypesError>;
type Tx = SignedEthTx;
type TxParseError = MmError<EthAssocTypesError>;
Expand All @@ -6837,7 +6866,8 @@ impl ParseCoinAssocTypes for EthCoin {
}

fn parse_pubkey(&self, pubkey: &[u8]) -> Result<Self::Pubkey, Self::PubkeyParseError> {
HtlcPubKey::from_slice(pubkey).map_to_mm(EthAssocTypesError::from)
let pubkey = PublicKey::from_slice(pubkey)?;
Ok(Public::from_slice(&pubkey.serialize_uncompressed()[1..65]))
shamardy marked this conversation as resolved.
Show resolved Hide resolved
shamardy marked this conversation as resolved.
Show resolved Hide resolved
}

fn parse_tx(&self, tx: &[u8]) -> Result<Self::Tx, Self::TxParseError> {
Expand Down Expand Up @@ -6872,6 +6902,10 @@ impl ToBytes for ContractType {
fn to_bytes(&self) -> Vec<u8> { self.to_string().into_bytes() }
}

impl ToBytes for Public {
fn to_bytes(&self) -> Vec<u8> { self.0.to_vec() }
}

impl ParseNftAssocTypes for EthCoin {
type ContractAddress = Address;
type TokenId = BigUint;
Expand Down Expand Up @@ -6922,16 +6956,16 @@ impl MakerNftSwapOpsV2 for EthCoin {

async fn refund_nft_maker_payment_v2_timelock(
&self,
args: RefundPaymentArgs<'_>,
args: RefundNftMakerPaymentArgs<'_, Self>,
) -> Result<Self::Tx, TransactionErr> {
self.refund_nft_maker_payment_v2_timelock_impl(args).await
}

async fn refund_nft_maker_payment_v2_secret(
&self,
_args: RefundMakerPaymentArgs<'_, Self>,
args: RefundNftMakerPaymentArgs<'_, Self>,
) -> Result<Self::Tx, TransactionErr> {
todo!()
self.refund_nft_maker_payment_v2_secret_impl(args).await
}
}

Expand Down Expand Up @@ -7061,3 +7095,132 @@ impl Eip1559Ops for EthCoin {
*self.swap_txfee_policy.lock().unwrap() = swap_txfee_policy
}
}

#[async_trait]
impl TakerCoinSwapOpsV2 for EthCoin {
async fn send_taker_funding(&self, args: SendTakerFundingArgs<'_>) -> Result<Self::Tx, TransactionErr> {
self.send_taker_funding_impl(args).await
}

async fn validate_taker_funding(&self, _args: ValidateTakerFundingArgs<'_, Self>) -> ValidateSwapV2TxResult {
todo!()
}

async fn refund_taker_funding_timelock(&self, _args: RefundPaymentArgs<'_>) -> Result<Self::Tx, TransactionErr> {
todo!()
}

async fn refund_taker_funding_secret(
&self,
_args: RefundFundingSecretArgs<'_, Self>,
) -> Result<Self::Tx, TransactionErr> {
todo!()
}

async fn search_for_taker_funding_spend(
&self,
_tx: &Self::Tx,
_from_block: u64,
_secret_hash: &[u8],
) -> Result<Option<FundingTxSpend<Self>>, SearchForFundingSpendErr> {
todo!()
}

/// Eth doesnt have preimages
async fn gen_taker_funding_spend_preimage(
&self,
args: &GenTakerFundingSpendArgs<'_, Self>,
_swap_unique_data: &[u8],
) -> GenPreimageResult<Self> {
let result = TxPreimageWithSig {
preimage: args.funding_tx.clone(),
signature: args.funding_tx.signature(),
};
Ok(result)
borngraced marked this conversation as resolved.
Show resolved Hide resolved
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine to do that at this stage as we discussed before. We might even leave it like that in the future (only drawback is some unneeded p2p messages are exchanged), but I might implement the state machine conditional logic for smart contract based chain/coins myself in the future as I have some ideas on how to do that in a good way, it will be either:

1 - Just adding if conditions to bypass some code execution and p2p messages sending/handling from both sides of the swap.
2 - More generic implementation, but this can get messy as well.
3- Extending storable state machine to be a conditional state machine with state transitions depending on specific conditions, but it can make it much more complex to understand.

Just thinking out loud here :)

Copy link
Member Author

@laruh laruh Jul 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just adding if conditions to bypass some code execution and p2p messages sending/handling from both sides of the swap.

I was thinking to add has_preimage:bool flag in coin to skip unneeded p2p messages, I just didnt want to leave unimplemented in functions. We can keep some simple logic here.

We might even leave it like that in the future

Yep, we can not to add if checks at the beginning and firstly test Utxo-Eth swaps as they are.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, we can not to add if checks at the beginning and firstly test Utxo-Eth swaps as they are.

Agreed.


/// Eth doesnt have preimages
async fn validate_taker_funding_spend_preimage(
&self,
_gen_args: &GenTakerFundingSpendArgs<'_, Self>,
_preimage: &TxPreimageWithSig<Self>,
) -> ValidateTakerFundingSpendPreimageResult {
Ok(())
}

/// Eth doesnt use multisig
async fn sign_and_send_taker_funding_spend(
&self,
_preimage: &TxPreimageWithSig<Self>,
_args: &GenTakerFundingSpendArgs<'_, Self>,
_swap_unique_data: &[u8],
) -> Result<Self::Tx, TransactionErr> {
todo!()
}

async fn refund_combined_taker_payment(&self, _args: RefundPaymentArgs<'_>) -> Result<Self::Tx, TransactionErr> {
todo!()
}

/// Eth doesnt have preimages
async fn gen_taker_payment_spend_preimage(
&self,
args: &GenTakerPaymentSpendArgs<'_, Self>,
_swap_unique_data: &[u8],
) -> GenPreimageResult<Self> {
let result = TxPreimageWithSig {
preimage: args.taker_tx.clone(),
signature: args.taker_tx.signature(),
};
Ok(result)
borngraced marked this conversation as resolved.
Show resolved Hide resolved
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment as the above here.


/// Eth doesnt have preimages
async fn validate_taker_payment_spend_preimage(
&self,
_gen_args: &GenTakerPaymentSpendArgs<'_, Self>,
_preimage: &TxPreimageWithSig<Self>,
) -> ValidateTakerPaymentSpendPreimageResult {
Ok(())
}

async fn sign_and_broadcast_taker_payment_spend(
&self,
_preimage: &TxPreimageWithSig<Self>,
_gen_args: &GenTakerPaymentSpendArgs<'_, Self>,
_secret: &[u8],
_swap_unique_data: &[u8],
) -> Result<Self::Tx, TransactionErr> {
todo!()
}

async fn wait_for_taker_payment_spend(
&self,
_taker_payment: &Self::Tx,
_from_block: u64,
_wait_until: u64,
) -> MmResult<Self::Tx, WaitForTakerPaymentSpendError> {
todo!()
}

#[inline(always)]
fn derive_htlc_pubkey_v2(&self, _swap_unique_data: &[u8]) -> Self::Pubkey {
match self.priv_key_policy {
EthPrivKeyPolicy::Iguana(ref key_pair)
| EthPrivKeyPolicy::HDWallet {
activated_key: ref key_pair,
..
} => *key_pair.public(),
EthPrivKeyPolicy::Trezor => todo!(),
#[cfg(target_arch = "wasm32")]
EthPrivKeyPolicy::Metamask(ref metamask_policy) => {
// The metamask public key should be uncompressed
// Remove the first byte (0x04) from the uncompressed public key
let pubkey_bytes: [u8; 64] = metamask_policy.public_key_uncompressed[1..65]
.try_into()
.expect("slice with incorrect length");
Public::from_slice(&pubkey_bytes)
},
}
}
Comment on lines +7183 to +7201
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to this #2093 (comment) , we can look into it in next PRs. We should try to use same format across HD wallet and external ones so that a swap can be continued from either if started from the other one (if both have the same mnemonic / seed and address_id)
c.c. @borngraced If we will not extract a pubkey from walletconnect / external wallet for EVM and we use Address hash after the 0x, then we should do the same here and address can still be derived from this hash by adding 0x to access contract functions.

}
Loading
Loading