From 0ff75fa3ce8cd3e535227bc60369ddcf91e8ab5c Mon Sep 17 00:00:00 2001
From: Andhika Prakasiwi
Date: Thu, 2 Jan 2025 15:12:15 +0700
Subject: [PATCH] Rename constructors to `try_new` (#3199)
# 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
---
crates/autopilot/src/domain/auction/mod.rs | 4 ++--
.../autopilot/src/domain/competition/mod.rs | 2 +-
crates/autopilot/src/domain/settlement/mod.rs | 23 +++++++++++--------
.../src/domain/settlement/transaction/mod.rs | 2 +-
.../settlement/transaction/tokenized.rs | 2 +-
.../src/infra/persistence/dto/auction.rs | 2 +-
crates/autopilot/src/infra/persistence/mod.rs | 2 +-
.../autopilot/src/infra/solvers/dto/solve.rs | 4 ++--
crates/autopilot/src/solvable_orders.rs | 2 +-
crates/contracts/src/bin/vendor.rs | 4 ++--
.../boundary/liquidity/balancer/v2/stable.rs | 2 +-
.../liquidity/balancer/v2/weighted.rs | 2 +-
crates/driver/src/boundary/liquidity/mod.rs | 2 +-
crates/driver/src/boundary/liquidity/swapr.rs | 2 +-
.../src/boundary/liquidity/uniswap/v2.rs | 2 +-
.../src/boundary/liquidity/uniswap/v3.rs | 2 +-
.../driver/src/domain/competition/auction.rs | 10 ++++----
.../domain/liquidity/balancer/v2/stable.rs | 2 +-
.../domain/liquidity/balancer/v2/weighted.rs | 2 +-
crates/driver/src/domain/liquidity/mod.rs | 2 +-
crates/driver/src/domain/liquidity/swapr.rs | 2 +-
.../driver/src/domain/liquidity/uniswap/v2.rs | 2 +-
crates/driver/src/domain/mempools.rs | 2 +-
crates/driver/src/domain/quote.rs | 8 +++----
.../src/infra/api/routes/quote/dto/order.rs | 2 +-
crates/driver/src/infra/blockchain/mod.rs | 2 +-
crates/driver/src/infra/liquidity/fetcher.rs | 4 ++--
crates/driver/src/infra/solver/mod.rs | 2 +-
crates/driver/src/run.rs | 10 ++++----
crates/driver/src/tests/setup/solver.rs | 2 +-
crates/orderbook/src/database/mod.rs | 2 +-
crates/orderbook/src/database/orders.rs | 12 +++++-----
.../src/database/solver_competition.rs | 2 +-
crates/orderbook/src/orderbook.rs | 2 +-
crates/orderbook/src/run.rs | 2 +-
crates/shared/src/external_prices.rs | 6 ++---
crates/shared/src/macros.rs | 2 +-
.../src/sources/balancer_v2/graph_api.rs | 2 +-
.../sources/balancer_v2/pool_fetching/mod.rs | 2 +-
.../balancer_v2/pools/composable_stable.rs | 2 +-
.../src/sources/balancer_v2/pools/stable.rs | 10 ++++----
.../src/sources/balancer_v2/swap/mod.rs | 6 ++---
.../src/sources/uniswap_v3/graph_api.rs | 2 +-
crates/shared/src/subgraph.rs | 2 +-
crates/solver/src/liquidity/balancer_v2.rs | 2 +-
.../solvers/src/boundary/liquidity/stable.rs | 2 +-
46 files changed, 88 insertions(+), 81 deletions(-)
diff --git a/crates/autopilot/src/domain/auction/mod.rs b/crates/autopilot/src/domain/auction/mod.rs
index 8906bad418..98d4fefb78 100644
--- a/crates/autopilot/src/domain/auction/mod.rs
+++ b/crates/autopilot/src/domain/auction/mod.rs
@@ -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 {
+ pub fn try_new(value: eth::Ether) -> Result {
if value.0.is_zero() {
Err(InvalidPrice)
} else {
@@ -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)));
diff --git a/crates/autopilot/src/domain/competition/mod.rs b/crates/autopilot/src/domain/competition/mod.rs
index d239ae6f44..52cd69df22 100644
--- a/crates/autopilot/src/domain/competition/mod.rs
+++ b/crates/autopilot/src/domain/competition/mod.rs
@@ -79,7 +79,7 @@ pub struct TradedOrder {
pub struct Score(eth::Ether);
impl Score {
- pub fn new(score: eth::Ether) -> Result {
+ pub fn try_new(score: eth::Ether) -> Result {
if score.0.is_zero() {
Err(ZeroScore)
} else {
diff --git a/crates/autopilot/src/domain/settlement/mod.rs b/crates/autopilot/src/domain/settlement/mod.rs
index 2a47bd4c75..7908789719 100644
--- a/crates/autopilot/src/domain/settlement/mod.rs
+++ b/crates/autopilot/src/domain/settlement/mod.rs
@@ -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(),
@@ -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(),
),
]);
@@ -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(),
),
]);
@@ -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(),
),
]);
diff --git a/crates/autopilot/src/domain/settlement/transaction/mod.rs b/crates/autopilot/src/domain/settlement/transaction/mod.rs
index 4f7ca2e62e..3b0e3f4540 100644
--- a/crates/autopilot/src/domain/settlement/transaction/mod.rs
+++ b/crates/autopilot/src/domain/settlement/transaction/mod.rs
@@ -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 {
diff --git a/crates/autopilot/src/domain/settlement/transaction/tokenized.rs b/crates/autopilot/src/domain/settlement/transaction/tokenized.rs
index b0874b7476..ffd2fbabf7 100644
--- a/crates/autopilot/src/domain/settlement/transaction/tokenized.rs
+++ b/crates/autopilot/src/domain/settlement/transaction/tokenized.rs
@@ -16,7 +16,7 @@ pub(super) struct Tokenized {
}
impl Tokenized {
- pub fn new(calldata: ð::Calldata) -> Result {
+ pub fn try_new(calldata: ð::Calldata) -> Result {
let function = contracts::GPv2Settlement::raw_contract()
.interface
.abi
diff --git a/crates/autopilot/src/infra/persistence/dto/auction.rs b/crates/autopilot/src/infra/persistence/dto/auction.rs
index 3c576a74fc..6dfa8a4fc6 100644
--- a/crates/autopilot/src/infra/persistence/dto/auction.rs
+++ b/crates/autopilot/src/infra/persistence/dto/auction.rs
@@ -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::>()?,
surplus_capturing_jit_order_owners: self
diff --git a/crates/autopilot/src/infra/persistence/mod.rs b/crates/autopilot/src/infra/persistence/mod.rs
index ce4654df77..5a46e35a7e 100644
--- a/crates/autopilot/src/infra/persistence/mod.rs
+++ b/crates/autopilot/src/infra/persistence/mod.rs
@@ -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))
})
diff --git a/crates/autopilot/src/infra/solvers/dto/solve.rs b/crates/autopilot/src/infra/solvers/dto/solve.rs
index ad793a7f2f..896580f8d2 100644
--- a/crates/autopilot/src/infra/solvers/dto/solve.rs
+++ b/crates/autopilot/src/infra/solvers/dto/solve.rs
@@ -95,7 +95,7 @@ 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()))
@@ -103,7 +103,7 @@ impl Solution {
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::>()?,
))
diff --git a/crates/autopilot/src/solvable_orders.rs b/crates/autopilot/src/solvable_orders.rs
index 25155833cd..b7345251e5 100644
--- a/crates/autopilot/src/solvable_orders.rs
+++ b/crates/autopilot/src/solvable_orders.rs
@@ -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::>()?,
surplus_capturing_jit_order_owners,
diff --git a/crates/contracts/src/bin/vendor.rs b/crates/contracts/src/bin/vendor.rs
index 3cf2fc0a36..b606c22bc0 100644
--- a/crates/contracts/src/bin/vendor.rs
+++ b/crates/contracts/src/bin/vendor.rs
@@ -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";
@@ -215,7 +215,7 @@ struct Vendor {
}
impl Vendor {
- fn new() -> Result {
+ fn try_new() -> Result {
let artifacts = paths::contract_artifacts_dir();
tracing::info!("vendoring contract artifacts to '{}'", artifacts.display());
fs::create_dir_all(&artifacts)?;
diff --git a/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs b/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs
index e34e206adc..539e8e7045 100644
--- a/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs
+++ b/crates/driver/src/boundary/liquidity/balancer/v2/stable.rs
@@ -20,7 +20,7 @@ pub fn to_domain(id: liquidity::Id, pool: StablePoolOrder) -> Result Result Result {
+ pub async fn try_new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result {
let blocks = current_block::Arguments {
block_stream_poll_interval: BLOCK_POLL_INTERVAL,
};
diff --git a/crates/driver/src/boundary/liquidity/swapr.rs b/crates/driver/src/boundary/liquidity/swapr.rs
index a1ac620ba5..e8492b2c32 100644
--- a/crates/driver/src/boundary/liquidity/swapr.rs
+++ b/crates/driver/src/boundary/liquidity/swapr.rs
@@ -24,7 +24,7 @@ pub fn to_domain(id: liquidity::Id, pool: ConstantProductOrder) -> Result Result HashSet {
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()
}
@@ -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 {
+ pub fn try_new(value: eth::Ether) -> Result {
if value.0.is_zero() {
Err(InvalidPrice)
} else {
@@ -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)));
@@ -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 {
diff --git a/crates/driver/src/domain/liquidity/balancer/v2/stable.rs b/crates/driver/src/domain/liquidity/balancer/v2/stable.rs
index 835bf5a1ff..fbcdbbdb6d 100644
--- a/crates/driver/src/domain/liquidity/balancer/v2/stable.rs
+++ b/crates/driver/src/domain/liquidity/balancer/v2/stable.rs
@@ -53,7 +53,7 @@ pub struct Reserves(Vec);
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) -> Result {
+ pub fn try_new(reserves: Vec) -> Result {
if !reserves.iter().map(|r| r.asset.token).all_unique() {
return Err(InvalidReserves);
}
diff --git a/crates/driver/src/domain/liquidity/balancer/v2/weighted.rs b/crates/driver/src/domain/liquidity/balancer/v2/weighted.rs
index cf31300341..8babb33d15 100644
--- a/crates/driver/src/domain/liquidity/balancer/v2/weighted.rs
+++ b/crates/driver/src/domain/liquidity/balancer/v2/weighted.rs
@@ -57,7 +57,7 @@ pub struct Reserves(Vec);
impl Reserves {
/// Creates new Balancer V2 token reserves, returns `Err` if the specified
/// token reserves are invalid.
- pub fn new(reserves: Vec) -> Result {
+ pub fn try_new(reserves: Vec) -> Result {
if !reserves.iter().map(|r| r.asset.token).all_unique() {
return Err(InvalidReserves::DuplicateToken);
}
diff --git a/crates/driver/src/domain/liquidity/mod.rs b/crates/driver/src/domain/liquidity/mod.rs
index 4f5d729fb9..2544958ec0 100644
--- a/crates/driver/src/domain/liquidity/mod.rs
+++ b/crates/driver/src/domain/liquidity/mod.rs
@@ -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 {
+ pub fn try_new(a: eth::TokenAddress, b: eth::TokenAddress) -> Result {
match a.cmp(&b) {
Ordering::Less => Ok(Self(a, b)),
Ordering::Equal => Err(InvalidTokenPair),
diff --git a/crates/driver/src/domain/liquidity/swapr.rs b/crates/driver/src/domain/liquidity/swapr.rs
index 689be3361d..fd96d584af 100644
--- a/crates/driver/src/domain/liquidity/swapr.rs
+++ b/crates/driver/src/domain/liquidity/swapr.rs
@@ -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 {
+ pub fn try_new(bps: u32) -> Result {
if !(0..=1000).contains(&bps) {
return Err(InvalidFee);
}
diff --git a/crates/driver/src/domain/liquidity/uniswap/v2.rs b/crates/driver/src/domain/liquidity/uniswap/v2.rs
index 7b24130688..4aadc47622 100644
--- a/crates/driver/src/domain/liquidity/uniswap/v2.rs
+++ b/crates/driver/src/domain/liquidity/uniswap/v2.rs
@@ -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 {
+ pub fn try_new(a: eth::Asset, b: eth::Asset) -> Result {
match a.token.cmp(&b.token) {
Ordering::Less => Ok(Self(a, b)),
Ordering::Equal => Err(InvalidReserves),
diff --git a/crates/driver/src/domain/mempools.rs b/crates/driver/src/domain/mempools.rs
index e5c73545a7..3d4ed86135 100644
--- a/crates/driver/src/domain/mempools.rs
+++ b/crates/driver/src/domain/mempools.rs
@@ -33,7 +33,7 @@ pub struct Mempools {
}
impl Mempools {
- pub fn new(mempools: Vec, ethereum: Ethereum) -> Result {
+ pub fn try_new(mempools: Vec, ethereum: Ethereum) -> Result {
if mempools.is_empty() {
Err(NoMempools)
} else {
diff --git a/crates/driver/src/domain/quote.rs b/crates/driver/src/domain/quote.rs
index cbb2776bc2..75aa0aecf7 100644
--- a/crates/driver/src/domain/quote.rs
+++ b/crates/driver/src/domain/quote.rs
@@ -36,7 +36,7 @@ pub struct Quote {
}
impl Quote {
- fn new(eth: &Ethereum, solution: competition::Solution) -> Result {
+ fn try_new(eth: &Ethereum, solution: competition::Solution) -> Result {
Ok(Self {
clearing_prices: solution
.clearing_prices()
@@ -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
@@ -226,7 +226,7 @@ impl Order {
/// Returns the token pairs to fetch liquidity for.
fn liquidity_pairs(&self) -> HashSet {
- 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()
}
@@ -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 {
+ pub fn try_new(sell: eth::TokenAddress, buy: eth::TokenAddress) -> Result {
if sell == buy {
return Err(SameTokens);
}
diff --git a/crates/driver/src/infra/api/routes/quote/dto/order.rs b/crates/driver/src/infra/api/routes/quote/dto/order.rs
index 81feb86cfa..fbc27ae160 100644
--- a/crates/driver/src/infra/api/routes/quote/dto/order.rs
+++ b/crates/driver/src/infra/api/routes/quote/dto/order.rs
@@ -11,7 +11,7 @@ use {
impl Order {
pub fn into_domain(self, timeouts: Timeouts) -> Result {
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 {
diff --git a/crates/driver/src/infra/blockchain/mod.rs b/crates/driver/src/infra/blockchain/mod.rs
index 0ec0938797..a43a037bfe 100644
--- a/crates/driver/src/infra/blockchain/mod.rs
+++ b/crates/driver/src/infra/blockchain/mod.rs
@@ -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 {
+ pub async fn try_new(url: &url::Url) -> Result {
let web3 = boundary::buffered_web3_client(url);
let chain = Chain::try_from(web3.eth().chain_id().await?)?;
diff --git a/crates/driver/src/infra/liquidity/fetcher.rs b/crates/driver/src/infra/liquidity/fetcher.rs
index 003b51b798..7ac7cd8129 100644
--- a/crates/driver/src/infra/liquidity/fetcher.rs
+++ b/crates/driver/src/infra/liquidity/fetcher.rs
@@ -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 {
+ pub async fn try_new(eth: &Ethereum, config: &infra::liquidity::Config) -> Result {
let eth = eth.with_metric_label("liquidity".into());
- let inner = boundary::liquidity::Fetcher::new(ð, config).await?;
+ let inner = boundary::liquidity::Fetcher::try_new(ð, config).await?;
Ok(Self {
inner: Arc::new(inner),
})
diff --git a/crates/driver/src/infra/solver/mod.rs b/crates/driver/src/infra/solver/mod.rs
index 421a2036a1..37aa96ef26 100644
--- a/crates/driver/src/infra/solver/mod.rs
+++ b/crates/driver/src/infra/solver/mod.rs
@@ -130,7 +130,7 @@ pub struct Config {
}
impl Solver {
- pub async fn new(config: Config, eth: Ethereum) -> Result {
+ pub async fn try_new(config: Config, eth: Ethereum) -> Result {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::CONTENT_TYPE,
diff --git a/crates/driver/src/run.rs b/crates/driver/src/run.rs
index 5d52e0accf..bf21134a52 100644
--- a/crates/driver/src/run.rs
+++ b/crates/driver/src/run.rs
@@ -55,7 +55,7 @@ async fn run_with(args: cli::Args, addr_sender: Option Simulator {
}
async fn ethrpc(args: &cli::Args) -> blockchain::Rpc {
- blockchain::Rpc::new(&args.ethrpc)
+ blockchain::Rpc::try_new(&args.ethrpc)
.await
.expect("connect ethereum RPC")
}
@@ -153,14 +153,16 @@ async fn solvers(config: &config::Config, eth: &Ethereum) -> Vec {
config
.solvers
.iter()
- .map(|config| async move { Solver::new(config.clone(), eth.clone()).await.unwrap() })
+ .map(
+ |config| async move { Solver::try_new(config.clone(), eth.clone()).await.unwrap() },
+ )
.collect::>(),
)
.await
}
async fn liquidity(config: &config::Config, eth: &Ethereum) -> liquidity::Fetcher {
- liquidity::Fetcher::new(eth, &config.liquidity)
+ liquidity::Fetcher::try_new(eth, &config.liquidity)
.await
.expect("initialize liquidity fetcher")
}
diff --git a/crates/driver/src/tests/setup/solver.rs b/crates/driver/src/tests/setup/solver.rs
index a53ea3d1b3..3b4ea924ee 100644
--- a/crates/driver/src/tests/setup/solver.rs
+++ b/crates/driver/src/tests/setup/solver.rs
@@ -408,7 +408,7 @@ impl Solver {
.collect::>();
let url = config.blockchain.web3_url.parse().unwrap();
- let rpc = infra::blockchain::Rpc::new(&url).await.unwrap();
+ let rpc = infra::blockchain::Rpc::try_new(&url).await.unwrap();
let gas = Arc::new(
infra::blockchain::GasPriceEstimator::new(
rpc.web3(),
diff --git a/crates/orderbook/src/database/mod.rs b/crates/orderbook/src/database/mod.rs
index 25d10f8c17..ed5d72e1fd 100644
--- a/crates/orderbook/src/database/mod.rs
+++ b/crates/orderbook/src/database/mod.rs
@@ -30,7 +30,7 @@ pub struct Postgres {
// methods.
impl Postgres {
- pub fn new(uri: &str) -> Result {
+ pub fn try_new(uri: &str) -> Result {
Ok(Self {
pool: PgPool::connect_lazy(uri)?,
})
diff --git a/crates/orderbook/src/database/orders.rs b/crates/orderbook/src/database/orders.rs
index 938389b210..d077b1c8a2 100644
--- a/crates/orderbook/src/database/orders.rs
+++ b/crates/orderbook/src/database/orders.rs
@@ -913,7 +913,7 @@ mod tests {
async fn postgres_replace_order() {
let owner = H160([0x77; 20]);
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let old_order = Order {
@@ -979,7 +979,7 @@ mod tests {
async fn postgres_replace_order_no_cancellation_on_error() {
let owner = H160([0x77; 20]);
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let old_order = Order {
@@ -1023,7 +1023,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn postgres_presignature_status() {
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let uid = OrderUid([0u8; 56]);
let order = Order {
@@ -1096,7 +1096,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn postgres_cancel_orders() {
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
// Define some helper closures to make the test easier to read.
@@ -1145,7 +1145,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn postgres_insert_orders_with_interactions() {
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let interaction = |byte: u8| InteractionData {
@@ -1198,7 +1198,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn postgres_insert_orders_with_interactions_and_verified() {
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let uid = OrderUid([0x42; 56]);
diff --git a/crates/orderbook/src/database/solver_competition.rs b/crates/orderbook/src/database/solver_competition.rs
index 00d4bb9704..62dc18234b 100644
--- a/crates/orderbook/src/database/solver_competition.rs
+++ b/crates/orderbook/src/database/solver_competition.rs
@@ -94,7 +94,7 @@ mod tests {
#[tokio::test]
#[ignore]
async fn not_found_error() {
- let db = Postgres::new("postgresql://").unwrap();
+ let db = Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&db.pool).await.unwrap();
let result = db
diff --git a/crates/orderbook/src/orderbook.rs b/crates/orderbook/src/orderbook.rs
index 2b4a6251c4..eabf66518c 100644
--- a/crates/orderbook/src/orderbook.rs
+++ b/crates/orderbook/src/orderbook.rs
@@ -600,7 +600,7 @@ mod tests {
))
});
- let database = crate::database::Postgres::new("postgresql://").unwrap();
+ let database = crate::database::Postgres::try_new("postgresql://").unwrap();
database::clear_DANGER(&database.pool).await.unwrap();
database.insert_order(&old_order, None).await.unwrap();
let app_data = Arc::new(crate::app_data::Registry::new(
diff --git a/crates/orderbook/src/run.rs b/crates/orderbook/src/run.rs
index 6922a6e77f..e1824713db 100644
--- a/crates/orderbook/src/run.rs
+++ b/crates/orderbook/src/run.rs
@@ -139,7 +139,7 @@ pub async fn run(args: Arguments) {
.await
.expect("Deployed contract constants don't match the ones in this binary");
let domain_separator = DomainSeparator::new(chain_id, settlement_contract.address());
- let postgres = Postgres::new(args.db_url.as_str()).expect("failed to create database");
+ let postgres = Postgres::try_new(args.db_url.as_str()).expect("failed to create database");
let balance_fetcher = account_balances::fetcher(
&web3,
diff --git a/crates/shared/src/external_prices.rs b/crates/shared/src/external_prices.rs
index 95109e318e..f7fb0b427b 100644
--- a/crates/shared/src/external_prices.rs
+++ b/crates/shared/src/external_prices.rs
@@ -22,7 +22,7 @@ pub struct ExternalPrices(HashMap);
impl ExternalPrices {
/// Creates a new set of external prices for the specified exchange rates.
- pub fn new(native_token: H160, mut xrates: HashMap) -> Result {
+ pub fn try_new(native_token: H160, mut xrates: HashMap) -> Result {
// Make sure to verify our invariant that native asset price and native
// wrapped asset price exist with a value of 1. This protects us from
// malformed input (in case there are issues with the prices from the
@@ -48,7 +48,7 @@ impl ExternalPrices {
native_token: H160,
prices: BTreeMap,
) -> Result {
- Self::new(
+ Self::try_new(
native_token,
prices
.into_iter()
@@ -68,7 +68,7 @@ impl ExternalPrices {
impl Default for ExternalPrices {
fn default() -> Self {
- Self::new(Default::default(), Default::default()).unwrap()
+ Self::try_new(Default::default(), Default::default()).unwrap()
}
}
diff --git a/crates/shared/src/macros.rs b/crates/shared/src/macros.rs
index 55c9930219..645ee0629c 100644
--- a/crates/shared/src/macros.rs
+++ b/crates/shared/src/macros.rs
@@ -36,7 +36,7 @@ macro_rules! json_map {
#[macro_export]
macro_rules! externalprices {
(native_token: $nt:expr $(, $($t:tt)*)?) => {
- $crate::external_prices::ExternalPrices::new(
+ $crate::external_prices::ExternalPrices::try_new(
$nt,
::maplit::hashmap!($($($t)*)*),
)
diff --git a/crates/shared/src/sources/balancer_v2/graph_api.rs b/crates/shared/src/sources/balancer_v2/graph_api.rs
index 671058d330..e9cc15ac1a 100644
--- a/crates/shared/src/sources/balancer_v2/graph_api.rs
+++ b/crates/shared/src/sources/balancer_v2/graph_api.rs
@@ -35,7 +35,7 @@ pub struct BalancerSubgraphClient(SubgraphClient);
impl BalancerSubgraphClient {
/// Creates a new Balancer subgraph client with full subgraph URL.
pub fn from_subgraph_url(subgraph_url: &Url, client: Client) -> Result {
- Ok(Self(SubgraphClient::new(subgraph_url.clone(), client)?))
+ Ok(Self(SubgraphClient::try_new(subgraph_url.clone(), client)?))
}
/// Retrieves the list of registered pools from the subgraph.
diff --git a/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs b/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs
index d31de8f4d4..ae3d256e38 100644
--- a/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs
+++ b/crates/shared/src/sources/balancer_v2/pool_fetching/mod.rs
@@ -229,7 +229,7 @@ pub struct BalancerContracts {
}
impl BalancerContracts {
- pub async fn new(web3: &Web3, factory_kinds: Vec) -> Result {
+ pub async fn try_new(web3: &Web3, factory_kinds: Vec) -> Result {
let web3 = ethrpc::instrumented::instrument_with_label(web3, "balancerV2".into());
let vault = BalancerV2Vault::deployed(&web3)
.await
diff --git a/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs b/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs
index 927ed0c8a9..92f9c2799f 100644
--- a/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs
+++ b/crates/shared/src/sources/balancer_v2/pools/composable_stable.rs
@@ -66,7 +66,7 @@ impl FactoryIndexing for BalancerV2ComposableStablePoolFactory {
)?;
let amplification_parameter = {
let (factor, _, precision) = amplification_parameter;
- AmplificationParameter::new(factor, precision)?
+ AmplificationParameter::try_new(factor, precision)?
};
Ok(Some(PoolState {
diff --git a/crates/shared/src/sources/balancer_v2/pools/stable.rs b/crates/shared/src/sources/balancer_v2/pools/stable.rs
index 4e38fd3c24..6c45b4ed79 100644
--- a/crates/shared/src/sources/balancer_v2/pools/stable.rs
+++ b/crates/shared/src/sources/balancer_v2/pools/stable.rs
@@ -48,7 +48,7 @@ pub struct AmplificationParameter {
}
impl AmplificationParameter {
- pub fn new(factor: U256, precision: U256) -> Result {
+ pub fn try_new(factor: U256, precision: U256) -> Result {
ensure!(!precision.is_zero(), "Zero precision not allowed");
Ok(Self { factor, precision })
}
@@ -106,7 +106,7 @@ impl FactoryIndexing for BalancerV2StablePoolFactoryV2 {
futures::try_join!(fetch_common, fetch_amplification_parameter)?;
let amplification_parameter = {
let (factor, _, precision) = amplification_parameter;
- AmplificationParameter::new(factor, precision)?
+ AmplificationParameter::try_new(factor, precision)?
};
Ok(Some(PoolState {
@@ -155,21 +155,21 @@ mod tests {
#[test]
fn amplification_parameter_conversions() {
assert_eq!(
- AmplificationParameter::new(2.into(), 3.into())
+ AmplificationParameter::try_new(2.into(), 3.into())
.unwrap()
.with_base(1000.into())
.unwrap(),
666.into()
);
assert_eq!(
- AmplificationParameter::new(7.into(), 8.into())
+ AmplificationParameter::try_new(7.into(), 8.into())
.unwrap()
.as_big_rational(),
BigRational::new(7.into(), 8.into())
);
assert_eq!(
- AmplificationParameter::new(1.into(), 0.into())
+ AmplificationParameter::try_new(1.into(), 0.into())
.unwrap_err()
.to_string(),
"Zero precision not allowed"
diff --git a/crates/shared/src/sources/balancer_v2/swap/mod.rs b/crates/shared/src/sources/balancer_v2/swap/mod.rs
index 96f81308df..fc06c66196 100644
--- a/crates/shared/src/sources/balancer_v2/swap/mod.rs
+++ b/crates/shared/src/sources/balancer_v2/swap/mod.rs
@@ -517,7 +517,7 @@ mod tests {
let pool = create_stable_pool_with(
tokens.clone(),
balances,
- AmplificationParameter::new(1.into(), 1.into()).unwrap(),
+ AmplificationParameter::try_new(1.into(), 1.into()).unwrap(),
vec![Bfp::exp10(18), Bfp::exp10(18), Bfp::exp10(18)],
1.into(),
);
@@ -559,7 +559,7 @@ mod tests {
let tokens = vec![dai, usdc, tusd];
let scaling_exps = vec![Bfp::exp10(0), Bfp::exp10(12), Bfp::exp10(12)];
let amplification_parameter =
- AmplificationParameter::new(570000.into(), 1000.into()).unwrap();
+ AmplificationParameter::try_new(570000.into(), 1000.into()).unwrap();
let balances = vec![
40_927_687_702_846_622_465_144_342_i128.into(),
59_448_574_675_062_i128.into(),
@@ -592,7 +592,7 @@ mod tests {
let tokens = vec![dai, usdc, tusd];
let scaling_exps = vec![Bfp::exp10(0), Bfp::exp10(12), Bfp::exp10(12)];
let amplification_parameter =
- AmplificationParameter::new(570000.into(), 1000.into()).unwrap();
+ AmplificationParameter::try_new(570000.into(), 1000.into()).unwrap();
let balances = vec![
34_869_494_603_218_073_631_628_580_i128.into(),
48_176_005_970_419_i128.into(),
diff --git a/crates/shared/src/sources/uniswap_v3/graph_api.rs b/crates/shared/src/sources/uniswap_v3/graph_api.rs
index a720aa9097..c7beff509c 100644
--- a/crates/shared/src/sources/uniswap_v3/graph_api.rs
+++ b/crates/shared/src/sources/uniswap_v3/graph_api.rs
@@ -108,7 +108,7 @@ pub struct UniV3SubgraphClient(SubgraphClient);
impl UniV3SubgraphClient {
/// Creates a new Uniswap V3 subgraph client from the specified URL.
pub fn from_subgraph_url(subgraph_url: &Url, client: Client) -> Result {
- Ok(Self(SubgraphClient::new(subgraph_url.clone(), client)?))
+ Ok(Self(SubgraphClient::try_new(subgraph_url.clone(), client)?))
}
async fn get_pools(&self, query: &str, variables: Map) -> Result> {
diff --git a/crates/shared/src/subgraph.rs b/crates/shared/src/subgraph.rs
index 2f2b077621..36d89bae71 100644
--- a/crates/shared/src/subgraph.rs
+++ b/crates/shared/src/subgraph.rs
@@ -29,7 +29,7 @@ pub struct Data {
impl SubgraphClient {
/// Creates a new subgraph client from the specified organization and name.
- pub fn new(subgraph_url: Url, client: Client) -> Result {
+ pub fn try_new(subgraph_url: Url, client: Client) -> Result {
Ok(Self {
client,
subgraph_url,
diff --git a/crates/solver/src/liquidity/balancer_v2.rs b/crates/solver/src/liquidity/balancer_v2.rs
index c56cefb504..697539258c 100644
--- a/crates/solver/src/liquidity/balancer_v2.rs
+++ b/crates/solver/src/liquidity/balancer_v2.rs
@@ -339,7 +339,7 @@ mod tests {
swap_fee: "0.002".parse().unwrap(),
paused: true,
},
- amplification_parameter: AmplificationParameter::new(1.into(), 1.into()).unwrap(),
+ amplification_parameter: AmplificationParameter::try_new(1.into(), 1.into()).unwrap(),
reserves: btreemap! {
H160([0x73; 20]) => TokenState {
balance: 1_000_000_000_000_000_000u128.into(),
diff --git a/crates/solvers/src/boundary/liquidity/stable.rs b/crates/solvers/src/boundary/liquidity/stable.rs
index feec338b94..7a634ab2b0 100644
--- a/crates/solvers/src/boundary/liquidity/stable.rs
+++ b/crates/solvers/src/boundary/liquidity/stable.rs
@@ -35,7 +35,7 @@ pub fn to_boundary_pool(address: H160, pool: &liquidity::stable::Pool) -> Option
))
})
.collect::