Skip to content

Commit

Permalink
feat(zcoin): ARRR WASM implementation (#1957)
Browse files Browse the repository at this point in the history
  • Loading branch information
borngraced authored Feb 23, 2024
1 parent af57160 commit 33af1f5
Show file tree
Hide file tree
Showing 61 changed files with 5,657 additions and 1,162 deletions.
435 changes: 260 additions & 175 deletions Cargo.lock

Large diffs are not rendered by default.

22 changes: 17 additions & 5 deletions mm2src/coins/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@ uuid = { version = "1.2.2", features = ["fast-rng", "serde", "v4"] }
# We don't need the default web3 features at all since we added our own web3 transport using shared HYPER instance.
web3 = { git = "https://github.com/KomodoPlatform/rust-web3", tag = "v0.19.0", default-features = false }
zbase32 = "0.1.2"
zcash_client_backend = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.3.0" }
zcash_primitives = { features = ["transparent-inputs"], git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.3.0" }
zcash_proofs = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.3.0" }
zcash_client_backend = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0" }
zcash_extras = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0" }
zcash_primitives = {features = ["transparent-inputs"], git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0" }

[target.'cfg(all(not(target_os = "ios"), not(target_os = "android"), not(target_arch = "wasm32")))'.dependencies]
bincode = { version = "1.3.3", default-features = false, optional = true }
Expand All @@ -121,15 +121,23 @@ spl-token = { version = "3", optional = true }
spl-associated-token-account = { version = "1", optional = true }

[target.'cfg(target_arch = "wasm32")'.dependencies]
blake2b_simd = "0.5"
ff = "0.8"
futures-util = "0.3"
instant = "0.1.12"
jubjub = "0.5.1"
js-sys = { version = "0.3.27" }
mm2_db = { path = "../mm2_db" }
mm2_metamask = { path = "../mm2_metamask" }
mm2_test_helpers = { path = "../mm2_test_helpers" }
time = { version = "0.3.20", features = ["wasm-bindgen"] }
tonic = { version = "0.7", default-features = false, features = ["prost", "codegen", "compression"] }
tower-service = "0.3"
wasm-bindgen = "0.2.86"
wasm-bindgen-futures = { version = "0.4.1" }
wasm-bindgen-test = { version = "0.3.2" }
web-sys = { version = "0.3.55", features = ["console", "Headers", "Request", "RequestInit", "RequestMode", "Response", "Window"] }
zcash_proofs = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0", default-features = false, features = ["local-prover"] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
dirs = { version = "1" }
Expand All @@ -151,14 +159,18 @@ tokio = { version = "1.20" }
tokio-rustls = { version = "0.23" }
tonic = { version = "0.7", features = ["tls", "tls-webpki-roots", "compression"] }
webpki-roots = { version = "0.22" }
zcash_client_sqlite = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.3.0" }
zcash_client_sqlite = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0" }
zcash_proofs = { git = "https://github.com/KomodoPlatform/librustzcash.git", tag = "k-1.4.0", default-features =false, features = ["local-prover", "multicore"] }

[target.'cfg(windows)'.dependencies]
winapi = "0.3"

[dev-dependencies]
mm2_test_helpers = { path = "../mm2_test_helpers" }

[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wagyu-zcash-parameters = { version = "0.2" }

[build-dependencies]
prost-build = { version = "0.10.4", default-features = false }
tonic-build = { version = "0.7", features = ["prost", "compression"] }
tonic-build = { version = "0.7", default-features = false, features = ["prost", "compression"] }
5 changes: 5 additions & 0 deletions mm2src/coins/eth/eth_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::*;
use crate::{DexFee, IguanaPrivKey};
use common::{block_on, now_sec};
use crypto::privkey::key_pair_from_seed;
#[cfg(not(target_arch = "wasm32"))]
use ethkey::{Generator, Random};
use mm2_core::mm_ctx::{MmArc, MmCtxBuilder};
use mm2_test_helpers::{for_tests::{eth_jst_testnet_conf, eth_testnet_conf, ETH_DEV_NODE, ETH_DEV_NODES,
Expand Down Expand Up @@ -88,6 +89,7 @@ fn eth_coin_for_test(
eth_coin_from_keypair(coin_type, urls, fallback_swap_contract, key_pair)
}

#[cfg(not(target_arch = "wasm32"))]
fn random_eth_coin_for_test(
coin_type: EthCoinType,
urls: &[&str],
Expand Down Expand Up @@ -157,6 +159,7 @@ fn eth_coin_from_keypair(
(ctx, eth_coin)
}

#[cfg(not(target_arch = "wasm32"))]
pub fn fill_eth(to_addr: Address, amount: f64) {
let wei_per_eth: u64 = 1_000_000_000_000_000_000;
let amount_in_wei = (amount * wei_per_eth as f64) as u64;
Expand Down Expand Up @@ -464,6 +467,7 @@ fn test_gas_station() {
assert_eq!(expected_eth_polygon, res_polygon);
}

#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_withdraw_impl_manual_fee() {
let (_ctx, coin) = eth_coin_for_test(EthCoinType::Eth, &["http://dummy.dummy"], None);
Expand Down Expand Up @@ -501,6 +505,7 @@ fn test_withdraw_impl_manual_fee() {
assert_eq!(expected, tx_details.fee_details);
}

#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_withdraw_impl_fee_details() {
let (_ctx, coin) = eth_coin_for_test(
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/eth/web3_transport/http_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ async fn send_request_once(
event_handlers: &Vec<RpcTransportEventHandlerShared>,
) -> Result<Json, Error> {
use http::header::ACCEPT;
use mm2_net::wasm_http::FetchRequest;
use mm2_net::wasm::http::FetchRequest;

// account for outgoing traffic
event_handlers.on_outgoing_request(request_payload.as_bytes());
Expand Down
4 changes: 2 additions & 2 deletions mm2src/coins/hd_wallet_storage/wasm_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ pub struct HDAccountTable {
}

impl TableSignature for HDAccountTable {
fn table_name() -> &'static str { "hd_account" }
const TABLE_NAME: &'static str = "hd_account";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(WALLET_ID_INDEX, &["coin", "hd_wallet_rmd160"], false)?;
table.create_multi_index(
WALLET_ACCOUNT_ID_INDEX,
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/lp_price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ async fn process_price_request(price_url: &str) -> Result<TickerInfosRegistry, M
#[cfg(target_arch = "wasm32")]
async fn process_price_request(price_url: &str) -> Result<TickerInfosRegistry, MmError<PriceServiceRequestError>> {
debug!("Fetching price from: {}", price_url);
let (status, headers, body) = mm2_net::wasm_http::slurp_url(price_url).await?;
let (status, headers, body) = mm2_net::wasm::http::slurp_url(price_url).await?;
let (status_code, body, _) = (status, std::str::from_utf8(&body)?.trim().into(), headers);
if status_code != StatusCode::OK {
return MmError::err(PriceServiceRequestError::HttpProcessError(body));
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/nft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use web3::types::TransactionId;
use mm2_net::native_http::send_request_to_uri;

#[cfg(target_arch = "wasm32")]
use mm2_net::wasm_http::send_request_to_uri;
use mm2_net::wasm::http::send_request_to_uri;

const MORALIS_API_ENDPOINT: &str = "api/v2";
/// query parameters for moralis request: The format of the token ID
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/nft/nft_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use mm2_net::native_http::send_request_to_uri;
common::cfg_wasm32! {
use wasm_bindgen_test::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
use mm2_net::wasm_http::send_request_to_uri;
use mm2_net::wasm::http::send_request_to_uri;
}

cross_test!(test_moralis_ipfs_bafy, {
Expand Down
12 changes: 6 additions & 6 deletions mm2src/coins/nft/storage/wasm/wasm_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -895,11 +895,11 @@ impl NftListTable {
}

impl TableSignature for NftListTable {
fn table_name() -> &'static str { "nft_list_cache_table" }
const TABLE_NAME: &'static str = "nft_list_cache_table";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if is_initial_upgrade(old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(
CHAIN_TOKEN_ADD_TOKEN_ID_INDEX,
&["chain", "token_address", "token_id"],
Expand Down Expand Up @@ -976,11 +976,11 @@ impl NftTransferHistoryTable {
}

impl TableSignature for NftTransferHistoryTable {
fn table_name() -> &'static str { "nft_transfer_history_cache_table" }
const TABLE_NAME: &'static str = "nft_transfer_history_cache_table";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if is_initial_upgrade(old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(
CHAIN_TOKEN_ADD_TOKEN_ID_INDEX,
&["chain", "token_address", "token_id"],
Expand Down Expand Up @@ -1009,11 +1009,11 @@ pub(crate) struct LastScannedBlockTable {
}

impl TableSignature for LastScannedBlockTable {
fn table_name() -> &'static str { "last_scanned_block_table" }
const TABLE_NAME: &'static str = "last_scanned_block_table";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if is_initial_upgrade(old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_index("chain", true)?;
}
Ok(())
Expand Down
12 changes: 9 additions & 3 deletions mm2src/coins/qrc20/qrc20_tests.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
use super::*;
use crate::utxo::rpc_clients::UnspentInfo;
use crate::{DexFee, TxFeeDetails, WaitForHTLCTxSpendArgs};
use chain::OutPoint;
use common::{block_on, wait_until_sec, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::Secp256k1Secret;
use itertools::Itertools;
use keys::{Address, AddressBuilder};
use mm2_core::mm_ctx::MmCtxBuilder;
use mm2_number::bigdecimal::Zero;
use mocktopus::mocking::{MockResult, Mockable};
use rpc::v1::types::ToTxHash;
use std::convert::TryFrom;
use std::mem::discriminant;

cfg_native!(
use crate::utxo::rpc_clients::UnspentInfo;

use mocktopus::mocking::{MockResult, Mockable};
use chain::OutPoint;
);

const EXPECTED_TX_FEE: i64 = 1000;
const CONTRACT_CALL_GAS_FEE: i64 = (QRC20_GAS_LIMIT_DEFAULT * QRC20_GAS_PRICE_DEFAULT) as i64;
const SWAP_PAYMENT_GAS_FEE: i64 = (QRC20_PAYMENT_GAS_LIMIT * QRC20_GAS_PRICE_DEFAULT) as i64;
Expand Down Expand Up @@ -58,6 +62,7 @@ fn check_tx_fee(coin: &Qrc20Coin, expected_tx_fee: ActualTxFee) {
assert_eq!(actual_tx_fee, expected_tx_fee);
}

#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_withdraw_to_p2sh_address_should_fail() {
let priv_key = [
Expand Down Expand Up @@ -91,6 +96,7 @@ fn test_withdraw_to_p2sh_address_should_fail() {
assert_eq!(err, expect);
}

#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_withdraw_impl_fee_details() {
Qrc20Coin::get_unspent_ordered_list.mock_safe(|coin, _| {
Expand Down
1 change: 0 additions & 1 deletion mm2src/coins/rpc_command/init_withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,6 @@ impl RpcTask for WithdrawTask {
match self.coin {
MmCoinEnum::UtxoCoin(ref standard_utxo) => standard_utxo.init_withdraw(ctx, request, task_handle).await,
MmCoinEnum::QtumCoin(ref qtum) => qtum.init_withdraw(ctx, request, task_handle).await,
#[cfg(not(target_arch = "wasm32"))]
MmCoinEnum::ZCoin(ref z) => z.init_withdraw(ctx, request, task_handle).await,
_ => MmError::err(WithdrawError::CoinDoesntSupportInitWithdraw {
coin: self.coin.ticker().to_owned(),
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/tendermint/rpc/tendermint_wasm_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use http::header::{ACCEPT, CONTENT_TYPE};
use http::uri::InvalidUri;
use http::{StatusCode, Uri};
use mm2_net::transport::SlurpError;
use mm2_net::wasm_http::FetchRequest;
use mm2_net::wasm::http::FetchRequest;
use std::str::FromStr;
use tendermint_rpc::endpoint::{abci_info, broadcast};
pub use tendermint_rpc::endpoint::{abci_query::{AbciQuery, Request as AbciRequest},
Expand Down
4 changes: 2 additions & 2 deletions mm2src/coins/test_coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,14 @@ impl SwapOps for TestCoin {

async fn search_for_swap_tx_spend_my(
&self,
_: SearchForSwapTxSpendInput<'_>,
_input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
unimplemented!()
}

async fn search_for_swap_tx_spend_other(
&self,
_: SearchForSwapTxSpendInput<'_>,
_input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
unimplemented!()
}
Expand Down
4 changes: 2 additions & 2 deletions mm2src/coins/tx_history_storage/wasm/tx_history_storage_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,11 @@ pub(crate) struct TxHistoryTableV1 {
}

impl TableSignature for TxHistoryTableV1 {
fn table_name() -> &'static str { "tx_history" }
const TABLE_NAME: &'static str = "tx_history";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_index("history_id", true)?;
}

Expand Down
8 changes: 4 additions & 4 deletions mm2src/coins/tx_history_storage/wasm/tx_history_storage_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,11 +414,11 @@ impl TxHistoryTableV2 {
}

impl TableSignature for TxHistoryTableV2 {
fn table_name() -> &'static str { "tx_history_v2" }
const TABLE_NAME: &'static str = "tx_history_v2";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(TxHistoryTableV2::WALLET_ID_INDEX, &["coin", "hd_wallet_rmd160"], false)?;
table.create_multi_index(
TxHistoryTableV2::WALLET_ID_INTERNAL_ID_INDEX,
Expand Down Expand Up @@ -468,11 +468,11 @@ impl TxCacheTableV2 {
}

impl TableSignature for TxCacheTableV2 {
fn table_name() -> &'static str { "tx_cache_v2" }
const TABLE_NAME: &'static str = "tx_cache_v2";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(TxCacheTableV2::COIN_TX_HASH_INDEX, &["coin", "tx_hash"], true)?;
}
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/utxo/rpc_clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2873,7 +2873,7 @@ async fn connect_loop<Spawner: SpawnFuture>(
static ref CONN_IDX: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
}

use mm2_net::wasm_ws::ws_transport;
use mm2_net::wasm::wasm_ws::ws_transport;

let delay = Arc::new(AtomicU64::new(0));
loop {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ impl BlockHeaderStorageTable {
}

impl TableSignature for BlockHeaderStorageTable {
fn table_name() -> &'static str { "block_header_storage_cache_table" }
const TABLE_NAME: &'static str = "block_header_storage_cache_table";

fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()> {
if let (0, 1) = (old_version, new_version) {
let table = upgrader.create_table(Self::table_name())?;
let table = upgrader.create_table(Self::TABLE_NAME)?;
table.create_multi_index(Self::TICKER_HEIGHT_INDEX, &["ticker", "height"], true)?;
table.create_multi_index(Self::HASH_TICKER_INDEX, &["hash", "ticker"], true)?;
table.create_index("ticker", false)?;
Expand Down
6 changes: 3 additions & 3 deletions mm2src/coins/utxo/utxo_builder/utxo_coin_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -770,16 +770,16 @@ pub trait UtxoCoinBuilderCommonOps {
.ok_or_else(|| format!("avg_blocktime not specified in {} coin config", self.ticker()))
.map_to_mm(UtxoCoinBuildError::ErrorCalculatingStartingHeight)?;
let blocks_per_day = DAY_IN_SECONDS / avg_blocktime;
let current_time_s = now_sec();
let current_time_sec = now_sec();

if current_time_s < date_s {
if current_time_sec < date_s {
return MmError::err(UtxoCoinBuildError::ErrorCalculatingStartingHeight(format!(
"{} sync date must be earlier then current date",
self.ticker()
)));
};

let secs_since_date = current_time_s - date_s;
let secs_since_date = current_time_sec - date_s;
let days_since_date = (secs_since_date / DAY_IN_SECONDS) - 1;
let blocks_to_sync = (days_since_date * blocks_per_day) + blocks_per_day;

Expand Down
Loading

0 comments on commit 33af1f5

Please sign in to comment.