From 6c050a041ef4d5aaf13708a85d9ff2e8fcc9b497 Mon Sep 17 00:00:00 2001 From: malik Date: Sun, 28 Apr 2024 09:10:13 +0100 Subject: [PATCH] chore(doc): Add comments and derive attributes (#60) * fix big-decimal issue * fix big-decimal issue * docs and example * changes * changes * change hash table * change hash table * changes to doc * fixed documentations and refactored some documentations * fixed documentations and refactored some documentations * fixed documentations and refactored some documentations * fixed documentations and refactored some documentations * fixed documentations and refactored some documentations * Update src/addresses.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/chains.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/error.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/utils/mod.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/token.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/token.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/constants.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/chains.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update addresses.rs * Update error.rs * Update src/entities/token.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/constants.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/base_currency.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/fractions/fraction.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/fractions/fraction.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/fractions/fraction.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/entities/currency.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> * Update src/error.rs Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> --------- Co-authored-by: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> --- Cargo.toml | 2 - README.md | 2 +- src/addresses.rs | 64 ++++++++++++++++++++++- src/chains.rs | 41 ++++++++++++++- src/constants.rs | 15 +++++- src/entities/base_currency.rs | 11 ++++ src/entities/currency.rs | 14 +++-- src/entities/ether.rs | 2 +- src/entities/fractions/currency_amount.rs | 8 ++- src/entities/fractions/fraction.rs | 20 +++++-- src/entities/fractions/mod.rs | 5 ++ src/entities/fractions/percent.rs | 3 +- src/entities/fractions/price.rs | 6 ++- src/entities/mod.rs | 6 +++ src/entities/token.rs | 23 ++++++++ src/entities/weth9.rs | 9 ++++ src/error.rs | 12 ++--- src/examples/mod.rs | 2 + src/examples/token_example.rs | 28 ++++++++++ src/lib.rs | 27 ++++++++++ 20 files changed, 268 insertions(+), 32 deletions(-) create mode 100644 src/examples/mod.rs create mode 100644 src/examples/token_example.rs diff --git a/Cargo.toml b/Cargo.toml index a6547fc..153b809 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,8 @@ eth_checksum = { version = "0.1.2", optional = true } lazy_static = "1.4" num-bigint = "0.4.4" num-integer = "0.1.45" -num-rational = "0.4.1" num-traits = "0.2.17" regex = { version = "1.10", optional = true } -syn = "2.0" thiserror = "1.0" [features] diff --git a/README.md b/README.md index 4c24db1..c7f65a6 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Add this to your Cargo.toml ``` [dependencies] -uniswap-sdk-core = "0.20.0"; +uniswap-sdk-core = "0.22.0"; ``` And this to your code: diff --git a/src/addresses.rs b/src/addresses.rs index a8b02f8..9d1bc78 100644 --- a/src/addresses.rs +++ b/src/addresses.rs @@ -4,7 +4,8 @@ type AddressMap = HashMap; type ChainMap = HashMap; type ChainAddress = HashMap; -#[derive(Clone, Copy)] +/// Represents the addresses of various core contracts of uniswap on a network. +#[derive(Clone, Copy, Debug)] pub struct ChainAddresses { v3_core_factory_address: Address, multicall_address: Address, @@ -16,6 +17,7 @@ pub struct ChainAddresses { v1_mixed_route_quoter_address: Option
, } +/// Represents default networks which are Mainnet, Goerli, Sepolia pub const DEFAULT_NETWORKS: [ChainId; 3] = [ChainId::MAINNET, ChainId::GOERLI, ChainId::SEPOLIA]; /// returns a hashmap of key pair input of chainid to address @@ -38,6 +40,7 @@ pub fn construct_same_address_map(address: Address, additional_networks: &[Chain } lazy_static! { + /// The UNI_ADDRESSES struct holds a map of addresses for the UNI token on various networks. #[derive(Debug, Clone, Copy)] pub static ref UNI_ADDRESSES: AddressMap = construct_same_address_map( address!("1f9840a85d5aF5bf1D1762F925BDADdC4201F984"), @@ -51,12 +54,15 @@ lazy_static! { ); } +/// The address for the Uniswap NFT airdrop claim contract. pub const UNISWAP_NFT_AIRDROP_CLAIM_ADDRESS: Address = address!("8B799381ac40b838BBA4131ffB26197C432AFe78"); +/// The address for the Uniswap V2 Factory Address claim contract. pub const V2_FACTORY_ADDRESS: Address = address!("5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f"); lazy_static! { + /// A map of Uniswap V2 Factory addresses for various networks. pub static ref V2_FACTORY_ADDRESSES: HashMap = { let mut m = HashMap::new(); m.insert(ChainId::MAINNET as u64, V2_FACTORY_ADDRESS); @@ -97,9 +103,15 @@ lazy_static! { }; } +/// This represents V2 router address across all chains pub const V2_ROUTER_ADDRESS: Address = address!("7a250d5630B4cF539739dF2C5dAcb4c659F2488D"); lazy_static! { + /// A map of Uniswap V2 Router addresses for various networks. + /// + /// This map is used to look up the address of the Uniswap V2 Router contract + /// for a given network. The keys in the map are the network IDs, and the values + /// are the corresponding contract addresses. pub static ref V2_ROUTER_ADDRESSES: HashMap = { let mut m = HashMap::new(); m.insert(ChainId::MAINNET as u64, V2_ROUTER_ADDRESS); @@ -134,7 +146,6 @@ lazy_static! { impl Default for ChainAddresses { /// Networks that share most of the same addresses i.e. Mainnet, Goerli, Optimism, Arbitrum, - /// Polygon fn default() -> Self { Self { v3_core_factory_address: address!("1F98431c8aD98523631AE4a59f267346ea31F984"), @@ -152,6 +163,7 @@ impl Default for ChainAddresses { } lazy_static! { + /// The `MAINNET_ADDRESSES` struct holds the Uniswap contract addresses for the Ethereum Mainnet. pub static ref MAINNET_ADDRESSES: ChainAddresses = { ChainAddresses { v1_mixed_route_quoter_address: Some(address!( @@ -163,6 +175,7 @@ lazy_static! { } lazy_static! { + /// The `GOERLI_ADDRESSES` struct holds the Uniswap contract addresses for the Goerli Testnet. pub static ref GOERLI_ADDRESSES: ChainAddresses = { ChainAddresses { v1_mixed_route_quoter_address: Some(address!( @@ -174,10 +187,12 @@ lazy_static! { } lazy_static! { + /// The `OPTIMISM_ADDRESSES` struct holds the Uniswap contract addresses for the Optimism network. pub static ref OPTIMISM_ADDRESSES: ChainAddresses = ChainAddresses::default(); } lazy_static! { + /// The `ARBITRUM_ONE_ADDRESSES` struct holds the Uniswap contract addresses for the Arbitrum One network. pub static ref ARBITUM_ONE_ADDRESSES: ChainAddresses = { ChainAddresses { multicall_address: address!("adF885960B47eA2CD9B55E6DAc6B42b7Cb2806dB"), @@ -187,6 +202,7 @@ lazy_static! { }; } lazy_static! { + /// The `POLYGON_ADDRESSES` struct holds the Uniswap contract addresses for the Polygon network. pub static ref POLYGON_ADDRESSES: ChainAddresses = ChainAddresses::default(); } @@ -373,6 +389,11 @@ pub const ROOTSTOCK_ADDRESSES: ChainAddresses = ChainAddresses { }; lazy_static! { + /// A map of chain IDs to their corresponding Uniswap contract addresses. + /// + /// This map is used to look up the addresses of various Uniswap contracts + /// for a given network. The keys in the map are the network IDs, and the values + /// are the corresponding contract addresses. pub static ref CHAIN_TO_ADDRESSES_MAP: ChainMap = { let mut new_map = ChainMap::new(); new_map.insert(ChainId::BNB as u64, BNB_ADDRESSES); @@ -485,11 +506,13 @@ pub static ref GOVERNANCE_BRAVO_ADDRESSES: AddressMap = { } lazy_static! { + /// The `TIMELOCK_ADDRESSES` struct holds the timelock contract addresses for various networks. pub static ref TIMELOCK_ADDRESSES: AddressMap = construct_same_address_map(address!("1a9C8182C09F50C8318d769245beA52c32BE35BC"), &[]); } lazy_static! { + /// The `MERKLE_DISTRIBUTOR_ADDRESS` struct holds the merkle distributor contract address for the mainnet. pub static ref MERKLE_DISTRIBUTOR_ADDRESS: AddressMap = { let mut new_map = AddressMap::new(); new_map.insert( @@ -501,6 +524,7 @@ lazy_static! { } lazy_static! { + /// The `ARGENT_WALLET_DETECTOR_ADDRESS` struct holds the Argent Wallet Detector contract address for the mainnet. pub static ref ARGENT_WALLET_DETECTOR_ADDRESS: AddressMap = { let mut new_map = AddressMap::new(); new_map.insert( @@ -512,6 +536,10 @@ lazy_static! { } lazy_static! { + /// The `QUOTER_ADDRESSES` struct holds the quoter contract addresses for various networks. + /// + /// This includes the addresses for the quoter contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network pub static ref QUOTER_ADDRESSES: ChainAddress = { let mut chain_add = ChainAddress::new(); for chain_id in SUPPORTED_CHAINS { @@ -528,6 +556,10 @@ lazy_static! { } lazy_static! { + /// The `NONFUNGIBLE_POSITION_MANAGER_ADDRESSES` struct holds the non-fungible position manager contract addresses for various networks. + /// + /// This includes the addresses for the non-fungible position manager contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network. pub static ref NONFUNGIBLE_POSITION_MANAGER_ADDRESSES: ChainAddress = { let mut chain_add = ChainAddress::new(); for chain_id in SUPPORTED_CHAINS { @@ -552,11 +584,19 @@ lazy_static! { } lazy_static! { + /// The `ENS_REGISTRAR_ADDRESSES` struct holds the ENS Registrar contract addresses for various networks. + /// + /// This includes the addresses for the ENS Registrar contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network. pub static ref ENS_REGISTRAR_ADDRESSES: AddressMap = construct_same_address_map(address!("00000000000C2E074eC69A0dFb2997BA6C7d2e1e"), &[]); } lazy_static! { + /// The `SOCKS_CONTROLLER_ADDRESSES` struct holds the SOCKS Controller contract addresses for various networks. + /// + /// This includes the addresses for the SOCKS Controller contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network. pub static ref SOCKS_CONTROLLER_ADDRESSES: AddressMap = { let mut new_map = AddressMap::new(); new_map.insert( @@ -568,6 +608,10 @@ lazy_static! { } lazy_static! { + /// The `TICK_LENS_ADDRESSES` struct holds the tick lens contract addresses for various networks. + /// + /// This includes the addresses for the tick lens contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network. pub static ref TICK_LENS_ADDRESSES: ChainAddress = { let mut chain_add = ChainAddress::new(); for chain_id in SUPPORTED_CHAINS { @@ -592,6 +636,10 @@ lazy_static! { } lazy_static! { + /// The `MIXED_ROUTE_QUOTER_V1_ADDRESSES` struct holds the mixed route quoter contract addresses for various networks. + /// + /// This includes the addresses for the mixed route quoter contract on different networks. + /// Each field in the struct corresponds to a specific contract and its address on the network. pub static ref MIXED_ROUTE_QUOTER_V1_ADDRESSES: ChainAddress = { let mut chain_add = ChainAddress::new(); for chain_id in SUPPORTED_CHAINS { @@ -615,6 +663,18 @@ lazy_static! { }; } +/// Returns the address of the Uniswap V2 Router contract for the specified chain. +/// +/// If the chain ID is not found in the `CHAIN_TO_ADDRESSES_MAP`, it defaults to the +/// address of the router contract on the Ethereum mainnet. +/// +/// # Arguments +/// +/// * `chain_id` - The ID of the chain for which to retrieve the router address. +/// +/// # Returns +/// +/// * `Address` - The address of the Uniswap V2 Router contract for the specified chain. pub fn swap_router02_address(chain_id: u64) -> Address { if CHAIN_TO_ADDRESSES_MAP.contains_key(&chain_id) && CHAIN_TO_ADDRESSES_MAP diff --git a/src/chains.rs b/src/chains.rs index 2d177df..f08eb85 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -1,29 +1,58 @@ -#[derive(Debug, Clone, Copy)] +/// 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. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ChainId { + /// The Ethereum Mainnet. MAINNET = 1, + /// The Goerli Testnet. GOERLI = 5, + /// The Sepolia Testnet. SEPOLIA = 11155111, + /// The Optimism network. OPTIMISM = 10, + /// The Optimism Goerli Testnet. OPTIMISMGOERLI = 420, + /// The Optimism Sepolia Testnet. OPTIMISMSEPOLIA = 11155420, + /// The Arbitrum One network. ARBITRUMONE = 42161, + /// The Arbitrum Goerli Testnet. ARBITRUMGOERLI = 421613, + /// The Arbitrum Sepolia Testnet. ARBITRUMSEPOLIA = 421614, + /// The Polygon network. POLYGON = 137, + /// The Polygon Mumbai Testnet. POLYGONMUMBAI = 80001, + /// The Celo network. CELO = 42220, + /// The Celo Alfajores Testnet. CELOALFAJORES = 44787, + /// The Gnosis network. GNOSIS = 100, + /// The Moonbeam network. MOONBEAM = 1284, + /// The Binance Smart Chain (BSC). BNB = 56, + /// The Avalanche network. AVALANCHE = 43114, + /// The Base network. BASEGOERLI = 84531, + /// The Base Goerli Testnet. BASE = 8453, + /// The Zora network. ZORA = 7777777, + /// The Zora Sepolia Testnet. ZORASEPOLIA = 999999999, + /// The Rootstock network. ROOTSTOCK = 30, } +/// A list of `ChainId` constants representing the blockchain networks supported by the Uniswap SDK. +/// +/// This array includes all the `ChainId` variants that are supported by the SDK, making it easy to +/// iterate over or check for supported chains. pub const SUPPORTED_CHAINS: [ChainId; 20] = [ ChainId::MAINNET, ChainId::OPTIMISM, @@ -47,13 +76,23 @@ pub const SUPPORTED_CHAINS: [ChainId; 20] = [ ChainId::ROOTSTOCK, ]; +/// Represents the names of native currencies supported by the Uniswap SDK. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NativeCurrencyName { + /// Ethereum's native currency. ETHER, + /// Polygon's native currency. MATIC, + /// Celo's native currency. CELO, + /// Gnosis's native currency. GNOSIS, + /// Moonbeam's native currency. MOONBEAM, + /// Binance Smart Chain's native currency. BNB, + /// Avalanche's native currency. AVAX, + /// Rootstock's native currency. ROOTSTOCK, } diff --git a/src/constants.rs b/src/constants.rs index d2fc50e..2e7cbbc 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -2,20 +2,31 @@ use crate::prelude::*; use alloy_primitives::U256; use num_bigint::Sign; -#[derive(Clone, Copy, Debug, PartialEq)] +/// Represents the various type of trades. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TradeType { + /// Indicates that the trade is based on an exact input amount. ExactInput, + + /// Indicates that the trade is based on an exact output amount. ExactOutput, } -#[derive(Clone, Debug, PartialEq)] +/// Represents three various way to rounds +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Rounding { + /// Rounds down to the nearest whole number. RoundDown, + + /// Rounds to the nearest whole number, rounding halfway cases away from zero. RoundHalfUp, + + /// Rounds up to the nearest whole number. RoundUp, } lazy_static! { + ///Represnts Maximum amount contained in a uint256 pub static ref MAX_UINT256: BigInt = BigInt::from_bytes_be(Sign::Plus, &U256::MAX.to_be_bytes::<32>()); } diff --git a/src/entities/base_currency.rs b/src/entities/base_currency.rs index 4a43e65..ca89a3e 100644 --- a/src/entities/base_currency.rs +++ b/src/entities/base_currency.rs @@ -2,12 +2,23 @@ use std::ops::Deref; use alloy_primitives::ChainId; +/// `CurrencyLike` is a generic struct representing a currency with a specific chain ID, +/// decimals, symbol, name, and additional metadata. #[derive(Clone, PartialEq, Debug)] pub struct CurrencyLike { + /// The chain ID on which this currency resides pub chain_id: ChainId, + + /// represents the deciamls for the prticular currency pub decimals: u8, + + /// The symbol of the currency, i.e. a short textual non-unique identifier pub symbol: Option, + + /// The name of the currency, i.e. a descriptive textual non-unique identifier pub name: Option, + + /// Metadata associated with the currency pub meta: M, } diff --git a/src/entities/currency.rs b/src/entities/currency.rs index 833b878..7758941 100644 --- a/src/entities/currency.rs +++ b/src/entities/currency.rs @@ -1,31 +1,30 @@ 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 { /// 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 - /// - /// # Arguments - /// - /// * `other`: the other currency fn equals(&self, other: &impl CurrencyTrait) -> bool; - /// Return the wrapped version of this currency that can be used with the Uniswap contracts. - /// Currencies must implement this to be used in Uniswap + /// Returns a Token that represents the wrapped quivalent of the mative currency fn wrapped(&self) -> Token; } impl CurrencyTrait for Currency { - /// Returns a bool indicating whether the currency is native or not fn is_native(&self) -> bool { match self { Currency::NativeCurrency(_) => true, @@ -33,7 +32,6 @@ impl CurrencyTrait for Currency { } } - /// Accessor method for retrieving either the NativeCurrency or Token address fn address(&self) -> Address { match self { Currency::NativeCurrency(native_currency) => native_currency.address(), diff --git a/src/entities/ether.rs b/src/entities/ether.rs index 1a1578e..e50029d 100644 --- a/src/entities/ether.rs +++ b/src/entities/ether.rs @@ -2,7 +2,7 @@ use crate::prelude::*; // Lazy static cache for Ether instances lazy_static! { - static ref ETHER_CACHE: Mutex> = Mutex::new(HashMap::new()); + static ref ETHER_CACHE: Mutex> = Mutex::new(HashMap::default()); } /// Ether is the main usage of a 'native' currency, i.e., for Ethereum mainnet and all testnets. diff --git a/src/entities/fractions/currency_amount.rs b/src/entities/fractions/currency_amount.rs index ba79729..0bd7c5a 100644 --- a/src/entities/fractions/currency_amount.rs +++ b/src/entities/fractions/currency_amount.rs @@ -7,7 +7,9 @@ pub type CurrencyAmount = FractionLike>; /// Struct representing metadata about a currency #[derive(Clone, Debug, PartialEq)] pub struct CurrencyMeta { + /// The currency associated with this metadata pub currency: T, + /// The scale factor for the currency's decimal places pub decimal_scale: BigUint, } @@ -118,6 +120,11 @@ impl CurrencyAmount { return Err(Error::NotEqual()); } + if decimal_places == 0 { + // Directly convert the numerator to a string for zero decimal places + return Ok(self.numerator().to_string()); + } + Ok( (self.as_fraction() / Fraction::new(self.decimal_scale.clone(), 1)) .to_fixed(decimal_places, rounding), @@ -134,7 +141,6 @@ impl CurrencyAmount { } } -/// Unit tests for the currency module #[cfg(test)] mod tests { use super::*; diff --git a/src/entities/fractions/fraction.rs b/src/entities/fractions/fraction.rs index ddc545a..274554a 100644 --- a/src/entities/fractions/fraction.rs +++ b/src/entities/fractions/fraction.rs @@ -7,6 +7,7 @@ use std::ops::{Add, Deref, Mul, Sub}; pub struct FractionLike { numerator: BigInt, denominator: BigInt, + /// Metadata associated with the fraction pub meta: M, } @@ -33,7 +34,20 @@ impl Deref for FractionLike { pub type Fraction = FractionLike<()>; impl Fraction { - // Constructor for creating a new Fraction instance + /// Creates a new `Fraction` instance with the given numerator and denominator. + /// + /// # Arguments + /// + /// * `numerator` - The numerator of the fraction. + /// * `denominator` - The denominator of the fraction. + /// + /// # Returns + /// + /// A new `Fraction` instance with the specified numerator and denominator. + /// + /// # Panics + /// + /// This function will panic if the denominator is zero. pub fn new(numerator: impl Into, denominator: impl Into) -> Self { FractionBase::new(numerator, denominator, ()) } @@ -195,7 +209,6 @@ where impl Add for FractionLike { type Output = Self; - /// Adds another fraction to the current fraction fn add(self, other: Self) -> Self::Output { if self.denominator == other.denominator() { FractionBase::new( @@ -216,7 +229,6 @@ impl Add for FractionLike { impl Sub for FractionLike { type Output = Self; - /// Subtracts another fraction from the current fraction fn sub(self, other: Self) -> Self::Output { if self.denominator == other.denominator() { FractionBase::new( @@ -237,7 +249,6 @@ impl Sub for FractionLike { impl Mul for FractionLike { type Output = Self; - /// Multiplies the current fraction by another fraction fn mul(self, other: Self) -> Self::Output { FractionBase::new( self.numerator() * other.numerator(), @@ -250,7 +261,6 @@ impl Mul for FractionLike { impl Div for FractionLike { type Output = Self; - /// Divides the current fraction by another fraction /// There's little to no possibility of an error, so unwrap can be used fn div(self, other: Self) -> Self::Output { FractionBase::new( diff --git a/src/entities/fractions/mod.rs b/src/entities/fractions/mod.rs index 0d4f58f..c781e4b 100644 --- a/src/entities/fractions/mod.rs +++ b/src/entities/fractions/mod.rs @@ -1,4 +1,9 @@ +/// This module represents currency, including the currency type and the amount as a fraction. pub mod currency_amount; +/// This module contains with precise division results, avoiding floating-point arithmetic issues. 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 +/// string conversions. pub mod price; diff --git a/src/entities/fractions/percent.rs b/src/entities/fractions/percent.rs index c8beac6..ceb0f5f 100644 --- a/src/entities/fractions/percent.rs +++ b/src/entities/fractions/percent.rs @@ -1,13 +1,12 @@ /// Importing dependencies from the same module use crate::prelude::*; -// Lazily initialized constant representing the fraction 100/1 lazy_static! { static ref ONE_HUNDRED: Fraction = Fraction::new(100, 1); } /// Unit struct to distinguish between a fraction and a percent -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, Copy)] pub struct IsPercent; /// Type alias for a Percent, a [`FractionLike`] with the [`IsPercent`] metadata diff --git a/src/entities/fractions/price.rs b/src/entities/fractions/price.rs index 8868e4a..ef18e3e 100644 --- a/src/entities/fractions/price.rs +++ b/src/entities/fractions/price.rs @@ -11,8 +11,13 @@ where TBase: CurrencyTrait, TQuote: CurrencyTrait, { + /// The base currency for the price pub base_currency: TBase, + + /// The quote currency for the price pub quote_currency: TQuote, + + /// The scalar used to adjust the price for decimal places pub scalar: Fraction, } @@ -49,7 +54,6 @@ where base_amount: CurrencyAmount, quote_amount: CurrencyAmount, ) -> Self { - // Calculate the price as the ratio of quote amount to base amount let res = quote_amount.divide(&base_amount).unwrap(); Self::new( base_amount.meta.currency, diff --git a/src/entities/mod.rs b/src/entities/mod.rs index fbd5c8a..30df1ff 100644 --- a/src/entities/mod.rs +++ b/src/entities/mod.rs @@ -1,6 +1,12 @@ +/// 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; diff --git a/src/entities/token.rs b/src/entities/token.rs index 06ec6aa..7ff6843 100644 --- a/src/entities/token.rs +++ b/src/entities/token.rs @@ -3,10 +3,14 @@ use crate::prelude::*; /// Represents an ERC20 token with a unique address and some metadata. pub type Token = CurrencyLike; +/// Represents the metadata for an ERC20 token, including its address and optional fees. #[derive(Clone, PartialEq, Debug)] pub struct TokenMeta { + /// The address of the token. pub address: Address, + /// The buy fee in basis points (bps) for the token. pub buy_fee_bps: Option, + /// The sell fee in basis points (bps) for the token. pub sell_fee_bps: Option, } @@ -40,6 +44,25 @@ impl CurrencyTrait for Token { } impl Token { + /// Creates a new [`Token`] with the given parameters. + /// + /// # Arguments + /// + /// * `chain_id` - The chain ID of the token. + /// * `address` - The address of the token. + /// * `decimals` - The number of decimals the token uses. + /// * `symbol` - The symbol of the token, if any. + /// * `name` - The name of the token, if any. + /// * `buy_fee_bps` - The buy fee in basis points (bps), if any. + /// * `sell_fee_bps` - The sell fee in basis points (bps), if any. + /// + /// # Returns + /// + /// A new [`Token`] instance. + /// + /// # Panics + /// + /// Panics if `chain_id` is 0. pub const fn new( chain_id: u64, address: Address, diff --git a/src/entities/weth9.rs b/src/entities/weth9.rs index d0b2a9c..13cab0f 100644 --- a/src/entities/weth9.rs +++ b/src/entities/weth9.rs @@ -17,6 +17,15 @@ impl Default for WETH9 { } impl WETH9 { + /// Creates a new instance of `WETH9` with predefined WETH tokens for various chains. + /// + /// This function initializes a `WETH9` struct with a predefined set of WETH tokens + /// for different Ethereum chains. It's useful for quickly setting up a `WETH9` + /// instance without manually inserting each token. + /// + /// # Returns + /// + /// A new `WETH9` instance with predefined WETH tokens. pub fn new() -> Self { let mut tokens = HashMap::new(); diff --git a/src/error.rs b/src/error.rs index cb433eb..ab778d2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,25 +1,25 @@ use crate::prelude::*; /// Represents errors that can occur in the context of currency operations. -#[derive(Debug, Error)] +#[derive(Debug, Error, Clone, Copy)] pub enum Error { - /// Indicates a mismatch in chain IDs. + /// Triggers when compared Chain Ids do not match #[error("Chain IDs do not match: {0} and {1}")] ChainIdMismatch(u64, u64), - /// Indicates that two addresses are equal. + /// Triggers when comapred addresses are the smae #[error("Addresses are equal")] EqualAddresses, - /// Indicates that an amount has exceeded MAX_UINT256. + /// Triggers when it tries to exceed the max uint #[error("amount has exceeded MAX_UINT256")] MaxUint, - /// Indicates that two entities are not equal. + ///Triggers when the Compared values are not equal #[error("not equal")] NotEqual(), - /// Custom error for incorrect input. + /// Triggers when The value is inccorrrect #[error("incorrect")] Incorrect(), } diff --git a/src/examples/mod.rs b/src/examples/mod.rs new file mode 100644 index 0000000..9e7b267 --- /dev/null +++ b/src/examples/mod.rs @@ -0,0 +1,2 @@ +///token example +pub mod token_example; diff --git a/src/examples/token_example.rs b/src/examples/token_example.rs new file mode 100644 index 0000000..22941b6 --- /dev/null +++ b/src/examples/token_example.rs @@ -0,0 +1,28 @@ +// token_example.rs + +// Import the Token struct from the Uniswap SDK-Core +use crate::entities::token::Token; + +/// This function demonstrates basic operations with the Token struct from the Uniswap SDK-Core. +pub fn main() { + // Create a new Token instance for DAI + let dai_token = Token::new( + 1, // Assuming chain_id is 1 for Ethereum mainnet + "0x6B175474E89094C44Da98b954EedeAC495271d0F" + .parse() + .unwrap(), // Assuming this is the correct address + 18, // Decimals for DAI + Some("DAI".to_string()), // Symbol for DAI + Some("Dai Stablecoin".to_string()), // Name for DAI + None, // Assuming no buy fee + None, // Assuming no sell fee + ); + + // Print the token's address and decimals + println!("DAI Token Address: {}", dai_token.address); + println!("DAI Token Decimals: {}", dai_token.decimals); + + // Convert a token chain id + let token_id = dai_token.chain_id; + println!("token_id {}", token_id); +} diff --git a/src/lib.rs b/src/lib.rs index 88ef78c..17eac0c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,11 +2,38 @@ //! //! The Uniswap SDK Core in Rust provides essential functionality for interacting with the Uniswap //! decentralized exchange. +#![warn( + missing_copy_implementations, + missing_debug_implementations, + missing_docs, + unreachable_pub, + clippy::missing_const_for_fn, + 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))] +/// Contains functionality related to All Contracts deployed and supported by the Uniswap SDK. pub mod addresses; +/// Contains functionality related to All Contracts deployed and supported by the Uniswap SDK. pub mod chains; +/// Contains some constants and enums used in the Uniswap SDK Core pub mod constants; +/// Contains entities related to the Uniswap SDK Core, such as currencies, tokens, and fractions. pub mod entities; +/// Contains error types for the Uniswap SDK Core. +/// +/// This module defines custom error types that are used throughout the SDK to +/// handle various error conditions. pub mod error; +/// Contains commonly used items from the Uniswap SDK Core. +/// +/// This module re-exports items that are commonly used together, +/// making it easier to import them in other parts of your application. pub mod prelude; +/// Contains utility functions and helpers used across the Uniswap SDK Core. pub mod utils; + +/// Contains examples of how Uniswap sdk core can be used +pub mod examples;