Skip to content

Commit

Permalink
perf!: refactor Token with generic impl Currency (#84)
Browse files Browse the repository at this point in the history
* perf!: refactor `Token` with generic `impl Currency`

Updated various functions to accept `CurrencyAmount<impl Currency>` instead of specific `Token` references, improving code flexibility and reusability. Adjusted internal logic and validations to accommodate the new type references, ensuring correctness and consistency.

* fix lint
  • Loading branch information
shuhuiluo authored Sep 26, 2024
1 parent 53b858f commit 72bdf2f
Show file tree
Hide file tree
Showing 7 changed files with 27 additions and 28 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ jobs:
${{ runner.os }}-cargo-registry-
- name: Install Rust toolchain via rustup
run: |
rustup override set nightly
rustup component add clippy --toolchain nightly
rustup component add rustfmt --toolchain nightly
rustup component add clippy
rustup component add rustfmt
- name: Check linting
run: cargo clippy --all-targets --all-features -- -D warnings
- name: Check formatting
Expand Down
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uniswap-v3-sdk"
version = "1.0.0"
version = "1.1.0"
edition = "2021"
authors = ["Shuhui Luo <twitter.com/aureliano_law>"]
description = "Uniswap V3 SDK for Rust"
Expand All @@ -14,7 +14,7 @@ exclude = [".github", ".gitignore", "rustfmt.toml"]
all-features = true

[dependencies]
alloy = { version = "0.3.5", optional = true, features = ["contract"] }
alloy = { version = "0.3", optional = true, features = ["contract"] }
alloy-primitives = "0.8"
alloy-sol-types = "0.8"
anyhow = { version = "1.0", optional = true }
Expand All @@ -29,7 +29,7 @@ rustc-hash = "2.0"
serde_json = { version = "1.0", optional = true }
thiserror = { version = "1.0", optional = true }
uniswap-lens = { version = "0.3", optional = true }
uniswap-sdk-core = "2.2.0"
uniswap-sdk-core = "2.3.0"

[features]
default = []
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Uniswap V3 SDK Rust

[![Unit Tests](https://github.com/shuhuiluo/uniswap-v3-sdk-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/shuhuiluo/uniswap-v3-sdk-rs/actions/workflows/rust.yml)
[![Rust CI](https://github.com/shuhuiluo/uniswap-v3-sdk-rs/actions/workflows/rust.yml/badge.svg)](https://github.com/shuhuiluo/uniswap-v3-sdk-rs/actions/workflows/rust.yml)
[![docs.rs](https://img.shields.io/docsrs/uniswap-v3-sdk)](https://docs.rs/uniswap-v3-sdk/latest/uniswap_v3_sdk/)
[![crates.io](https://img.shields.io/crates/v/uniswap-v3-sdk.svg)](https://crates.io/crates/uniswap-v3-sdk)

A Rust SDK for building applications on top of Uniswap V3. Migration from the
Expand Down Expand Up @@ -48,7 +49,7 @@ It is feature-complete with unit tests matching the TypeScript SDK.
Add the following to your `Cargo.toml` file:

```toml
uniswap-v3-sdk = { version = "1.0.0", features = ["extensions", "std"] }
uniswap-v3-sdk = { version = "1.1.0", features = ["extensions", "std"] }
```

### Usage
Expand Down
18 changes: 9 additions & 9 deletions src/entities/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ impl<TP: TickDataProvider> Pool<TP> {
///
/// returns: bool
#[inline]
pub fn involves_token(&self, token: &Token) -> bool {
pub fn involves_token(&self, token: &impl Currency) -> bool {
self.token0.equals(token) || self.token1.equals(token)
}

Expand Down Expand Up @@ -399,9 +399,9 @@ impl<TP: Clone + TickDataProvider> Pool<TP> {
#[inline]
pub fn get_output_amount(
&self,
input_amount: &CurrencyAmount<Token>,
input_amount: &CurrencyAmount<impl Currency>,
sqrt_price_limit_x96: Option<U160>,
) -> Result<(CurrencyAmount<Token>, Self), Error> {
) -> Result<(CurrencyAmount<&Token>, Self), Error> {
assert!(self.involves_token(&input_amount.currency), "TOKEN");

let zero_for_one = input_amount.currency.equals(&self.token0);
Expand All @@ -423,9 +423,9 @@ impl<TP: Clone + TickDataProvider> Pool<TP> {
}

let output_token = if zero_for_one {
self.token1.clone()
&self.token1
} else {
self.token0.clone()
&self.token0
};
Ok((
CurrencyAmount::from_raw_amount(output_token, -output_amount.to_big_int())?,
Expand Down Expand Up @@ -454,9 +454,9 @@ impl<TP: Clone + TickDataProvider> Pool<TP> {
#[inline]
pub fn get_input_amount(
&self,
output_amount: &CurrencyAmount<Token>,
output_amount: &CurrencyAmount<impl Currency>,
sqrt_price_limit_x96: Option<U160>,
) -> Result<(CurrencyAmount<Token>, Self), Error> {
) -> Result<(CurrencyAmount<&Token>, Self), Error> {
assert!(self.involves_token(&output_amount.currency), "TOKEN");

let zero_for_one = output_amount.currency.equals(&self.token1);
Expand All @@ -478,9 +478,9 @@ impl<TP: Clone + TickDataProvider> Pool<TP> {
}

let input_token = if zero_for_one {
self.token0.clone()
&self.token0
} else {
self.token1.clone()
&self.token1
};
Ok((
CurrencyAmount::from_raw_amount(input_token, input_amount.to_big_int())?,
Expand Down
16 changes: 8 additions & 8 deletions src/entities/trade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ where
amount: CurrencyAmount<impl Currency>,
trade_type: TradeType,
) -> Result<Self, Error> {
let mut token_amount: CurrencyAmount<Token> = amount.wrapped()?;
let mut token_amount: CurrencyAmount<&Token> = amount.wrapped()?;
let input_amount: CurrencyAmount<TInput>;
let output_amount: CurrencyAmount<TOutput>;
match trade_type {
Expand All @@ -554,16 +554,16 @@ where
for pool in &route.pools {
(token_amount, _) = pool.get_output_amount(&token_amount, None)?;
}
input_amount = CurrencyAmount::from_fractional_amount(
route.input.clone(),
amount.numerator,
amount.denominator,
)?;
output_amount = CurrencyAmount::from_fractional_amount(
route.output.clone(),
token_amount.numerator,
token_amount.denominator,
)?;
input_amount = CurrencyAmount::from_fractional_amount(
route.input.clone(),
amount.numerator,
amount.denominator,
)?;
}
TradeType::ExactOutput => {
assert!(
Expand Down Expand Up @@ -633,7 +633,7 @@ where
currency_out: &'a TOutput,
best_trade_options: BestTradeOptions,
current_pools: Vec<Pool<TP>>,
next_amount_in: Option<CurrencyAmount<Token>>,
next_amount_in: Option<CurrencyAmount<&'a Token>>,
best_trades: &'a mut Vec<Self>,
) -> Result<&'a mut Vec<Self>, Error> {
assert!(!pools.is_empty(), "POOLS");
Expand Down Expand Up @@ -723,7 +723,7 @@ where
currency_amount_out: &'a CurrencyAmount<TOutput>,
best_trade_options: BestTradeOptions,
current_pools: Vec<Pool<TP>>,
next_amount_out: Option<CurrencyAmount<Token>>,
next_amount_out: Option<CurrencyAmount<&'a Token>>,
best_trades: &'a mut Vec<Self>,
) -> Result<&'a mut Vec<Self>, Error> {
assert!(!pools.is_empty(), "POOLS");
Expand Down
1 change: 0 additions & 1 deletion src/extensions/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ fn reconstruct_liquidity_array<I: TickIndex>(
Ok(liquidity_array)
}

#[allow(clippy::too_long_first_doc_paragraph)]
/// Fetches the liquidity within a tick range for the specified pool, using an [ephemeral contract](https://github.com/Aperture-Finance/Aperture-Lens/blob/904101e4daed59e02fd4b758b98b0749e70b583b/contracts/EphemeralGetPopulatedTicksInRange.sol)
/// in a single `eth_call`.
///
Expand Down
4 changes: 2 additions & 2 deletions src/extensions/price_tick_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ where
/// ## Arguments
///
/// * `sqrt_ratio_x96`: The sqrt ratio of the base token in terms of the quote token as a Q64.96
/// [`U256`].
/// [`U160`].
/// * `base_token`: The base token.
/// * `quote_token`: The quote token.
///
Expand Down Expand Up @@ -235,7 +235,7 @@ where
///
/// ## Returns
///
/// The sqrt ratio of token1/token0, as a [`U256`].
/// The sqrt ratio of token1/token0, as a [`U160`].
///
/// ## Examples
///
Expand Down

0 comments on commit 72bdf2f

Please sign in to comment.