From 9f6036de524da136581ac18428f4be55266cb04b Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 14:20:40 -0800 Subject: [PATCH 1/8] run rustfmt --- Cargo.lock | 68 ++++++++++++----------- rustfmt.toml | 3 + src/addresses.rs | 10 +--- src/chains.rs | 33 ++++++----- src/constants.rs | 10 +++- src/entities/base_currency.rs | 6 +- src/entities/currency.rs | 6 +- src/entities/ether.rs | 6 +- src/entities/fractions/currency_amount.rs | 17 ++++-- src/entities/fractions/mod.rs | 2 +- src/entities/fractions/percent.rs | 8 +-- src/entities/mod.rs | 8 +-- src/entities/native_currency.rs | 3 +- src/entities/token.rs | 2 +- src/entities/weth9.rs | 15 +---- src/lib.rs | 6 +- src/utils/compute_price_impact.rs | 1 + src/utils/mod.rs | 2 +- src/utils/validate_and_parse_address.rs | 1 + 19 files changed, 100 insertions(+), 107 deletions(-) create mode 100644 rustfmt.toml diff --git a/Cargo.lock b/Cargo.lock index acfd89c..2148061 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -68,9 +68,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf617fabf5cdbdc92f774bfe5062d870f228b80056d41180797abf48bed4056e" +checksum = "26d4d6dafc1a3bb54687538972158f07b2c948bc57d5890df22c0739098b3028" dependencies = [ "borsh-derive", "cfg_aliases", @@ -78,15 +78,15 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f404657a7ea7b5249e36808dff544bc88a28f26e0ac40009f674b7a009d14be3" +checksum = "bf4918709cc4dd777ad2b6303ed03cb37f3ca0ccede8c1b0d28ac6db8f4710e0" dependencies = [ "once_cell", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.42", "syn_derive", ] @@ -153,9 +153,9 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" [[package]] name = "crossbeam-utils" -version = "0.8.16" +version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f" dependencies = [ "cfg-if", ] @@ -253,9 +253,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "lazy_static" @@ -265,9 +265,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.150" +version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "memchr" @@ -319,9 +319,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "ordered-float" @@ -340,10 +340,11 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro-crate" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" +checksum = "97dc5fea232fc28d2f597b37c4876b348a40e33f3b02cc975c8d006d78d94b1a" dependencies = [ + "toml_datetime", "toml_edit", ] @@ -372,9 +373,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" dependencies = [ "unicode-ident", ] @@ -519,12 +520,13 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.42" +version = "0.7.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0200c8230b013893c0b2d6213d6ec64ed2b9be2e0e016682b7224ff82cff5c58" +checksum = "527a97cdfef66f65998b5f3b637c26f5a5ec09cc52a3f9932313ac645f4190f5" dependencies = [ "bitvec", "bytecheck", + "bytes", "hashbrown 0.12.3", "ptr_meta", "rend", @@ -536,9 +538,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.42" +version = "0.7.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e06b915b5c230a17d7a736d1e2e63ee753c256a8614ef3f5147b13a4f5541d" +checksum = "b5c462a1328c8e67e4d6dbad1eb0355dd43e8ab432c6e227a43657f16ade5033" dependencies = [ "proc-macro2", "quote", @@ -600,9 +602,9 @@ checksum = "fe834bc780604f4674073badbad26d7219cadfb4a2275802db12cbae17498401" [[package]] name = "ryu" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" [[package]] name = "seahash" @@ -637,7 +639,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.42", ] [[package]] @@ -670,9 +672,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "5b7d0a2c048d661a1a59fcd7355baa232f7ed34e0ee4df2eef3c1c1c0d3852d8" dependencies = [ "proc-macro2", "quote", @@ -688,7 +690,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.42", ] [[package]] @@ -736,15 +738,15 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "toml_datetime" -version = "0.6.5" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" [[package]] name = "toml_edit" -version = "0.20.7" +version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" dependencies = [ "indexmap", "toml_datetime", @@ -827,9 +829,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "winnow" -version = "0.5.22" +version = "0.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40460c13b1e9b107cfc9ede71232f204c36250bbf6f9c78515e2e27ead3122a7" +checksum = "9b5c3db89721d50d0e2a673f5043fc4722f76dcc352d7b1ab8b8288bed4ed2c5" dependencies = [ "memchr", ] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..4b8a8c2 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +max_width = 100 +imports_granularity = "Crate" +unstable_features = true diff --git a/src/addresses.rs b/src/addresses.rs index 0f2219c..1e79d0e 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -472,14 +472,8 @@ pub fn v1_mixed_route_quoter_address() -> ChainAddress { pub fn swap_router02_address(chainid: u32) -> ChainAddresses { if chainid == ChainId::BNB as u32 { - CHAIN_TO_ADDRESSES_MAP - .get(&{ chainid }) - .unwrap() - .to_owned() + CHAIN_TO_ADDRESSES_MAP.get(&{ chainid }).unwrap().to_owned() } else { - CHAIN_TO_ADDRESSES_MAP - .get(&{ chainid }) - .unwrap() - .to_owned() + CHAIN_TO_ADDRESSES_MAP.get(&{ chainid }).unwrap().to_owned() } } diff --git a/src/chains.rs b/src/chains.rs index d51c2c2..f70eaab 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -20,28 +20,27 @@ pub enum ChainId { } pub const SUPPORTED_CHAINS: [ChainId; 15] = [ - ChainId::MAINNET, - ChainId::OPTIMISM, - ChainId::OPTIMISMGOERLI, - ChainId::ARBITRUMONE, - ChainId::ARBITRUMGOERLI, - ChainId::POLYGON, - ChainId::POLYGONMUMBAI, - ChainId::GOERLI, - ChainId::SEPOLIA, - ChainId::CELOALFAJORES, - ChainId::CELO, - ChainId::BNB, - ChainId::AVALANCHE, - ChainId::BASE, - ChainId::BASEGOERLI, + ChainId::MAINNET, + ChainId::OPTIMISM, + ChainId::OPTIMISMGOERLI, + ChainId::ARBITRUMONE, + ChainId::ARBITRUMGOERLI, + ChainId::POLYGON, + ChainId::POLYGONMUMBAI, + ChainId::GOERLI, + ChainId::SEPOLIA, + ChainId::CELOALFAJORES, + ChainId::CELO, + ChainId::BNB, + ChainId::AVALANCHE, + ChainId::BASE, + ChainId::BASEGOERLI, ]; - pub enum NativeCurrencyName { ETHER, MATIC, - CELO , + CELO, GNOSIS, MOONBEAM, BNB, diff --git a/src/constants.rs b/src/constants.rs index 06fd6f6..5c091f6 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,6 +1,6 @@ +use lazy_static::lazy_static; use num_bigint::BigInt; use num_traits::Num; -use lazy_static::lazy_static; pub enum TradeType { ExactInput, @@ -14,5 +14,9 @@ pub enum Rounding { } lazy_static! { - pub static ref MAX_UINT256: BigInt = BigInt::from_str_radix("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).unwrap(); -} \ No newline at end of file + pub static ref MAX_UINT256: BigInt = BigInt::from_str_radix( + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", + 16 + ) + .unwrap(); +} diff --git a/src/entities/base_currency.rs b/src/entities/base_currency.rs index 7a93373..72bad74 100644 --- a/src/entities/base_currency.rs +++ b/src/entities/base_currency.rs @@ -7,7 +7,7 @@ pub struct BaseCurrency { pub decimals: u32, pub name: Option, pub symbol: Option, - pub is_native: bool + pub is_native: bool, } impl BaseCurrency { @@ -24,12 +24,10 @@ impl BaseCurrency { } } - /** * Returns whether the currency is native to the chain and must be wrapped (e.g. Ether) - */ + */ pub fn is_native() -> bool { true } } - diff --git a/src/entities/currency.rs b/src/entities/currency.rs index b734156..c0de993 100644 --- a/src/entities/currency.rs +++ b/src/entities/currency.rs @@ -1,7 +1,7 @@ -use super::{token::Token, native_currency::NativeCurrency}; +use super::{native_currency::NativeCurrency, token::Token}; #[derive(Clone, PartialEq)] pub enum Currency { - NativeCurrency(NativeCurrency), + NativeCurrency(NativeCurrency), Token(Token), -} \ No newline at end of file +} diff --git a/src/entities/ether.rs b/src/entities/ether.rs index c6781e3..2dd15ce 100644 --- a/src/entities/ether.rs +++ b/src/entities/ether.rs @@ -31,7 +31,7 @@ impl Ether { &self.wrapped } - pub fn on_chain() -> Ether{ + pub fn on_chain() -> Ether { Ether::new(1) } @@ -46,12 +46,11 @@ mod tests { #[test] fn test_ethers() { - let eth = Ether::new(1); assert!(eth == Ether::on_chain(), "not equal"); } - + #[test] #[should_panic] fn test_expect_revert() { @@ -68,7 +67,6 @@ mod tests { assert!(*weth == eth2.wrapped, "NOT WETH"); } - #[test] #[should_panic] fn test_expect_revert_wrapped() { diff --git a/src/entities/fractions/currency_amount.rs b/src/entities/fractions/currency_amount.rs index 8521bee..1f3de4c 100644 --- a/src/entities/fractions/currency_amount.rs +++ b/src/entities/fractions/currency_amount.rs @@ -1,6 +1,7 @@ - - -use crate::entities::{currency::Currency, fractions::fraction::{Fraction, Rounding}}; +use crate::entities::{ + currency::Currency, + fractions::fraction::{Fraction, Rounding}, +}; use num_bigint::{BigInt, BigUint}; use num_traits::ToPrimitive; @@ -83,11 +84,15 @@ impl CurrencyAmount { pub fn to_fixed(&self, decimals: BigUint) -> String { assert!(decimals <= self.decimal_scale.clone().unwrap(), "DECIMALS"); - Fraction::to_fixed(&self.fraction.clone().unwrap(), decimals.to_u32().unwrap(), Rounding::RoundUp) + Fraction::to_fixed( + &self.fraction.clone().unwrap(), + decimals.to_u32().unwrap(), + Rounding::RoundUp, + ) } - + //Implementation not done yet - pub fn to_exact(){} + pub fn to_exact() {} // pub fn wrapped(&self) -> CurrencyAmount { // if Token::is_token() {//don't really understand this part, but is_token will always return true anyway diff --git a/src/entities/fractions/mod.rs b/src/entities/fractions/mod.rs index d30254b..0d4f58f 100644 --- a/src/entities/fractions/mod.rs +++ b/src/entities/fractions/mod.rs @@ -1,4 +1,4 @@ +pub mod currency_amount; pub mod fraction; pub mod percent; pub mod price; -pub mod currency_amount; \ No newline at end of file diff --git a/src/entities/fractions/percent.rs b/src/entities/fractions/percent.rs index 785a6b9..612e3e1 100644 --- a/src/entities/fractions/percent.rs +++ b/src/entities/fractions/percent.rs @@ -32,13 +32,13 @@ impl Percent { } pub fn to_significant(&self, other: &Fraction) -> String { - let hundred = Fraction::new(BigInt::from(100) , BigInt::from(1)); - let mult = Fraction::multiply(&hundred, other); - Fraction::to_significant(&mult, 5, Rounding::RoundUp) + let hundred = Fraction::new(BigInt::from(100), BigInt::from(1)); + let mult = Fraction::multiply(&hundred, other); + Fraction::to_significant(&mult, 5, Rounding::RoundUp) } pub fn to_fixed(&self, other: &Fraction) -> String { - let hundred = Fraction::new(BigInt::from(100) , BigInt::from(1)); + let hundred = Fraction::new(BigInt::from(100), BigInt::from(1)); let mult = Fraction::multiply(&hundred, other); Fraction::to_fixed(&mult, 2, Rounding::RoundUp) } diff --git a/src/entities/mod.rs b/src/entities/mod.rs index e2a3d76..6e0c6df 100644 --- a/src/entities/mod.rs +++ b/src/entities/mod.rs @@ -1,7 +1,7 @@ -pub mod fractions; -pub mod token; pub mod base_currency; +pub mod currency; pub mod ether; -pub mod weth9; +pub mod fractions; pub mod native_currency; -pub mod currency; \ No newline at end of file +pub mod token; +pub mod weth9; diff --git a/src/entities/native_currency.rs b/src/entities/native_currency.rs index 0bf81d5..e4aa7ef 100644 --- a/src/entities/native_currency.rs +++ b/src/entities/native_currency.rs @@ -1,6 +1,5 @@ - #[derive(Clone, PartialEq)] pub struct NativeCurrency { pub is_native: bool, pub is_token: bool, -} \ No newline at end of file +} diff --git a/src/entities/token.rs b/src/entities/token.rs index 57f5a31..21f4f1e 100644 --- a/src/entities/token.rs +++ b/src/entities/token.rs @@ -1,7 +1,7 @@ use super::base_currency::BaseCurrency; use num_bigint::BigUint; -#[derive(Clone, PartialEq)] +#[derive(Clone, PartialEq)] pub struct Token { pub base_currency: BaseCurrency, pub address: String, diff --git a/src/entities/weth9.rs b/src/entities/weth9.rs index 9f1edea..bb56d36 100644 --- a/src/entities/weth9.rs +++ b/src/entities/weth9.rs @@ -1,5 +1,5 @@ -use std::collections::HashMap; use super::token::Token; +use std::collections::HashMap; pub struct WETH9 { tokens: HashMap, @@ -23,7 +23,7 @@ impl WETH9 { Some("WETH".to_string()), Some("Wrapped Ether".to_string()), None, - None + None, ), ); tokens.insert( @@ -48,7 +48,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -61,7 +60,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -74,7 +72,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -87,7 +84,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -100,7 +96,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -113,7 +108,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -126,7 +120,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -139,7 +132,6 @@ impl WETH9 { Some("Wrapped Ether".to_string()), None, None, - ), ); tokens.insert( @@ -152,7 +144,6 @@ impl WETH9 { Some("Wrapped BNB".to_string()), None, None, - ), ); tokens.insert( @@ -165,7 +156,6 @@ impl WETH9 { Some("Wrapped MATIC".to_string()), None, None, - ), ); tokens.insert( @@ -178,7 +168,6 @@ impl WETH9 { Some("Wrapped AVAX".to_string()), None, None, - ), ); diff --git a/src/lib.rs b/src/lib.rs index b0a705a..461d9c4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ -pub mod entities; -pub mod utils; +pub mod addresses; pub mod chains; pub mod constants; -pub mod addresses; \ No newline at end of file +pub mod entities; +pub mod utils; diff --git a/src/utils/compute_price_impact.rs b/src/utils/compute_price_impact.rs index e69de29..d3f5a12 100644 --- a/src/utils/compute_price_impact.rs +++ b/src/utils/compute_price_impact.rs @@ -0,0 +1 @@ + diff --git a/src/utils/mod.rs b/src/utils/mod.rs index f38a3a5..5279e1f 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,4 +1,4 @@ pub mod compute_price_impact; pub mod sorted_insert; pub mod sqrt; -pub mod validate_and_parse_address; \ No newline at end of file +pub mod validate_and_parse_address; diff --git a/src/utils/validate_and_parse_address.rs b/src/utils/validate_and_parse_address.rs index e69de29..d3f5a12 100644 --- a/src/utils/validate_and_parse_address.rs +++ b/src/utils/validate_and_parse_address.rs @@ -0,0 +1 @@ + From 75e913a32041e96a738c13f03b3d6fa8458893dd Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 15:19:23 -0800 Subject: [PATCH 2/8] remove clippy dependency --- Cargo.lock | 134 ++--------------------------------------------------- Cargo.toml | 1 - 2 files changed, 3 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2148061..0f7e7d3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,23 +8,11 @@ version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a824f2aa7e75a0c98c5a504fceb80649e9c35265d44525b5f94de4771a395cd" dependencies = [ - "getrandom 0.2.11", + "getrandom", "once_cell", "version_check", ] -[[package]] -name = "arrayref" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" - -[[package]] -name = "arrayvec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" - [[package]] name = "arrayvec" version = "0.7.4" @@ -37,12 +25,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - [[package]] name = "bitvec" version = "1.0.1" @@ -55,17 +37,6 @@ dependencies = [ "wyz", ] -[[package]] -name = "blake2b_simd" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" -dependencies = [ - "arrayref", - "arrayvec 0.5.2", - "constant_time_eq", -] - [[package]] name = "borsh" version = "1.3.0" @@ -112,12 +83,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "bytes" version = "1.5.0" @@ -136,41 +101,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" -[[package]] -name = "clippy" -version = "0.0.302" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d911ee15579a3f50880d8c1d59ef6e79f9533127a3bd342462f5d584f5e8c294" -dependencies = [ - "term", -] - -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - -[[package]] -name = "crossbeam-utils" -version = "0.8.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "dirs" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" -dependencies = [ - "libc", - "redox_users", - "winapi", -] - [[package]] name = "equivalent" version = "1.0.1" @@ -204,17 +134,6 @@ version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" -[[package]] -name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - [[package]] name = "getrandom" version = "0.2.11" @@ -480,7 +399,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.11", + "getrandom", ] [[package]] @@ -492,23 +411,6 @@ dependencies = [ "rand_core 0.3.1", ] -[[package]] -name = "redox_syscall" -version = "0.1.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" - -[[package]] -name = "redox_users" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" -dependencies = [ - "getrandom 0.1.16", - "redox_syscall", - "rust-argon2", -] - [[package]] name = "rend" version = "0.4.1" @@ -547,18 +449,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "rust-argon2" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" -dependencies = [ - "base64", - "blake2b_simd", - "constant_time_eq", - "crossbeam-utils", -] - [[package]] name = "rust-crypto" version = "0.2.36" @@ -578,7 +468,7 @@ version = "1.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06676aec5ccb8fc1da723cc8c0f9a46549f21ebb8753d3915c6c41db1e7f1dc4" dependencies = [ - "arrayvec 0.7.4", + "arrayvec", "borsh", "bytes", "num-traits", @@ -699,17 +589,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" -[[package]] -name = "term" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" -dependencies = [ - "byteorder", - "dirs", - "winapi", -] - [[package]] name = "time" version = "0.1.45" @@ -763,7 +642,6 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" name = "uniswap-sdk-core-rust" version = "0.1.0" dependencies = [ - "clippy", "eth_checksum", "lazy_static", "num-bigint", @@ -787,12 +665,6 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" -[[package]] -name = "wasi" -version = "0.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - [[package]] name = "wasi" version = "0.10.0+wasi-snapshot-preview1" diff --git a/Cargo.toml b/Cargo.toml index 7cca8a4..0185e6d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -clippy = "0.0.302" eth_checksum = "0.1.2" lazy_static = "1.4.0" num-bigint = "0.4.4" From 2d87eff40dbb1988f7fb46b22332d574ac1322c2 Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 15:19:50 -0800 Subject: [PATCH 3/8] remove redundant check in `sqrt` --- src/utils/sqrt.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/utils/sqrt.rs b/src/utils/sqrt.rs index 920c6da..5c897ef 100644 --- a/src/utils/sqrt.rs +++ b/src/utils/sqrt.rs @@ -1,19 +1,15 @@ use num_bigint::{BigInt, ToBigInt}; use num_traits::{ToPrimitive, Zero}; -const MAX_SAFE_INTEGER: i64 = i64::MAX; - fn sqrt(value: &BigInt) -> BigInt { assert!(*value >= Zero::zero(), "NEGATIVE"); // If the value is less than or equal to MAX_SAFE_INTEGER, // we can safely convert it to an i64 and use the primitive sqrt function. if let Some(safe_value) = value.to_i64() { - if safe_value <= MAX_SAFE_INTEGER { - return ((safe_value as f64).sqrt().floor() as i64) - .to_bigint() - .unwrap(); - } + return ((safe_value as f64).sqrt().floor() as i64) + .to_bigint() + .unwrap(); } // Otherwise, we use the Babylonian method to calculate the square root. From 6a569c51d2e15fb4f0bbf027e035d65470f683db Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 15:20:36 -0800 Subject: [PATCH 4/8] refactor addresses.rs --- src/addresses.rs | 147 +++++++++++++++++++++++------------------------ 1 file changed, 72 insertions(+), 75 deletions(-) diff --git a/src/addresses.rs b/src/addresses.rs index 1e79d0e..bc278f6 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -1,6 +1,7 @@ use super::chains::{ChainId, SUPPORTED_CHAINS}; use lazy_static::lazy_static; use std::collections::HashMap; + type AddressMap = HashMap; type ChainMap = HashMap; type ChainAddress = HashMap; @@ -18,29 +19,29 @@ pub struct ChainAddresses { v1_mixed_route_quoter_address: Option, } -pub const _DEFAULT_NETWORKS: [ChainId; 3] = [ChainId::MAINNET, ChainId::GOERLI, ChainId::SEPOLIA]; +pub const DEFAULT_NETWORKS: [ChainId; 3] = [ChainId::MAINNET, ChainId::GOERLI, ChainId::SEPOLIA]; -pub fn construct_same_address_map(address: &str, additional_networks: Vec) -> AddressMap { +pub fn construct_same_address_map(address: &str, additional_networks: &[ChainId]) -> AddressMap { + let mut networks = DEFAULT_NETWORKS.to_vec(); + networks.extend_from_slice(additional_networks); let mut map = AddressMap::new(); - let default_networks = [1, 2, 3]; // Placeholder for actual default networks - for &network in default_networks.iter().chain(additional_networks.iter()) { - map.insert(network, address.to_string()); + for chain_id in networks { + map.insert(chain_id as u32, String::from(address)); } map } lazy_static! { #[derive(Copy, Clone)] - pub static ref UNIADDRESSES: AddressMap = construct_same_address_map( + pub static ref UNI_ADDRESSES: AddressMap = construct_same_address_map( "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", - [ - ChainId::OPTIMISM as u32, - ChainId::ARBITRUMONE as u32, - ChainId::POLYGON as u32, - ChainId::POLYGONMUMBAI as u32, - ChainId::SEPOLIA as u32, + &[ + ChainId::OPTIMISM, + ChainId::ARBITRUMONE, + ChainId::POLYGON, + ChainId::POLYGONMUMBAI, + ChainId::SEPOLIA, ] - .to_vec() ); } @@ -51,16 +52,15 @@ pub const V2_FACTORY_ADDRESS: &str = "0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f lazy_static! { pub static ref V2_FACTORY_ADDRESSES: AddressMap = construct_same_address_map( V2_FACTORY_ADDRESS, - [ - ChainId::POLYGON as u32, - ChainId::OPTIMISM as u32, - ChainId::CELO as u32, - ChainId::ARBITRUMONE as u32, - ChainId::BNB as u32, - ChainId::AVALANCHE as u32, - ChainId::BASE as u32, + &[ + ChainId::POLYGON, + ChainId::OPTIMISM, + ChainId::CELO, + ChainId::ARBITRUMONE, + ChainId::BNB, + ChainId::AVALANCHE, + ChainId::BASE, ] - .to_vec() ); } @@ -68,47 +68,47 @@ pub const V2_ROUTER_ADDRESS: &str = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D" lazy_static! { pub static ref V2_ROUTER_ADDRESSES: AddressMap = - construct_same_address_map(V2_ROUTER_ADDRESS, [].to_vec()); -} - -pub fn default_addr() -> ChainAddresses { - // Networks that share most of the same addresses i.e. Mainnet, Goerli, Optimism, Arbitrum, Polygon - let default_addresses: ChainAddresses = ChainAddresses { - v3_core_factory_address: "0x1F98431c8aD98523631AE4a59f267346ea31F984".to_string(), - multicall_address: "0x1F98415757620B543A52E61c46B32eB19261F984".to_string(), - quoter_address: "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6".to_string(), - v3_migrator_address: Some("0xA5644E29708357803b5A882D272c41cC0dF92B34".to_string()), - nonfungible_position_manager_address: Some( - "0xC36442b4a4522E871399CD717aBDD847Ab11FE88".to_string(), - ), - tick_lens_address: None, - swap_router02_address: None, - v1_mixed_route_quoter_address: None, - }; - default_addresses + construct_same_address_map(V2_ROUTER_ADDRESS, &[]); +} + +impl ChainAddresses { + /// Networks that share most of the same addresses i.e. Mainnet, Goerli, Optimism, Arbitrum, Polygon + pub fn default() -> Self { + ChainAddresses { + v3_core_factory_address: "0x1F98431c8aD98523631AE4a59f267346ea31F984".to_string(), + multicall_address: "0x1F98415757620B543A52E61c46B32eB19261F984".to_string(), + quoter_address: "0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6".to_string(), + v3_migrator_address: Some("0xA5644E29708357803b5A882D272c41cC0dF92B34".to_string()), + nonfungible_position_manager_address: Some( + "0xC36442b4a4522E871399CD717aBDD847Ab11FE88".to_string(), + ), + tick_lens_address: None, + swap_router02_address: None, + v1_mixed_route_quoter_address: None, + } + } } pub fn mainnet_address() -> ChainAddresses { - let mut mainnet_addresses = default_addr().clone(); + let mut mainnet_addresses = ChainAddresses::default(); mainnet_addresses.v1_mixed_route_quoter_address = Some("0x84E44095eeBfEC7793Cd7d5b57B7e401D7f1cA2E".to_string()); mainnet_addresses } pub fn goerli_address() -> ChainAddresses { - let mut mainnet_addresses = default_addr().clone(); + let mut mainnet_addresses = ChainAddresses::default(); mainnet_addresses.v1_mixed_route_quoter_address = Some("0xBa60b6e6fF25488308789E6e0A65D838be34194e".to_string()); mainnet_addresses } pub fn optimism_addresses() -> ChainAddresses { - let optimism_addresses: ChainAddresses = default_addr().clone(); - optimism_addresses + ChainAddresses::default() } pub fn arbitum_one_addresses() -> ChainAddresses { - let mut mainnet_addresses = default_addr().clone(); + let mut mainnet_addresses = ChainAddresses::default(); mainnet_addresses.multicall_address = "0xadF885960B47eA2CD9B55E6DAc6B42b7Cb2806dB".to_string(); mainnet_addresses.tick_lens_address = Some("0xbfd8137f7d1516D3ea5cA83523914859ec47F573".to_string()); @@ -116,13 +116,11 @@ pub fn arbitum_one_addresses() -> ChainAddresses { } pub fn polygon_addresses() -> ChainAddresses { - let polygon_addresses: ChainAddresses = default_addr().clone(); - polygon_addresses + ChainAddresses::default() } -// celo v3 addresses +/// celo v3 addresses pub fn celo_addresses() -> ChainAddresses { - // Networks that share most of the same addresses i.e. Mainnet, Goerli, Optimism, Arbitrum, Polygon ChainAddresses { v3_core_factory_address: "0xAfE208a311B21f13EF87E33A90049fC17A7acDEc".to_string(), multicall_address: "0x633987602DE5C4F337e3DbF265303A1080324204".to_string(), @@ -137,7 +135,7 @@ pub fn celo_addresses() -> ChainAddresses { } } -// BNB v3 addresses +/// BNB v3 addresses pub fn bnb_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7".to_string(), @@ -153,7 +151,7 @@ pub fn bnb_addresses() -> ChainAddresses { } } -// Optimism Goerli addresses +/// Optimism Goerli addresses pub fn optimism_goerli_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0xB656dA17129e7EB733A557f4EBc57B76CFbB5d10".to_string(), @@ -169,7 +167,7 @@ pub fn optimism_goerli_addresses() -> ChainAddresses { } } -// Arbitrum Goerli v3 addresses +/// Arbitrum Goerli v3 addresses pub fn arbitrum_goerli_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0x4893376342d5D7b3e31d4184c08b265e5aB2A3f6".to_string(), @@ -185,8 +183,8 @@ pub fn arbitrum_goerli_addresses() -> ChainAddresses { } } +/// sepolia v3 addresses pub fn sepolia_address() -> ChainAddresses { - // Sepolia v3 addresses ChainAddresses { v3_core_factory_address: "0x0227628f3F023bb0B980b67D528571c95c6DaC1c".to_string(), multicall_address: "0xD7F33bCdb21b359c8ee6F0251d30E94832baAd07".to_string(), @@ -201,7 +199,7 @@ pub fn sepolia_address() -> ChainAddresses { } } -// Avalanche v3 addresses +/// Avalanche v3 addresses pub fn avalanche_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD".to_string(), @@ -217,7 +215,7 @@ pub fn avalanche_addresses() -> ChainAddresses { } } -// Base v3 addresses +/// Base v3 addresses pub fn base_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0x33128a8fC17869897dcE68Ed026d694621f6FDfD".to_string(), @@ -233,7 +231,7 @@ pub fn base_addresses() -> ChainAddresses { } } -// Base Goerli v3 addresses +/// Base Goerli v3 addresses pub fn base_goerli_addresses() -> ChainAddresses { ChainAddresses { v3_core_factory_address: "0x9323c1d6D800ed51Bd7C6B216cfBec678B7d0BC2".to_string(), @@ -256,14 +254,11 @@ lazy_static! { new_map.insert(ChainId::AVALANCHE as u32, avalanche_addresses()); new_map.insert(ChainId::MAINNET as u32, mainnet_address()); - new_map.insert(ChainId::SEPOLIA as u32, sepolia_address().clone()); + new_map.insert(ChainId::SEPOLIA as u32, sepolia_address()); new_map.insert(ChainId::GOERLI as u32, goerli_address()); new_map.insert(ChainId::ARBITRUMONE as u32, arbitum_one_addresses()); - new_map.insert( - ChainId::ARBITRUMGOERLI as u32, - arbitrum_goerli_addresses().clone(), - ); - new_map.insert(ChainId::CELO as u32, celo_addresses().clone()); + new_map.insert(ChainId::ARBITRUMGOERLI as u32, arbitrum_goerli_addresses()); + new_map.insert(ChainId::CELO as u32, celo_addresses()); new_map.insert(ChainId::CELOALFAJORES as u32, celo_addresses()); new_map.insert(ChainId::POLYGON as u32, polygon_addresses()); @@ -277,7 +272,7 @@ lazy_static! { }; } -/* V3 Contract Addresses */ +/// V3 Contract Addresses pub fn v3_factory_addresses() -> ChainAddress { let mut chain_add = ChainAddress::new(); for memo in SUPPORTED_CHAINS { @@ -293,7 +288,7 @@ pub fn v3_factory_addresses() -> ChainAddress { chain_add } -/* V3 Contract Addresses */ +/// V3 Contract Addresses pub fn v3_migrator_addresses() -> ChainAddress { let mut chain_add = ChainAddress::new(); for memo in SUPPORTED_CHAINS { @@ -310,7 +305,7 @@ pub fn v3_migrator_addresses() -> ChainAddress { chain_add } -/* V3 Contract Addresses */ +/// V3 Contract Addresses pub fn multicall_addresses() -> ChainAddress { let mut chain_add = ChainAddress::new(); for memo in SUPPORTED_CHAINS { @@ -327,7 +322,7 @@ pub fn multicall_addresses() -> ChainAddress { } pub fn governance_alpha_v0_addresses() -> AddressMap { - construct_same_address_map("0x5e4be8Bc9637f0EAA1A755019e06A68ce081D58F", [].to_vec()) + construct_same_address_map("0x5e4be8Bc9637f0EAA1A755019e06A68ce081D58F", &[]) } pub fn governance_alpha_v1_addresses() -> AddressMap { @@ -349,7 +344,7 @@ pub fn governance_bravo_addresses() -> AddressMap { } pub fn timelock_addresses() -> AddressMap { - construct_same_address_map("0x1a9C8182C09F50C8318d769245beA5", [].to_vec()) + construct_same_address_map("0x1a9C8182C09F50C8318d769245beA5", &[]) } pub fn merkle_distributor_address() -> AddressMap { @@ -392,7 +387,6 @@ pub fn nonfungible_position_manager_address() -> ChainAddress { .get(&(memo as u32)) .unwrap() .nonfungible_position_manager_address - .clone() .is_some() { chain_add.insert( @@ -410,7 +404,7 @@ pub fn nonfungible_position_manager_address() -> ChainAddress { } pub fn ens_resgister_address_map() -> AddressMap { - construct_same_address_map("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", [].to_vec()) + construct_same_address_map("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", &[]) } pub fn socks_controller_addresses() -> AddressMap { @@ -429,7 +423,6 @@ pub fn tick_lens_addresses() -> ChainAddress { .get(&(memo as u32)) .unwrap() .tick_lens_address - .clone() .is_some() { chain_add.insert( @@ -453,7 +446,6 @@ pub fn v1_mixed_route_quoter_address() -> ChainAddress { .get(&(memo as u32)) .unwrap() .v1_mixed_route_quoter_address - .clone() .is_some() { chain_add.insert( @@ -470,10 +462,15 @@ pub fn v1_mixed_route_quoter_address() -> ChainAddress { chain_add } -pub fn swap_router02_address(chainid: u32) -> ChainAddresses { - if chainid == ChainId::BNB as u32 { - CHAIN_TO_ADDRESSES_MAP.get(&{ chainid }).unwrap().to_owned() +pub fn swap_router02_address(chain_id: u32) -> String { + if chain_id == ChainId::BNB as u32 { + CHAIN_TO_ADDRESSES_MAP + .get(&chain_id) + .unwrap() + .swap_router02_address + .clone() + .unwrap() } else { - CHAIN_TO_ADDRESSES_MAP.get(&{ chainid }).unwrap().to_owned() + "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45".into() } } From c5b38e60bcce2f0870512b0ca8cbadb34184aa1c Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 16:22:55 -0800 Subject: [PATCH 5/8] refactor ether.rs and tests --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/addresses.rs | 1 - src/entities/base_currency.rs | 8 ++---- src/entities/ether.rs | 51 ++++++++++++++++++----------------- 5 files changed, 31 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0f7e7d3..1d77816 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -640,7 +640,7 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "uniswap-sdk-core-rust" -version = "0.1.0" +version = "0.1.1" dependencies = [ "eth_checksum", "lazy_static", diff --git a/Cargo.toml b/Cargo.toml index 0185e6d..5282d6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "uniswap-sdk-core-rust" -version = "0.1.0" +version = "0.1.1" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/addresses.rs b/src/addresses.rs index bc278f6..25975ca 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -7,7 +7,6 @@ type ChainMap = HashMap; type ChainAddress = HashMap; #[derive(Clone)] -#[allow(dead_code)] pub struct ChainAddresses { v3_core_factory_address: String, multicall_address: String, diff --git a/src/entities/base_currency.rs b/src/entities/base_currency.rs index 72bad74..5f5135d 100644 --- a/src/entities/base_currency.rs +++ b/src/entities/base_currency.rs @@ -1,6 +1,4 @@ -/** - * A currency is any fungible financial instrument, including Ether, all ERC20 tokens, and other chain-native currencies - */ +/// A currency is any fungible financial instrument, including Ether, all ERC20 tokens, and other chain-native currencies #[derive(Clone, PartialEq)] pub struct BaseCurrency { pub chain_id: u32, @@ -24,9 +22,7 @@ impl BaseCurrency { } } - /** - * Returns whether the currency is native to the chain and must be wrapped (e.g. Ether) - */ + /// Returns whether the currency is native to the chain and must be wrapped (e.g. Ether) pub fn is_native() -> bool { true } diff --git a/src/entities/ether.rs b/src/entities/ether.rs index 2dd15ce..6745787 100644 --- a/src/entities/ether.rs +++ b/src/entities/ether.rs @@ -1,6 +1,13 @@ use super::{base_currency::BaseCurrency, token::Token}; +use lazy_static::lazy_static; +use std::{collections::HashMap, sync::Mutex}; -#[derive(PartialEq)] +lazy_static! { + static ref ETHER_CACHE: Mutex> = Mutex::new(HashMap::new()); +} + +/// Ether is the main usage of a 'native' currency, i.e. for Ethereum mainnet and all testnets +#[derive(Clone, PartialEq)] pub struct Ether { base_currency: BaseCurrency, wrapped: Token, @@ -31,8 +38,16 @@ impl Ether { &self.wrapped } - pub fn on_chain() -> Ether { - Ether::new(1) + pub fn on_chain(chain_id: u32) -> Self { + let mut cache = ETHER_CACHE.lock().unwrap(); + match cache.get(&chain_id) { + Some(ether) => ether.clone(), + None => { + let ether = Ether::new(chain_id); + cache.insert(chain_id, ether.clone()); + ether + } + } } pub fn equals(&self, other: &BaseCurrency) -> bool { @@ -42,37 +57,25 @@ impl Ether { #[cfg(test)] mod tests { - use super::Ether; + use super::*; #[test] - fn test_ethers() { - let eth = Ether::new(1); - - assert!(eth == Ether::on_chain(), "not equal"); + fn test_static_constructor_uses_cache() { + assert!(Ether::on_chain(1) == Ether::on_chain(1)); } #[test] - #[should_panic] - fn test_expect_revert() { - let eth = Ether::new(2); - - assert!(eth == Ether::on_chain(), "not equal"); + fn test_caches_once_per_chain_id() { + assert!(Ether::on_chain(1) != Ether::on_chain(2)); } #[test] - fn test_wrapped() { - let eth = Ether::new(1); - let eth2 = Ether::new(1); - let weth = Ether::wrapped(ð); - assert!(*weth == eth2.wrapped, "NOT WETH"); + fn test_equals_returns_false_for_different_chains() { + assert!(!Ether::on_chain(1).equals(&Ether::on_chain(2).base_currency)); } #[test] - #[should_panic] - fn test_expect_revert_wrapped() { - let eth = Ether::new(1); - let eth2 = Ether::new(2); - let weth = Ether::wrapped(ð); - assert!(*weth == eth2.wrapped, "NOT WETH"); + fn test_equals_returns_true_for_same_chains() { + assert!(Ether::on_chain(1).equals(&Ether::on_chain(1).base_currency)); } } From af97acfb1e97257dd7e83806b6784291a35d7679 Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 16:25:02 -0800 Subject: [PATCH 6/8] refactor token.rs and fix tests --- src/entities/token.rs | 69 +++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/src/entities/token.rs b/src/entities/token.rs index 21f4f1e..878e7e3 100644 --- a/src/entities/token.rs +++ b/src/entities/token.rs @@ -1,11 +1,11 @@ use super::base_currency::BaseCurrency; use num_bigint::BigUint; +/// Represents an ERC20 token with a unique address and some metadata. #[derive(Clone, PartialEq)] pub struct Token { pub base_currency: BaseCurrency, pub address: String, - //bypass_checksum: bool, pub buy_fee_bps: Option, pub sell_fee_bps: Option, } @@ -30,25 +30,44 @@ impl Token { } } - pub fn is_native() -> bool { + pub fn is_native(&self) -> bool { false } - pub fn is_token() -> bool { + pub fn is_token(&self) -> bool { true } + /// Returns true if the two tokens are equivalent, i.e. have the same chainId and address. + /// + /// # Arguments + /// + /// * `other` - The other token to compare. + /// pub fn equals(&self, other: &Token) -> bool { - self.base_currency.chain_id == other.base_currency.chain_id + other.is_token() + && self.base_currency.chain_id == other.base_currency.chain_id + && self.address.to_lowercase() == other.address.to_lowercase() } + /// Returns true if the address of this token sorts before the address of the other token. + /// Panics if the tokens have the same address or if the tokens are on different chains. + /// + /// # Arguments + /// + /// * `other` - The other token to compare. + /// pub fn sorts_before(&self, other: &Token) -> bool { - assert!( - self.base_currency.chain_id == other.base_currency.chain_id, + assert_eq!( + self.base_currency.chain_id, other.base_currency.chain_id, "CHAIN_IDS" ); - assert!(self.address != other.address, "ADDRESSES"); - self.address < other.address + assert_ne!( + self.address.to_lowercase(), + other.address.to_lowercase(), + "ADDRESSES" + ); + self.address.to_lowercase() < other.address.to_lowercase() } pub fn wrapped(&self) -> Token { @@ -58,7 +77,7 @@ impl Token { #[cfg(test)] mod tests { - //should test for neg chain_id or neg decicals or neg_buyfee or neg sellfee, but the compiler will panic by itself, so no need + //should test for neg chain_id or neg decimals or neg buy_fee or neg sell_fee, but the compiler will panic by itself, so no need use super::Token; const ADDRESS_ONE: &str = "0x0000000000000000000000000000000000000001"; const ADDRESS_TWO: &str = "0x0000000000000000000000000000000000000002"; @@ -85,8 +104,8 @@ mod tests { None, ); - assert!(token.address == *ADDRESS_ONE); - assert!(token_1.address == *ADDRESS_TWO); + assert_eq!(token.address, *ADDRESS_ONE); + assert_eq!(token_1.address, *ADDRESS_TWO); } #[test] @@ -127,20 +146,19 @@ mod tests { ); assert!( - token == token_1, + token.equals(&token_1), "SHOULD_FAILS_EVEN_THOUGH_CHAIN_ID_IS_DIFFERENT" ); } #[test] - #[should_panic] - fn test_expect_revert_diff_name() { + fn test_diff_name() { let token = Token::new( 4, ADDRESS_ONE.to_string(), 25, Some("Test".to_string()), - Some("Te".to_string()), + Some("TeW".to_string()), None, None, ); @@ -149,27 +167,23 @@ mod tests { 4, ADDRESS_ONE.to_string(), 25, - Some("WETest".to_string()), + Some("Test".to_string()), Some("Te".to_string()), None, None, ); - assert!( - token == token_1, - "SHOULD_FAILS_EVEN_THOUGH_NAME_IS_DIFFERENT" - ); + assert!(token.equals(&token_1), "true even if names differ"); } #[test] - #[should_panic] - fn test_expect_revert_diff_symbol() { + fn test_diff_symbol() { let token = Token::new( 4, ADDRESS_ONE.to_string(), 25, Some("Test".to_string()), - Some("TeW".to_string()), + Some("Te".to_string()), None, None, ); @@ -184,10 +198,7 @@ mod tests { None, ); - assert!( - token == token_1, - "SHOULD_FAILS_EVEN_THOUGH_SYMBOL_IS_DIFFERENT" - ); + assert!(token.equals(&token_1), "true even if symbols differ"); } #[test] @@ -214,7 +225,7 @@ mod tests { ); assert!( - token == token_1, + token.equals(&token_1), "SHOULD_FAILS_EVEN_THOUGH_ADDRESS_IS_DIFFERENT" ); } @@ -241,6 +252,6 @@ mod tests { None, ); - assert!(token.equals(&token_1) == token_1.equals(&token), "SHOULD_FAILS_EVEN_THOUGH_ADDRESS_IS_DIFFERENT, SHOULD ONLY REVERT FOR DIFFERENT CHAIN_ID"); + assert_eq!(token.equals(&token_1), token_1.equals(&token), "SHOULD_FAILS_EVEN_THOUGH_ADDRESS_IS_DIFFERENT, SHOULD ONLY REVERT FOR DIFFERENT CHAIN_ID"); } } From 696af597bc21831496bd955a4d2fc44fafd92948 Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 22:16:20 -0800 Subject: [PATCH 7/8] fix and test `sorted_insert` --- src/utils/sorted_insert.rs | 119 +++++++++++++++++++++++++++++++++---- 1 file changed, 109 insertions(+), 10 deletions(-) diff --git a/src/utils/sorted_insert.rs b/src/utils/sorted_insert.rs index a7f5a50..0bbee28 100644 --- a/src/utils/sorted_insert.rs +++ b/src/utils/sorted_insert.rs @@ -1,21 +1,120 @@ -pub fn sorted_insert(items: &mut Vec, add: T, max_size: usize) -> Option { +use std::cmp::Ordering; + +/// Given an array of items sorted by `comparator`, insert an item into its sort index and constrain the size to +/// `maxSize` by removing the last item +pub fn sorted_insert( + items: &mut Vec, + add: T, + max_size: usize, + comparator: fn(&T, &T) -> Ordering, +) -> Option { assert!(max_size > 0, "MAX_SIZE_ZERO"); assert!(items.len() <= max_size, "ITEMS_SIZE"); - // Find the position to insert the new item - let pos = match items.binary_search(&add) { - Ok(pos) | Err(pos) => pos, - }; - - // If the array is full, remove the last item let removed_item = if items.len() == max_size { - items.pop() + match items.last() { + Some(last) if comparator(&add, last) != Ordering::Greater => items.pop(), + // short circuit if full and the additional item does not come before the last item + _ => return Some(add), + } } else { None }; - // Insert the new item at the correct position - items.insert(pos, add); + let pos = match items.binary_search_by(|i| comparator(i, &add)) { + Ok(pos) | Err(pos) => pos, + }; + items.insert(pos, add); removed_item } + +#[cfg(test)] +mod tests { + use super::*; + + fn cmp(a: &i32, b: &i32) -> Ordering { + a.cmp(b) + } + + fn reverse_cmp(a: &i32, b: &i32) -> Ordering { + b.cmp(a) + } + + #[test] + #[should_panic(expected = "MAX_SIZE_ZERO")] + fn test_max_size_zero() { + let mut arr = Vec::new(); + sorted_insert(&mut arr, 1, 0, cmp); + } + + #[test] + #[should_panic(expected = "ITEMS_SIZE")] + fn test_length_greater_than_max_size() { + let mut arr = vec![1, 2]; + sorted_insert(&mut arr, 1, 1, cmp); + } + + #[test] + fn test_add_if_empty() { + let mut arr = Vec::new(); + assert_eq!(sorted_insert(&mut arr, 3, 2, cmp), None); + assert_eq!(arr, vec![3]); + } + + #[test] + fn test_add_if_not_full() { + let mut arr = vec![1, 5]; + assert_eq!(sorted_insert(&mut arr, 3, 3, cmp), None); + assert_eq!(arr, vec![1, 3, 5]); + } + + #[test] + fn test_add_if_will_not_be_full_after() { + let mut arr = vec![1]; + assert_eq!(sorted_insert(&mut arr, 0, 3, cmp), None); + assert_eq!(arr, vec![0, 1]); + } + + #[test] + fn test_return_add_if_sorts_after_last() { + let mut arr = vec![1, 2, 3]; + assert_eq!(sorted_insert(&mut arr, 4, 3, cmp), Some(4)); + assert_eq!(arr, vec![1, 2, 3]); + } + + #[test] + fn test_remove_from_end_if_full() { + let mut arr = vec![1, 3, 4]; + assert_eq!(sorted_insert(&mut arr, 2, 3, cmp), Some(4)); + assert_eq!(arr, vec![1, 2, 3]); + } + + #[test] + fn test_uses_comparator() { + let mut arr = vec![4, 2, 1]; + assert_eq!(sorted_insert(&mut arr, 3, 3, reverse_cmp), Some(1)); + assert_eq!(arr, vec![4, 3, 2]); + } + + #[test] + fn test_max_size_of_1_empty_add() { + let mut arr = Vec::new(); + assert_eq!(sorted_insert(&mut arr, 3, 1, cmp), None); + assert_eq!(arr, vec![3]); + } + + #[test] + fn test_max_size_of_1_full_add_greater() { + let mut arr = vec![2]; + assert_eq!(sorted_insert(&mut arr, 3, 1, cmp), Some(3)); + assert_eq!(arr, vec![2]); + } + + #[test] + fn test_max_size_of_1_full_add_lesser() { + let mut arr = vec![4]; + assert_eq!(sorted_insert(&mut arr, 3, 1, cmp), Some(4)); + assert_eq!(arr, vec![3]); + } +} From 9fe323867beb385b22c1871a002c609b81d63978 Mon Sep 17 00:00:00 2001 From: Shuhui Luo Date: Sat, 23 Dec 2023 23:54:52 -0800 Subject: [PATCH 8/8] test `sqrt` --- src/utils/sqrt.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/utils/sqrt.rs b/src/utils/sqrt.rs index 5c897ef..0fcfc9f 100644 --- a/src/utils/sqrt.rs +++ b/src/utils/sqrt.rs @@ -1,6 +1,14 @@ use num_bigint::{BigInt, ToBigInt}; use num_traits::{ToPrimitive, Zero}; +/// Computes floor(sqrt(value)) +/// +/// # Arguments +/// +/// * `value`: The value for which to compute the square root, rounded down +/// +/// returns: BigInt +/// fn sqrt(value: &BigInt) -> BigInt { assert!(*value >= Zero::zero(), "NEGATIVE"); @@ -25,3 +33,36 @@ fn sqrt(value: &BigInt) -> BigInt { z } + +#[cfg(test)] +mod tests { + use super::*; + use num_traits::Num; + + #[test] + fn test_sqrt_0_1000() { + for i in 0..1000 { + let sqrt_i = sqrt(&BigInt::from(i)); + assert_eq!(sqrt_i, BigInt::from((i as f64).sqrt().floor() as i64)); + } + } + + #[test] + fn test_sqrt_2_powers() { + for i in 0..256 { + let root = BigInt::from(2).pow(i as u32); + let root_squared = &root * &root; + assert_eq!(sqrt(&root_squared), root); + } + } + + #[test] + fn test_sqrt_max_uint256() { + let max_uint256_string = + "115792089237316195423570985008687907853269984665640564039457584007913129639935"; + let max_uint256 = BigInt::from_str_radix(max_uint256_string, 10).unwrap(); + let expected_sqrt = + BigInt::from_str_radix("340282366920938463463374607431768211455", 10).unwrap(); + assert_eq!(sqrt(&max_uint256), expected_sqrt); + } +}