Skip to content

Commit

Permalink
refactor: Refactor currency representation and correct minor comment …
Browse files Browse the repository at this point in the history
…typos

Restructured the handling of currencies in the system by consolidating all currency-related functionalities under the `Currency` trait. Eliminated the `CurrencyTrait` and the `Currency` enum, which were previously holding this responsibility across multiple code portions. Also corrected several minor errors in the comments and improved the comment descriptions across multiple files.
  • Loading branch information
shuhuiluo committed Jul 10, 2024
1 parent 6401616 commit aa19902
Show file tree
Hide file tree
Showing 15 changed files with 34 additions and 112 deletions.
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 = "0.26.0"
version = "1.0.0-rc"
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
2 changes: 1 addition & 1 deletion src/addresses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type AddressMap = FxHashMap<u64, Address>;
type ChainMap = FxHashMap<u64, ChainAddresses>;
type ChainAddress = FxHashMap<u64, Address>;

/// Represents the addresses of various core contracts of uniswap on a network.
/// Represents the addresses of various core contracts of Uniswap on a network.
#[derive(Clone, Copy, Debug)]
pub struct ChainAddresses {
v3_core_factory_address: Address,
Expand Down
6 changes: 3 additions & 3 deletions src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::prelude::*;
use alloy_primitives::U256;
use num_bigint::Sign;

/// Represents the various type of trades.
/// Represents the various types of trades.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TradeType {
/// Indicates that the trade is based on an exact input amount.
Expand All @@ -12,7 +12,7 @@ pub enum TradeType {
ExactOutput,
}

/// Represents three various way to rounds
/// Represents three various ways to round
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rounding {
/// Rounds down to the nearest whole number.
Expand All @@ -26,7 +26,7 @@ pub enum Rounding {
}

lazy_static! {
///Represnts Maximum amount contained in a uint256
/// Represents the maximum amount contained in a uint256
pub static ref MAX_UINT256: BigInt =
BigInt::from_bytes_be(Sign::Plus, &U256::MAX.to_be_bytes::<32>());
}
2 changes: 1 addition & 1 deletion src/entities/base_currency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct CurrencyLike<M> {
/// The chain ID on which this currency resides
pub chain_id: ChainId,

/// represents the deciamls for the prticular currency
/// The decimals for the particular currency
pub decimals: u8,

/// The symbol of the currency, i.e. a short textual non-unique identifier
Expand Down
75 changes: 3 additions & 72 deletions src/entities/currency.rs
Original file line number Diff line number Diff line change
@@ -1,89 +1,20 @@
use crate::prelude::*;

/// This enum represnets the two type of currencies i.e native and Token
#[derive(Clone, PartialEq, Debug)]
pub enum Currency {
/// Represents a native currency.
NativeCurrency(Ether),
/// Represents a token.
Token(Token),
}

/// Trait for representing a currency in the Uniswap Core SDK.
pub trait CurrencyTrait: BaseCurrency {
pub trait Currency: BaseCurrency {
/// Returns whether the currency is native to the chain and must be wrapped (e.g. Ether)
fn is_native(&self) -> bool;

/// Returns the address of the currency.
fn address(&self) -> Address;

/// Returns whether this currency is functionally equivalent to the other currency
fn equals(&self, other: &impl CurrencyTrait) -> bool;
fn equals(&self, other: &impl Currency) -> bool;

/// Returns a Token that represents the wrapped quivalent of the mative currency
/// Returns a Token that represents the wrapped equivalent of the native currency
fn wrapped(&self) -> Token;
}

impl CurrencyTrait for Currency {
fn is_native(&self) -> bool {
match self {
Currency::NativeCurrency(_) => true,
Currency::Token(_) => false,
}
}

fn address(&self) -> Address {
match self {
Currency::NativeCurrency(native_currency) => native_currency.address(),
Currency::Token(token) => token.address(),
}
}

fn equals(&self, other: &impl CurrencyTrait) -> bool {
match self {
Currency::NativeCurrency(native_currency) => native_currency.equals(other),
Currency::Token(token) => token.equals(other),
}
}

fn wrapped(&self) -> Token {
match self {
Currency::NativeCurrency(native_currency) => native_currency.wrapped(),
Currency::Token(token) => token.clone(),
}
}
}

impl BaseCurrency for Currency {
fn chain_id(&self) -> u64 {
match self {
Currency::NativeCurrency(native_currency) => native_currency.chain_id(),
Currency::Token(token) => token.chain_id(),
}
}

fn decimals(&self) -> u8 {
match self {
Currency::NativeCurrency(native_currency) => native_currency.decimals(),
Currency::Token(token) => token.decimals(),
}
}

fn symbol(&self) -> Option<String> {
match self {
Currency::NativeCurrency(native_currency) => native_currency.symbol(),
Currency::Token(token) => token.symbol(),
}
}

fn name(&self) -> Option<String> {
match self {
Currency::NativeCurrency(native_currency) => native_currency.name(),
Currency::Token(token) => token.name(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
8 changes: 4 additions & 4 deletions src/entities/ether.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::prelude::*;
/// Represents the native currency of the blockchain.
pub type Ether = CurrencyLike<()>;

impl CurrencyTrait for Ether {
impl Currency for Ether {
/// Checks if the currency is native to the blockchain.
fn is_native(&self) -> bool {
true
Expand All @@ -16,7 +16,7 @@ impl CurrencyTrait for Ether {
}

/// Checks if the currency is equal to another currency.
fn equals(&self, other: &impl CurrencyTrait) -> bool {
fn equals(&self, other: &impl Currency) -> bool {
match other.is_native() {
true => self.chain_id() == other.chain_id(),
_ => false,
Expand Down Expand Up @@ -66,11 +66,11 @@ mod tests {

#[test]
fn test_equals_returns_false_for_different_chains() {
assert!(!Ether::on_chain(1).equals(&Currency::NativeCurrency(Ether::on_chain(2))));
assert!(!Ether::on_chain(1).equals(&Ether::on_chain(2)));
}

#[test]
fn test_equals_returns_true_for_same_chains() {
assert!(Ether::on_chain(1).equals(&Currency::NativeCurrency(Ether::on_chain(1))));
assert!(Ether::on_chain(1).equals(&Ether::on_chain(1)));
}
}
13 changes: 6 additions & 7 deletions src/entities/fractions/currency_amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ pub type CurrencyAmount<T> = FractionLike<CurrencyMeta<T>>;

/// Struct representing metadata about a currency
#[derive(Clone, Debug, PartialEq)]
pub struct CurrencyMeta<T: CurrencyTrait> {
pub struct CurrencyMeta<T: Currency> {
/// The currency associated with this metadata
pub currency: T,
/// The scale factor for the currency's decimal places
pub decimal_scale: BigUint,
}

impl<T: CurrencyTrait> CurrencyAmount<T> {
impl<T: Currency> CurrencyAmount<T> {
/// Constructor method for creating a new currency amount
fn new(
currency: T,
Expand Down Expand Up @@ -151,8 +151,8 @@ mod tests {

// Lazy static variables for testing currencies
lazy_static! {
static ref TOKEN18: Currency = Currency::Token(token!(1, ADDRESS_ONE, 18));
static ref TOKEN0: Currency = Currency::Token(token!(1, ADDRESS_ONE, 0));
static ref TOKEN18: Token = token!(1, ADDRESS_ONE, 18);
static ref TOKEN0: Token = token!(1, ADDRESS_ONE, 0);
}

// Unit tests
Expand All @@ -174,10 +174,9 @@ mod tests {
#[test]
fn test_ether() {
let ether = Ether::on_chain(1);
let amount =
CurrencyAmount::from_raw_amount(Currency::NativeCurrency(ether.clone()), 100).unwrap();
let amount = CurrencyAmount::from_raw_amount(ether.clone(), 100).unwrap();
assert_eq!(amount.quotient(), 100.into());
assert!(amount.currency.equals(&Currency::NativeCurrency(ether)));
assert!(amount.currency.equals(&ether));
}

#[test]
Expand Down
1 change: 0 additions & 1 deletion src/entities/fractions/fraction.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/// External crate dependencies
use crate::prelude::*;
use core::ops::{Add, Deref, Mul, Sub};

Expand Down
2 changes: 1 addition & 1 deletion src/entities/fractions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ pub mod currency_amount;
pub mod fraction;
/// A module represents a percentage.
pub mod percent;
/// A module represents' a price as a ratio between two currencies, with methods for arithmetic and
/// A module represents a price as a ratio between two currencies, with methods for arithmetic and
/// string conversions.
pub mod price;
1 change: 0 additions & 1 deletion src/entities/fractions/percent.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/// Importing dependencies from the same module
use crate::prelude::*;

lazy_static! {
Expand Down
16 changes: 8 additions & 8 deletions src/entities/fractions/price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ pub type Price<TBase, TQuote> = FractionLike<PriceMeta<TBase, TQuote>>;
#[derive(Clone, Debug, PartialEq)]
pub struct PriceMeta<TBase, TQuote>
where
TBase: CurrencyTrait,
TQuote: CurrencyTrait,
TBase: Currency,
TQuote: Currency,
{
/// The base currency for the price
pub base_currency: TBase,
Expand All @@ -23,8 +23,8 @@ where

impl<TBase, TQuote> Price<TBase, TQuote>
where
TBase: CurrencyTrait,
TQuote: CurrencyTrait,
TBase: Currency,
TQuote: Currency,
{
/// Constructor for creating a new [`Price`] instance
pub fn new(
Expand Down Expand Up @@ -75,7 +75,7 @@ where

/// Multiply the price by another price, returning a new price.
/// The other price must have the same base currency as this price's quote currency.
pub fn multiply<TOtherQuote: CurrencyTrait>(
pub fn multiply<TOtherQuote: Currency>(
&self,
other: &Price<TQuote, TOtherQuote>,
) -> Result<Price<TBase, TOtherQuote>, Error> {
Expand Down Expand Up @@ -141,9 +141,9 @@ mod test {
const ADDRESS_ONE: &str = "0x0000000000000000000000000000000000000001";

lazy_static! {
static ref TOKEN0: Currency = Currency::Token(token!(1, ADDRESS_ZERO, 18));
static ref TOKEN0_6: Currency = Currency::Token(token!(1, ADDRESS_ZERO, 6));
static ref TOKEN1: Currency = Currency::Token(token!(1, ADDRESS_ONE, 18));
static ref TOKEN0: Token = token!(1, ADDRESS_ZERO, 18);
static ref TOKEN0_6: Token = token!(1, ADDRESS_ZERO, 6);
static ref TOKEN1: Token = token!(1, ADDRESS_ONE, 18);
}

#[test]
Expand Down
6 changes: 0 additions & 6 deletions src/entities/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
/// Module represnting base currency
pub mod base_currency;
/// Module representing currency
pub mod currency;
/// Module representing ether
pub mod ether;
/// Module represnting fractions
pub mod fractions;
/// Module represnting token
pub mod token;
/// Module representing Weth9
pub mod weth9;
8 changes: 4 additions & 4 deletions src/entities/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct TokenMeta {
pub sell_fee_bps: Option<BigUint>,
}

impl CurrencyTrait for Token {
impl Currency for Token {
fn is_native(&self) -> bool {
false
}
Expand All @@ -27,10 +27,10 @@ impl CurrencyTrait for Token {
///
/// # Arguments
///
/// * `other`: other token to compare
/// * `other`: another token to compare
///
/// returns: bool
fn equals(&self, other: &impl CurrencyTrait) -> bool {
fn equals(&self, other: &impl Currency) -> bool {
match other.is_native() {
false => self.chain_id == other.chain_id() && self.address() == other.address(),
_ => false,
Expand Down Expand Up @@ -93,7 +93,7 @@ impl Token {
///
/// # Arguments
///
/// * `other`: other token to compare
/// * `other`: another token to compare
pub fn sorts_before(&self, other: &Token) -> Result<bool, Error> {
if self.chain_id != other.chain_id {
return Err(Error::ChainIdMismatch(self.chain_id, other.chain_id));
Expand Down
2 changes: 1 addition & 1 deletion src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ pub use crate::{
constants::*,
entities::{
base_currency::{BaseCurrency, CurrencyLike},
currency::{Currency, CurrencyTrait},
currency::Currency,
ether::Ether,
fractions::{
currency_amount::CurrencyAmount,
Expand Down
2 changes: 1 addition & 1 deletion src/utils/compute_price_impact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::prelude::*;
/// * `outputAmount`: the output amount of the trade
///
/// returns: Percent
pub fn compute_price_impact<TBase: CurrencyTrait, TQuote: CurrencyTrait>(
pub fn compute_price_impact<TBase: Currency, TQuote: Currency>(
mid_price: Price<TBase, TQuote>,
input_amount: CurrencyAmount<TBase>,
output_amount: CurrencyAmount<TQuote>,
Expand Down

0 comments on commit aa19902

Please sign in to comment.