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

refactor!: address mappings for conciseness #80

Merged
merged 6 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uniswap-sdk-core"
version = "2.1.0"
version = "2.2.0"
edition = "2021"
authors = ["malik <[email protected]>", "Shuhui Luo <twitter.com/aureliano_law>"]
description = "The Uniswap SDK Core in Rust provides essential functionality for interacting with the Uniswap decentralized exchange"
Expand Down
573 changes: 225 additions & 348 deletions src/addresses.rs

Large diffs are not rendered by default.

38 changes: 20 additions & 18 deletions src/chains.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(non_camel_case_types)]

/// Represents the unique identifier for different blockchain networks supported by the Uniswap SDK.
///
/// Each variant corresponds to a specific blockchain network, identified by its unique chain ID.
Expand All @@ -12,23 +14,23 @@ pub enum ChainId {
/// The Optimism network.
OPTIMISM = 10,
/// The Optimism Goerli Testnet.
OPTIMISMGOERLI = 420,
OPTIMISM_GOERLI = 420,
/// The Optimism Sepolia Testnet.
OPTIMISMSEPOLIA = 11155420,
OPTIMISM_SEPOLIA = 11155420,
/// The Arbitrum One network.
ARBITRUMONE = 42161,
ARBITRUM_ONE = 42161,
/// The Arbitrum Goerli Testnet.
ARBITRUMGOERLI = 421613,
ARBITRUM_GOERLI = 421613,
/// The Arbitrum Sepolia Testnet.
ARBITRUMSEPOLIA = 421614,
ARBITRUM_SEPOLIA = 421614,
/// The Polygon network.
POLYGON = 137,
/// The Polygon Mumbai Testnet.
POLYGONMUMBAI = 80001,
POLYGON_MUMBAI = 80001,
/// The Celo network.
CELO = 42220,
/// The Celo Alfajores Testnet.
CELOALFAJORES = 44787,
CELO_ALFAJORES = 44787,
/// The Gnosis network.
GNOSIS = 100,
/// The Moonbeam network.
Expand All @@ -38,13 +40,13 @@ pub enum ChainId {
/// The Avalanche network.
AVALANCHE = 43114,
/// The Base network.
BASEGOERLI = 84531,
BASE_GOERLI = 84531,
/// The Base Goerli Testnet.
BASE = 8453,
/// The Zora network.
ZORA = 7777777,
/// The Zora Sepolia Testnet.
ZORASEPOLIA = 999999999,
ZORA_SEPOLIA = 999999999,
/// The Rootstock network.
ROOTSTOCK = 30,
/// The Blast network.
Expand All @@ -58,23 +60,23 @@ pub enum ChainId {
pub const SUPPORTED_CHAINS: [ChainId; 21] = [
ChainId::MAINNET,
ChainId::OPTIMISM,
ChainId::OPTIMISMGOERLI,
ChainId::OPTIMISMSEPOLIA,
ChainId::ARBITRUMONE,
ChainId::ARBITRUMGOERLI,
ChainId::ARBITRUMSEPOLIA,
ChainId::OPTIMISM_GOERLI,
ChainId::OPTIMISM_SEPOLIA,
ChainId::ARBITRUM_ONE,
ChainId::ARBITRUM_GOERLI,
ChainId::ARBITRUM_SEPOLIA,
ChainId::POLYGON,
ChainId::POLYGONMUMBAI,
ChainId::POLYGON_MUMBAI,
ChainId::GOERLI,
ChainId::SEPOLIA,
ChainId::CELOALFAJORES,
ChainId::CELO_ALFAJORES,
ChainId::CELO,
ChainId::BNB,
ChainId::AVALANCHE,
ChainId::BASE,
ChainId::BASEGOERLI,
ChainId::BASE_GOERLI,
ChainId::ZORA,
ChainId::ZORASEPOLIA,
ChainId::ZORA_SEPOLIA,
ChainId::ROOTSTOCK,
ChainId::BLAST,
];
Expand Down
2 changes: 2 additions & 0 deletions src/entities/ether.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ impl Currency for Ether {
impl Ether {
/// Creates a new instance of [`Ether`] with the specified chain ID.
#[inline]
#[must_use]
pub fn new(chain_id: u64) -> Self {
Self {
chain_id,
Expand All @@ -44,6 +45,7 @@ impl Ether {

/// Retrieves or creates an [`Ether`] instance for the specified chain ID.
#[inline]
#[must_use]
pub fn on_chain(chain_id: u64) -> Self {
Self::new(chain_id)
}
Expand Down
2 changes: 1 addition & 1 deletion src/entities/fractions/currency_amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl<T: Currency> CurrencyAmount<T> {
denominator,
CurrencyMeta {
currency,
decimal_scale: BigUint::from(10u64).pow(exponent as u32),
decimal_scale: BigUint::from(10_u64).pow(exponent as u32),
},
))
}
Expand Down
4 changes: 1 addition & 3 deletions src/entities/fractions/fraction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,7 @@ impl<M: Clone> FractionBase<M> for FractionLike<M> {
fn new(numerator: impl Into<BigInt>, denominator: impl Into<BigInt>, meta: M) -> Self {
let denominator = denominator.into();
// Ensure the denominator is not zero
if denominator.is_zero() {
panic!("denominator is zero");
}
assert!(!denominator.is_zero(), "denominator is zero");
Self {
numerator: numerator.into(),
denominator,
Expand Down
1 change: 1 addition & 0 deletions src/entities/fractions/percent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl Percent {
/// Converts the [`Percent`] to a string with a fixed number of decimal places and rounding
/// strategy
#[inline]
#[must_use]
pub fn to_fixed(&self, decimal_places: u8, rounding: Rounding) -> String {
// Convert the Percent to a simple Fraction, multiply by 100, and then call to_fixed on the
// result
Expand Down
6 changes: 3 additions & 3 deletions src/entities/fractions/price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ where
Price::new(
self.quote_currency.clone(),
self.base_currency.clone(),
self.numerator().clone(),
self.denominator().clone(),
self.numerator.clone(),
self.denominator.clone(),
)
}

Expand Down Expand Up @@ -116,7 +116,7 @@ where
/// Get the value scaled by decimals for formatting
#[inline]
pub fn adjusted_for_decimals(&self) -> Fraction {
self.as_fraction() * self.scalar.clone()
self.as_fraction() * &self.scalar
}

/// Converts the adjusted price to a string with a specified number of significant digits and
Expand Down
2 changes: 2 additions & 0 deletions src/entities/native_currency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ use crate::prelude::*;

/// Represents the native currency of the chain on which it resides
pub trait NativeCurrency: Currency {
#[inline]
fn is_native(&self) -> bool {
true
}

#[inline]
fn is_token(&self) -> bool {
false
}
Expand Down
5 changes: 2 additions & 3 deletions src/entities/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ impl Token {
///
/// Panics if `chain_id` is 0.
#[inline]
#[must_use]
pub const fn new(
chain_id: u64,
address: Address,
Expand All @@ -69,9 +70,7 @@ impl Token {
buy_fee_bps: Option<BigUint>,
sell_fee_bps: Option<BigUint>,
) -> Self {
if chain_id == 0 {
panic!("chain id can't be zero");
}
assert!(chain_id != 0, "chain id can't be zero");
Self {
chain_id,
decimals,
Expand Down
34 changes: 20 additions & 14 deletions src/entities/weth9.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{prelude::*, token};
use alloc::vec;

/// Represents the WETH9 contract and provides information about WETH tokens on different Ethereum
/// chains.
Expand All @@ -11,6 +12,7 @@ pub struct WETH9 {
/// Default implementation for [`WETH9`], creating an instance with predefined WETH tokens on
/// various chains.
impl Default for WETH9 {
#[inline]
fn default() -> Self {
Self::new()
}
Expand All @@ -27,21 +29,23 @@ impl WETH9 {
///
/// A new `WETH9` instance with predefined WETH tokens.
#[inline]
#[must_use]
pub fn new() -> Self {
let mut tokens = FxHashMap::default();
tokens.insert(1, Self::on_chain(1).unwrap());
tokens.insert(3, Self::on_chain(3).unwrap());
tokens.insert(4, Self::on_chain(4).unwrap());
tokens.insert(5, Self::on_chain(5).unwrap());
tokens.insert(42, Self::on_chain(42).unwrap());
tokens.insert(10, Self::on_chain(10).unwrap());
tokens.insert(69, Self::on_chain(69).unwrap());
tokens.insert(42161, Self::on_chain(42161).unwrap());
tokens.insert(421611, Self::on_chain(421611).unwrap());
tokens.insert(8453, Self::on_chain(8453).unwrap());
tokens.insert(56, Self::on_chain(56).unwrap());
tokens.insert(137, Self::on_chain(137).unwrap());
tokens.insert(43114, Self::on_chain(43114).unwrap());
let tokens = FxHashMap::from_iter(vec![
(1, Self::on_chain(1).unwrap()),
(3, Self::on_chain(3).unwrap()),
(4, Self::on_chain(4).unwrap()),
(5, Self::on_chain(5).unwrap()),
(42, Self::on_chain(42).unwrap()),
(10, Self::on_chain(10).unwrap()),
(69, Self::on_chain(69).unwrap()),
(42161, Self::on_chain(42161).unwrap()),
(421611, Self::on_chain(421611).unwrap()),
(8453, Self::on_chain(8453).unwrap()),
(56, Self::on_chain(56).unwrap()),
(137, Self::on_chain(137).unwrap()),
(43114, Self::on_chain(43114).unwrap()),
]);
malik672 marked this conversation as resolved.
Show resolved Hide resolved
Self { tokens }
}

Expand All @@ -53,6 +57,7 @@ impl WETH9 {
///
/// Returns: `Some(Token)` if the token exists, `None` otherwise.
#[inline]
#[must_use]
pub fn on_chain(chain_id: u64) -> Option<Token> {
match chain_id {
1 => Some(token!(
Expand Down Expand Up @@ -158,6 +163,7 @@ impl WETH9 {
///
/// Returns: `Some(Token)` if the token exists, `None` otherwise.
#[inline]
#[must_use]
pub fn get(&self, chain_id: u64) -> Option<&Token> {
self.tokens.get(&chain_id)
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,25 @@
//!
//! The Uniswap SDK Core in Rust provides essential functionality for interacting with the Uniswap
//! decentralized exchange.

#![cfg_attr(not(any(feature = "std", test)), no_std)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
unreachable_pub,
clippy::missing_const_for_fn,
clippy::missing_inline_in_public_items,
clippy::needless_pass_by_value,
clippy::redundant_clone,
clippy::manual_assert,
clippy::must_use_candidate,
clippy::unseparated_literal_suffix,
rustdoc::all
)]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![deny(unused_must_use, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]

extern crate alloc;

/// Contains functionality related to All Contracts deployed and supported by the Uniswap SDK.
Expand Down
12 changes: 6 additions & 6 deletions src/utils/compute_price_impact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::prelude::*;
/// returns: Percent
#[inline]
pub fn compute_price_impact<TBase: Currency, TQuote: Currency>(
mid_price: Price<TBase, TQuote>,
mid_price: &Price<TBase, TQuote>,
input_amount: &CurrencyAmount<TBase>,
output_amount: &CurrencyAmount<TQuote>,
) -> Result<Percent, Error> {
Expand Down Expand Up @@ -42,7 +42,7 @@ mod tests {
//is correct for zero
assert!(
compute_price_impact(
Price::new(Ether::on_chain(1), token.clone(), 10, 100),
&Price::new(Ether::on_chain(1), token.clone(), 10, 100),
&CurrencyAmount::from_raw_amount(Ether::on_chain(1), 10).unwrap(),
&CurrencyAmount::from_raw_amount(token.clone(), 100).unwrap()
)
Expand All @@ -53,7 +53,7 @@ mod tests {
//is correct for half output
assert!(
compute_price_impact(
Price::new(token.clone(), token_1.clone(), 10, 100),
&Price::new(token.clone(), token_1.clone(), 10, 100),
&CurrencyAmount::from_raw_amount(token.clone(), 10).unwrap(),
&CurrencyAmount::from_raw_amount(token_1.clone(), 50).unwrap()
)
Expand All @@ -64,9 +64,9 @@ mod tests {
//is negative for more output
assert_eq!(
compute_price_impact(
Price::new(token.clone(), token_1.clone(), 10, 100),
&CurrencyAmount::from_raw_amount(token.clone(), 10).unwrap(),
&CurrencyAmount::from_raw_amount(token_1.clone(), 200).unwrap()
&Price::new(token.clone(), token_1.clone(), 10, 100),
&CurrencyAmount::from_raw_amount(token, 10).unwrap(),
&CurrencyAmount::from_raw_amount(token_1, 200).unwrap()
)
.unwrap(),
Percent::new(-10000, 10000)
Expand Down
1 change: 1 addition & 0 deletions src/utils/sorted_insert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::prelude::*;

/// 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
#[inline]
pub fn sorted_insert<T: Clone>(
items: &mut Vec<T>,
add: T,
Expand Down
1 change: 1 addition & 0 deletions src/utils/sqrt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use num_traits::Signed;
/// * `value`: the value for which to compute the square root, rounded down
///
/// returns: BigInt
#[inline]
pub fn sqrt(value: &BigInt) -> Result<BigInt, Error> {
if value.is_negative() {
Err(Error::Invalid)
Expand Down
2 changes: 2 additions & 0 deletions src/utils/validate_and_parse_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use regex::Regex;
/// with only hexadecimal characters after `0x`, returns `Ok(ethereum_address.to_string())`.
/// * Otherwise, returns an error message in the form of `Err(format!("{} is not a valid Ethereum
/// address.", ethereum_address))`.
#[inline]
pub fn check_valid_ethereum_address(ethereum_address: &str) -> Result<&str, String> {
let valid_address_regex = Regex::new(r"^0x[0-9a-fA-F]{40}$").unwrap();
if valid_address_regex.is_match(ethereum_address) {
Expand All @@ -37,6 +38,7 @@ pub fn check_valid_ethereum_address(ethereum_address: &str) -> Result<&str, Stri
/// with only hexadecimal characters after `0x`, returns the checksummed address.
/// * Otherwise, returns an error message in the form of `Err(format!("{} is not a valid Ethereum
/// address.", ethereum_address))`.
#[inline]
pub fn validate_and_parse_address(ethereum_address: &str) -> Result<String, String> {
let checksummed_address = eth_checksum::checksum(ethereum_address);
check_valid_ethereum_address(&checksummed_address)?;
Expand Down