Skip to content

Commit

Permalink
Rename constructors to try_new (#3199)
Browse files Browse the repository at this point in the history
# Description
This PR try to tackle issue #3179.

# Changes
- [ ] Rename all constructors that return `Result` to `try_new`.

## How to test
Existing unit test.

---------

Co-authored-by: ilya <[email protected]>
  • Loading branch information
p-andhika and squadgazzz authored Jan 2, 2025
1 parent 9d5a117 commit 0ff75fa
Show file tree
Hide file tree
Showing 46 changed files with 88 additions and 81 deletions.
4 changes: 2 additions & 2 deletions crates/autopilot/src/domain/auction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl Price {
/// The base Ether amount for pricing.
const BASE: u128 = 10_u128.pow(18);

pub fn new(value: eth::Ether) -> Result<Self, InvalidPrice> {
pub fn try_new(value: eth::Ether) -> Result<Self, InvalidPrice> {
if value.0.is_zero() {
Err(InvalidPrice)
} else {
Expand All @@ -70,7 +70,7 @@ impl Price {
/// use autopilot::domain::{auction::Price, eth};
///
/// let amount = eth::TokenAmount::from(eth::U256::exp10(18));
/// let price = Price::new(eth::Ether::from(eth::U256::exp10(15))).unwrap(); // 0.001 ETH
/// let price = Price::try_new(eth::Ether::from(eth::U256::exp10(15))).unwrap(); // 0.001 ETH
///
/// let eth = price.in_eth(amount);
/// assert_eq!(eth, eth::Ether::from(eth::U256::exp10(15)));
Expand Down
2 changes: 1 addition & 1 deletion crates/autopilot/src/domain/competition/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub struct TradedOrder {
pub struct Score(eth::Ether);

impl Score {
pub fn new(score: eth::Ether) -> Result<Self, ZeroScore> {
pub fn try_new(score: eth::Ether) -> Result<Self, ZeroScore> {
if score.0.is_zero() {
Err(ZeroScore)
} else {
Expand Down
23 changes: 13 additions & 10 deletions crates/autopilot/src/domain/settlement/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,13 +325,14 @@ mod tests {
eth::TokenAddress(eth::H160::from_slice(&hex!(
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
))),
auction::Price::new(eth::U256::from(1000000000000000000u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(1000000000000000000u128).into())
.unwrap(),
),
(
eth::TokenAddress(eth::H160::from_slice(&hex!(
"c52fafdc900cb92ae01e6e4f8979af7f436e2eb2"
))),
auction::Price::new(eth::U256::from(537359915436704u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(537359915436704u128).into()).unwrap(),
),
]),
surplus_capturing_jit_order_owners: Default::default(),
Expand Down Expand Up @@ -455,15 +456,17 @@ mod tests {
eth::TokenAddress(eth::H160::from_slice(&hex!(
"dac17f958d2ee523a2206206994597c13d831ec7"
))),
auction::Price::new(eth::U256::from(321341140475275961528483840u128).into())
auction::Price::try_new(eth::U256::from(321341140475275961528483840u128).into())
.unwrap(),
),
(
eth::TokenAddress(eth::H160::from_slice(&hex!(
"056fd409e1d7a124bd7017459dfea2f387b6d5cd"
))),
auction::Price::new(eth::U256::from(3177764302250520038326415654912u128).into())
.unwrap(),
auction::Price::try_new(
eth::U256::from(3177764302250520038326415654912u128).into(),
)
.unwrap(),
),
]);

Expand Down Expand Up @@ -621,14 +624,14 @@ mod tests {
eth::TokenAddress(eth::H160::from_slice(&hex!(
"a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
))),
auction::Price::new(eth::U256::from(374263465721452989998170112u128).into())
auction::Price::try_new(eth::U256::from(374263465721452989998170112u128).into())
.unwrap(),
),
(
eth::TokenAddress(eth::H160::from_slice(&hex!(
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
))),
auction::Price::new(eth::U256::from(1000000000000000000u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(1000000000000000000u128).into()).unwrap(),
),
]);

Expand Down Expand Up @@ -795,19 +798,19 @@ mod tests {
eth::TokenAddress(eth::H160::from_slice(&hex!(
"812Ba41e071C7b7fA4EBcFB62dF5F45f6fA853Ee"
))),
auction::Price::new(eth::U256::from(400373909534592401408u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(400373909534592401408u128).into()).unwrap(),
),
(
eth::TokenAddress(eth::H160::from_slice(&hex!(
"a21Af1050F7B26e0cfF45ee51548254C41ED6b5c"
))),
auction::Price::new(eth::U256::from(127910593u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(127910593u128).into()).unwrap(),
),
(
eth::TokenAddress(eth::H160::from_slice(&hex!(
"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
))),
auction::Price::new(eth::U256::from(1000000000000000000u128).into()).unwrap(),
auction::Price::try_new(eth::U256::from(1000000000000000000u128).into()).unwrap(),
),
]);

Expand Down
2 changes: 1 addition & 1 deletion crates/autopilot/src/domain/settlement/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl Transaction {
clearing_prices,
trades: decoded_trades,
interactions: _interactions,
} = tokenized::Tokenized::new(&crate::util::Bytes(data.to_vec()))?;
} = tokenized::Tokenized::try_new(&crate::util::Bytes(data.to_vec()))?;

let mut trades = Vec::with_capacity(decoded_trades.len());
for trade in decoded_trades {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub(super) struct Tokenized {
}

impl Tokenized {
pub fn new(calldata: &eth::Calldata) -> Result<Self, error::Decoding> {
pub fn try_new(calldata: &eth::Calldata) -> Result<Self, error::Decoding> {
let function = contracts::GPv2Settlement::raw_contract()
.interface
.abi
Expand Down
2 changes: 1 addition & 1 deletion crates/autopilot/src/infra/persistence/dto/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Auction {
.prices
.into_iter()
.map(|(key, value)| {
Price::new(value.into()).map(|price| (eth::TokenAddress(key), price))
Price::try_new(value.into()).map(|price| (eth::TokenAddress(key), price))
})
.collect::<Result<_, _>>()?,
surplus_capturing_jit_order_owners: self
Expand Down
2 changes: 1 addition & 1 deletion crates/autopilot/src/infra/persistence/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ impl Persistence {
let token = eth::H160(price.token.0).into();
let price = big_decimal_to_u256(&price.price)
.ok_or(domain::auction::InvalidPrice)
.and_then(|p| domain::auction::Price::new(p.into()))
.and_then(|p| domain::auction::Price::try_new(p.into()))
.map_err(|_err| error::Auction::InvalidPrice(token));
price.map(|price| (token, price))
})
Expand Down
4 changes: 2 additions & 2 deletions crates/autopilot/src/infra/solvers/dto/solve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,15 @@ impl Solution {
Ok(domain::competition::Solution::new(
self.solution_id,
self.submission_address.into(),
domain::competition::Score::new(self.score.into())?,
domain::competition::Score::try_new(self.score.into())?,
self.orders
.into_iter()
.map(|(o, amounts)| (o.into(), amounts.into_domain()))
.collect(),
self.clearing_prices
.into_iter()
.map(|(token, price)| {
domain::auction::Price::new(price.into()).map(|price| (token.into(), price))
domain::auction::Price::try_new(price.into()).map(|price| (token.into(), price))
})
.collect::<Result<_, _>>()?,
))
Expand Down
2 changes: 1 addition & 1 deletion crates/autopilot/src/solvable_orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ impl SolvableOrdersCache {
prices: prices
.into_iter()
.map(|(key, value)| {
Price::new(value.into()).map(|price| (eth::TokenAddress(key), price))
Price::try_new(value.into()).map(|price| (eth::TokenAddress(key), price))
})
.collect::<Result<_, _>>()?,
surplus_capturing_jit_order_owners,
Expand Down
4 changes: 2 additions & 2 deletions crates/contracts/src/bin/vendor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn main() {

#[rustfmt::skip]
fn run() -> Result<()> {
let vendor = Vendor::new()?;
let vendor = Vendor::try_new()?;

const ETHFLOW_VERSION: &str = "0.0.0-rc.3";

Expand Down Expand Up @@ -215,7 +215,7 @@ struct Vendor {
}

impl Vendor {
fn new() -> Result<Self> {
fn try_new() -> Result<Self> {
let artifacts = paths::contract_artifacts_dir();
tracing::info!("vendoring contract artifacts to '{}'", artifacts.display());
fs::create_dir_all(&artifacts)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/boundary/liquidity/balancer/v2/stable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn to_domain(id: liquidity::Id, pool: StablePoolOrder) -> Result<liquidity::
kind: liquidity::Kind::BalancerV2Stable(balancer::v2::stable::Pool {
vault: vault(&pool),
id: pool_id(&pool),
reserves: balancer::v2::stable::Reserves::new(
reserves: balancer::v2::stable::Reserves::try_new(
pool.reserves
.into_iter()
.map(|(token, reserve)| {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn to_domain(id: liquidity::Id, pool: WeightedProductOrder) -> Result<liquid
kind: liquidity::Kind::BalancerV2Weighted(balancer::v2::weighted::Pool {
vault: vault(&pool),
id: pool_id(&pool),
reserves: balancer::v2::weighted::Reserves::new(
reserves: balancer::v2::weighted::Reserves::try_new(
pool.reserves
.into_iter()
.map(|(token, reserve)| {
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/boundary/liquidity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub struct Fetcher {

impl Fetcher {
/// Creates a new fetcher for the specified configuration.
pub async fn new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result<Self> {
pub async fn try_new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result<Self> {
let blocks = current_block::Arguments {
block_stream_poll_interval: BLOCK_POLL_INTERVAL,
};
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/boundary/liquidity/swapr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn to_domain(id: liquidity::Id, pool: ConstantProductOrder) -> Result<liquid
);

let bps = (pool.fee.numer() * BPS_BASE) / pool.fee.denom();
let fee = swapr::Fee::new(bps)?;
let fee = swapr::Fee::try_new(bps)?;
Ok(liquidity::Liquidity {
id,
gas: GAS_PER_SWAP.into(),
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/boundary/liquidity/uniswap/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub(in crate::boundary::liquidity) fn to_domain_pool(
Ok(liquidity::uniswap::v2::Pool {
address: pool.address.into(),
router: router(&pool),
reserves: liquidity::uniswap::v2::Reserves::new(
reserves: liquidity::uniswap::v2::Reserves::try_new(
eth::Asset {
token: pool.tokens.get().0.into(),
amount: pool.reserves.0.into(),
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/boundary/liquidity/uniswap/v3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn to_domain(id: liquidity::Id, pool: ConcentratedLiquidity) -> Result<liqui
kind: liquidity::Kind::UniswapV3(Pool {
router: handler.inner.router.address().into(),
address: pool.pool.address.into(),
tokens: liquidity::TokenPair::new(
tokens: liquidity::TokenPair::try_new(
pool.pool.tokens[0].id.into(),
pool.pool.tokens[1].id.into(),
)?,
Expand Down
10 changes: 6 additions & 4 deletions crates/driver/src/domain/competition/auction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ impl Auction {
pub fn liquidity_pairs(&self) -> HashSet<liquidity::TokenPair> {
self.orders
.iter()
.filter_map(|order| liquidity::TokenPair::new(order.sell.token, order.buy.token).ok())
.filter_map(|order| {
liquidity::TokenPair::try_new(order.sell.token, order.buy.token).ok()
})
.collect()
}

Expand Down Expand Up @@ -528,7 +530,7 @@ impl Price {
/// The base Ether amount for pricing.
const BASE: u128 = 10_u128.pow(18);

pub fn new(value: eth::Ether) -> Result<Self, InvalidPrice> {
pub fn try_new(value: eth::Ether) -> Result<Self, InvalidPrice> {
if value.0.is_zero() {
Err(InvalidPrice)
} else {
Expand All @@ -546,7 +548,7 @@ impl Price {
/// use driver::domain::{competition::auction::Price, eth};
///
/// let amount = eth::TokenAmount::from(eth::U256::exp10(18));
/// let price = Price::new(eth::Ether::from(eth::U256::exp10(15))).unwrap(); // 0.001 ETH
/// let price = Price::try_new(eth::Ether::from(eth::U256::exp10(15))).unwrap(); // 0.001 ETH
///
/// let eth = price.in_eth(amount);
/// assert_eq!(eth, eth::Ether::from(eth::U256::exp10(15)));
Expand All @@ -564,7 +566,7 @@ impl Price {
/// use driver::domain::{competition::auction::Price, eth};
///
/// let amount = eth::Ether::from(eth::U256::exp10(18));
/// let price = Price::new(eth::Ether::from(eth::U256::exp10(17))).unwrap(); // 0.1ETH
/// let price = Price::try_new(eth::Ether::from(eth::U256::exp10(17))).unwrap(); // 0.1ETH
/// assert_eq!(price.from_eth(amount), eth::U256::exp10(19).into());
/// ```
pub fn from_eth(self, amount: eth::Ether) -> eth::TokenAmount {
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/liquidity/balancer/v2/stable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub struct Reserves(Vec<Reserve>);
impl Reserves {
/// Creates new Balancer V2 token reserves, returns `Err` if the specified
/// token reserves are invalid, specifically, if there are duplicate tokens.
pub fn new(reserves: Vec<Reserve>) -> Result<Self, InvalidReserves> {
pub fn try_new(reserves: Vec<Reserve>) -> Result<Self, InvalidReserves> {
if !reserves.iter().map(|r| r.asset.token).all_unique() {
return Err(InvalidReserves);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/liquidity/balancer/v2/weighted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub struct Reserves(Vec<Reserve>);
impl Reserves {
/// Creates new Balancer V2 token reserves, returns `Err` if the specified
/// token reserves are invalid.
pub fn new(reserves: Vec<Reserve>) -> Result<Self, InvalidReserves> {
pub fn try_new(reserves: Vec<Reserve>) -> Result<Self, InvalidReserves> {
if !reserves.iter().map(|r| r.asset.token).all_unique() {
return Err(InvalidReserves::DuplicateToken);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/liquidity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ pub struct TokenPair(eth::TokenAddress, eth::TokenAddress);
impl TokenPair {
/// Returns a token pair for the given tokens, or `Err` if `a` and `b` are
/// equal.
pub fn new(a: eth::TokenAddress, b: eth::TokenAddress) -> Result<Self, InvalidTokenPair> {
pub fn try_new(a: eth::TokenAddress, b: eth::TokenAddress) -> Result<Self, InvalidTokenPair> {
match a.cmp(&b) {
Ordering::Less => Ok(Self(a, b)),
Ordering::Equal => Err(InvalidTokenPair),
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/liquidity/swapr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl Pool {
impl Fee {
/// Creates a new fee from the specified basis points. Returns `Err` for
/// invalid fee values (i.e. outside the range `[0, 1000]`).
pub fn new(bps: u32) -> Result<Self, InvalidFee> {
pub fn try_new(bps: u32) -> Result<Self, InvalidFee> {
if !(0..=1000).contains(&bps) {
return Err(InvalidFee);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/liquidity/uniswap/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub struct Reserves(eth::Asset, eth::Asset);
impl Reserves {
/// Creates new Uniswap V2 token reserves, returns `Err` if the specified
/// token addresses are equal.
pub fn new(a: eth::Asset, b: eth::Asset) -> Result<Self, InvalidReserves> {
pub fn try_new(a: eth::Asset, b: eth::Asset) -> Result<Self, InvalidReserves> {
match a.token.cmp(&b.token) {
Ordering::Less => Ok(Self(a, b)),
Ordering::Equal => Err(InvalidReserves),
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/domain/mempools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct Mempools {
}

impl Mempools {
pub fn new(mempools: Vec<infra::Mempool>, ethereum: Ethereum) -> Result<Self, NoMempools> {
pub fn try_new(mempools: Vec<infra::Mempool>, ethereum: Ethereum) -> Result<Self, NoMempools> {
if mempools.is_empty() {
Err(NoMempools)
} else {
Expand Down
8 changes: 4 additions & 4 deletions crates/driver/src/domain/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct Quote {
}

impl Quote {
fn new(eth: &Ethereum, solution: competition::Solution) -> Result<Self, Error> {
fn try_new(eth: &Ethereum, solution: competition::Solution) -> Result<Self, Error> {
Ok(Self {
clearing_prices: solution
.clearing_prices()
Expand Down Expand Up @@ -101,7 +101,7 @@ impl Order {
.fake_auction(eth, tokens, solver.quote_using_limit_orders())
.await?;
let solutions = solver.solve(&auction, &liquidity).await?;
Quote::new(
Quote::try_new(
eth,
// TODO(#1468): choose the best solution in the future, but for now just pick the
// first solution
Expand Down Expand Up @@ -226,7 +226,7 @@ impl Order {

/// Returns the token pairs to fetch liquidity for.
fn liquidity_pairs(&self) -> HashSet<liquidity::TokenPair> {
let pair = liquidity::TokenPair::new(self.tokens.sell(), self.tokens.buy())
let pair = liquidity::TokenPair::try_new(self.tokens.sell(), self.tokens.buy())
.expect("sell != buy by construction");
iter::once(pair).collect()
}
Expand All @@ -243,7 +243,7 @@ pub struct Tokens {
impl Tokens {
/// Creates a new instance of [`Tokens`], verifying that the input buy and
/// sell tokens are distinct.
pub fn new(sell: eth::TokenAddress, buy: eth::TokenAddress) -> Result<Self, SameTokens> {
pub fn try_new(sell: eth::TokenAddress, buy: eth::TokenAddress) -> Result<Self, SameTokens> {
if sell == buy {
return Err(SameTokens);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/infra/api/routes/quote/dto/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use {
impl Order {
pub fn into_domain(self, timeouts: Timeouts) -> Result<quote::Order, Error> {
Ok(quote::Order {
tokens: quote::Tokens::new(self.sell_token.into(), self.buy_token.into())
tokens: quote::Tokens::try_new(self.sell_token.into(), self.buy_token.into())
.map_err(|quote::SameTokens| Error::SameTokens)?,
amount: self.amount.into(),
side: match self.kind {
Expand Down
2 changes: 1 addition & 1 deletion crates/driver/src/infra/blockchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub struct Rpc {
impl Rpc {
/// Instantiate an RPC client to an Ethereum (or Ethereum-compatible) node
/// at the specifed URL.
pub async fn new(url: &url::Url) -> Result<Self, RpcError> {
pub async fn try_new(url: &url::Url) -> Result<Self, RpcError> {
let web3 = boundary::buffered_web3_client(url);
let chain = Chain::try_from(web3.eth().chain_id().await?)?;

Expand Down
4 changes: 2 additions & 2 deletions crates/driver/src/infra/liquidity/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ pub enum AtBlock {
impl Fetcher {
/// Creates a new liquidity fetcher for the specified Ethereum instance and
/// configuration.
pub async fn new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result<Self, Error> {
pub async fn try_new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result<Self, Error> {
let eth = eth.with_metric_label("liquidity".into());
let inner = boundary::liquidity::Fetcher::new(&eth, config).await?;
let inner = boundary::liquidity::Fetcher::try_new(&eth, config).await?;
Ok(Self {
inner: Arc::new(inner),
})
Expand Down
Loading

0 comments on commit 0ff75fa

Please sign in to comment.