Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace once-cell and lazy-static with std types #3208

Merged
merged 2 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@ humantime-serde = "1.1.1"
hyper = "0.14.29"
indexmap = "2.2.6"
itertools = "0.12.1"
lazy_static = "1.4.0"
maplit = "1.0.2"
mockall = "0.12.1"
num = "0.4.3"
once_cell = "1.19.0"
primitive-types = "0.12"
prometheus = "0.13.4"
prometheus-metric-storage = "0.5.0"
Expand Down
1 change: 0 additions & 1 deletion crates/driver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ hex-literal = { workspace = true }
humantime = { workspace = true }
humantime-serde = { workspace = true }
hyper = { workspace = true }
lazy_static = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
itertools = { workspace = true }
mimalloc = { workspace = true }
Expand Down
6 changes: 3 additions & 3 deletions crates/driver/src/infra/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub fn now() -> chrono::DateTime<chrono::Utc> {
/// During tests, the time is fixed.
#[cfg(test)]
pub fn now() -> chrono::DateTime<chrono::Utc> {
use std::sync::OnceLock;
static TIME: OnceLock<chrono::DateTime<chrono::Utc>> = OnceLock::new();
TIME.get_or_init(chrono::Utc::now).to_owned()
use std::sync::LazyLock;
static TIME: LazyLock<chrono::DateTime<chrono::Utc>> = LazyLock::new(chrono::Utc::now);
*TIME
}
28 changes: 13 additions & 15 deletions crates/e2e/src/api/zeroex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@ use {
autopilot::domain::eth::U256,
chrono::{DateTime, NaiveDateTime, Utc},
driver::domain::eth::H256,
ethcontract::{
common::abi::{encode, Token},
private::lazy_static,
},
ethcontract::common::abi::{encode, Token},
hex_literal::hex,
model::DomainSeparator,
shared::{
zeroex_api,
zeroex_api::{Order, OrderMetadata, OrderRecord, ZeroExSignature},
},
std::net::SocketAddr,
std::{net::SocketAddr, sync::LazyLock},
warp::{Filter, Reply},
web3::{signing, types::H160},
};
Expand Down Expand Up @@ -155,18 +152,19 @@ struct ZeroExDomainSeparator([u8; 32]);
impl ZeroExDomainSeparator {
// See <https://github.com/0xProject/protocol/blob/%400x/contracts-zero-ex%400.49.0/contracts/zero-ex/contracts/src/fixins/FixinEIP712.sol>
pub fn new(chain_id: u64, contract_addr: H160) -> Self {
lazy_static! {
/// The EIP-712 domain name used for computing the domain separator.
static ref DOMAIN_NAME: [u8; 32] = signing::keccak256(b"ZeroEx");
/// The EIP-712 domain name used for computing the domain separator.
static DOMAIN_NAME: LazyLock<[u8; 32]> = LazyLock::new(|| signing::keccak256(b"ZeroEx"));

/// The EIP-712 domain version used for computing the domain separator.
static ref DOMAIN_VERSION: [u8; 32] = signing::keccak256(b"1.0.0");
/// The EIP-712 domain version used for computing the domain separator.
static DOMAIN_VERSION: LazyLock<[u8; 32]> = LazyLock::new(|| signing::keccak256(b"1.0.0"));

/// The EIP-712 domain type used computing the domain separator.
static DOMAIN_TYPE_HASH: LazyLock<[u8; 32]> = LazyLock::new(|| {
signing::keccak256(
b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
)
});

/// The EIP-712 domain type used computing the domain separator.
static ref DOMAIN_TYPE_HASH: [u8; 32] = signing::keccak256(
b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
);
}
let abi_encode_string = encode(&[
Token::FixedBytes((*DOMAIN_TYPE_HASH).into()),
Token::FixedBytes((*DOMAIN_NAME).into()),
Expand Down
1 change: 0 additions & 1 deletion crates/ethrpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ async-trait = { workspace = true }
futures = { workspace = true }
hex = { workspace = true }
hex-literal = { workspace = true }
lazy_static = { workspace = true }
mockall = { workspace = true }
observe = { path = "../observe" }
primitive-types = { workspace = true }
Expand Down
11 changes: 5 additions & 6 deletions crates/ethrpc/src/multicall.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ use {
tokens::{self, Tokenize as _},
},
hex_literal::hex,
lazy_static::lazy_static,
std::iter,
std::{iter, sync::LazyLock},
web3::{
self,
api::Eth,
Expand Down Expand Up @@ -160,12 +159,12 @@ fn decode(len: usize, return_data: Bytes) -> Vec<Result<Vec<u8>, ExecutionError>
type ReturnData = Vec<(bool, ethcontract::Bytes<Vec<u8>>)>;

fn decode_return_data(len: usize, return_data: Bytes) -> Result<ReturnData, DecodeError> {
lazy_static! {
static ref KIND: [ParamType; 1] = [ParamType::Array(Box::new(ParamType::Tuple(vec![
static KIND: LazyLock<[ParamType; 1]> = LazyLock::new(|| {
[ParamType::Array(Box::new(ParamType::Tuple(vec![
ParamType::Bool,
ParamType::Bytes,
])),)];
}
])))]
});

let tokens = ethabi::decode(&*KIND, &return_data.0)?;
let (results,) = <(ReturnData,)>::from_token(Token::Tuple(tokens))?;
Expand Down
1 change: 0 additions & 1 deletion crates/model/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ chrono = { workspace = true, features = ["serde", "clock"] }
derive_more = { workspace = true }
hex = { workspace = true, default-features = false }
hex-literal = { workspace = true }
lazy_static = { workspace = true }
number = { path = "../number" }
num = { workspace = true }
primitive-types = { workspace = true }
Expand Down
24 changes: 12 additions & 12 deletions crates/model/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ pub mod trade;

use {
hex::{FromHex, FromHexError},
lazy_static::lazy_static,
primitive_types::H160,
std::fmt,
std::{fmt, sync::LazyLock},
web3::{
ethabi::{encode, Token},
signing,
Expand Down Expand Up @@ -115,18 +114,19 @@ impl std::fmt::Debug for DomainSeparator {

impl DomainSeparator {
pub fn new(chain_id: u64, contract_address: H160) -> Self {
lazy_static! {
/// The EIP-712 domain name used for computing the domain separator.
static ref DOMAIN_NAME: [u8; 32] = signing::keccak256(b"Gnosis Protocol");
/// The EIP-712 domain name used for computing the domain separator.
static DOMAIN_NAME: LazyLock<[u8; 32]> =
LazyLock::new(|| signing::keccak256(b"Gnosis Protocol"));

/// The EIP-712 domain version used for computing the domain separator.
static ref DOMAIN_VERSION: [u8; 32] = signing::keccak256(b"v2");
/// The EIP-712 domain version used for computing the domain separator.
static DOMAIN_VERSION: LazyLock<[u8; 32]> = LazyLock::new(|| signing::keccak256(b"v2"));

/// The EIP-712 domain type used computing the domain separator.
static ref DOMAIN_TYPE_HASH: [u8; 32] = signing::keccak256(
b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
);
}
/// The EIP-712 domain type used computing the domain separator.
static DOMAIN_TYPE_HASH: LazyLock<[u8; 32]> = LazyLock::new(|| {
signing::keccak256(
b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
)
});
let abi_encode_string = encode(&[
Token::Uint((*DOMAIN_TYPE_HASH).into()),
Token::Uint((*DOMAIN_NAME).into()),
Expand Down
1 change: 0 additions & 1 deletion crates/observe/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ atty = "0.2"
async-trait = { workspace = true }
console-subscriber = "0.3.0"
futures = { workspace = true }
once_cell = { workspace = true }
pin-project-lite = "0.2.14"
prometheus = { workspace = true }
prometheus-metric-storage = { workspace = true }
Expand Down
10 changes: 7 additions & 3 deletions crates/observe/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
use {
once_cell::sync::OnceCell,
prometheus::Encoder,
std::{collections::HashMap, convert::Infallible, net::SocketAddr, sync::Arc},
std::{
collections::HashMap,
convert::Infallible,
net::SocketAddr,
sync::{Arc, OnceLock},
},
tokio::task::{self, JoinHandle},
warp::{Filter, Rejection, Reply},
};

/// Global metrics registry used by all components.
static REGISTRY: OnceCell<prometheus_metric_storage::StorageRegistry> = OnceCell::new();
static REGISTRY: OnceLock<prometheus_metric_storage::StorageRegistry> = OnceLock::new();

/// Configure global metrics registry.
///
Expand Down
1 change: 0 additions & 1 deletion crates/shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ hex-literal = { workspace = true }
humantime = { workspace = true }
indexmap = { workspace = true }
itertools = { workspace = true }
lazy_static = { workspace = true }
maplit = { workspace = true }
mockall = { workspace = true }
model = { path = "../model" }
Expand Down
10 changes: 5 additions & 5 deletions crates/shared/src/external_prices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ use {
crate::conversions::U256Ext,
anyhow::{bail, Result},
ethcontract::{H160, U256},
lazy_static::lazy_static,
model::order::BUY_ETH_ADDRESS,
num::{BigInt, BigRational, One as _, ToPrimitive as _},
std::collections::{BTreeMap, HashMap},
std::{
collections::{BTreeMap, HashMap},
sync::LazyLock,
},
};

/// A collection of external prices used for converting token amounts to native
Expand Down Expand Up @@ -72,9 +74,7 @@ impl Default for ExternalPrices {
}
}

lazy_static! {
static ref UNIT: BigInt = BigInt::from(1_000_000_000_000_000_000_u128);
}
static UNIT: LazyLock<BigInt> = LazyLock::new(|| BigInt::from(1_000_000_000_000_000_000_u128));

/// Converts a token price from the orderbook API `/auction` endpoint to an
/// native token exchange rate.
Expand Down
5 changes: 2 additions & 3 deletions crates/shared/src/price_estimation/native/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use {
crate::price_estimation::{PriceEstimating, PriceEstimationError, Query},
bigdecimal::{BigDecimal, ToPrimitive},
cached::once_cell::sync::Lazy,
futures::FutureExt,
model::order::OrderKind,
number::nonzero::U256 as NonZeroU256,
primitive_types::{H160, U256},
std::sync::Arc,
std::sync::{Arc, LazyLock},
};

mod coingecko;
Expand All @@ -19,7 +18,7 @@ pub type NativePriceEstimateResult = Result<NativePrice, PriceEstimationError>;

/// Convert from normalized price to floating point price
pub fn from_normalized_price(price: BigDecimal) -> Option<f64> {
static ONE_E18: Lazy<BigDecimal> = Lazy::new(|| BigDecimal::try_from(1e18).unwrap());
static ONE_E18: LazyLock<BigDecimal> = LazyLock::new(|| BigDecimal::try_from(1e18).unwrap());

// Divide by 1e18 to reverse the multiplication by 1e18
let normalized_price = price / ONE_E18.clone();
Expand Down
21 changes: 10 additions & 11 deletions crates/shared/src/sources/balancer_v2/swap/fixed_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ use {
super::error::Error,
anyhow::{bail, ensure, Context, Result},
ethcontract::U256,
lazy_static::lazy_static,
num::{BigInt, BigRational},
number::conversions::{big_int_to_u256, u256_to_big_int},
std::{
convert::TryFrom,
fmt::{self, Debug, Formatter},
str::FromStr,
sync::LazyLock,
},
};

Expand All @@ -27,16 +27,13 @@ mod logexpmath;
/// including error codes, from which the name (Balancer Fixed Point).
pub struct Bfp(U256);

lazy_static! {
static ref ONE_18: U256 = U256::exp10(18);
static ref ONE_18_BIGINT: BigInt = u256_to_big_int(&ONE_18);
static ref ZERO: Bfp = Bfp(U256::zero());
static ref EPSILON: Bfp = Bfp(U256::one());
static ref ONE: Bfp = Bfp(*ONE_18);
static ref TWO: Bfp = Bfp(*ONE_18 * 2);
static ref FOUR: Bfp = Bfp(*ONE_18 * 4);
static ref MAX_POW_RELATIVE_ERROR: Bfp = Bfp(10000_usize.into());
}
static ONE_18: LazyLock<U256> = LazyLock::new(|| U256::exp10(18));
static ONE_18_BIGINT: LazyLock<BigInt> = LazyLock::new(|| u256_to_big_int(&ONE_18));
static ZERO: LazyLock<Bfp> = LazyLock::new(|| Bfp(U256::zero()));
static ONE: LazyLock<Bfp> = LazyLock::new(|| Bfp(*ONE_18));
static TWO: LazyLock<Bfp> = LazyLock::new(|| Bfp(*ONE_18 * 2));
static FOUR: LazyLock<Bfp> = LazyLock::new(|| Bfp(*ONE_18 * 4));
static MAX_POW_RELATIVE_ERROR: LazyLock<Bfp> = LazyLock::new(|| Bfp(10000_usize.into()));

impl From<usize> for Bfp {
fn from(num: usize) -> Self {
Expand Down Expand Up @@ -223,6 +220,8 @@ mod tests {
num::{BigInt, One, Zero},
};

static EPSILON: LazyLock<Bfp> = LazyLock::new(|| Bfp(U256::one()));

#[test]
fn parsing() {
assert_eq!("1".parse::<Bfp>().unwrap(), Bfp::one());
Expand Down
Loading
Loading