Skip to content

Commit

Permalink
feat: Remove fee_ticker and token_trading_volume fetcher modules (#262)
Browse files Browse the repository at this point in the history
# What ❔

- Removes `fee_ticker` module.
- Removes `token_trading_volume` fetcher.
- Removes some (now unused) methods from DAL.
- Removes some (now unused) types.

## Why ❔

Dead code.

## Checklist

<!-- Check your PR fulfills the following items. -->
<!-- For draft PRs check the boxes as you complete them. -->

- [x] PR title corresponds to the body of PR (we generate changelog
entries from PRs).
- [ ] ~~Tests for the changes have been added / updated.~~
- [ ] ~~Documentation comments have been added / updated.~~
- [x] Code has been formatted via `zk fmt` and `zk lint`.
  • Loading branch information
popzxc committed Oct 20, 2023
1 parent feb8a6c commit 44f7179
Show file tree
Hide file tree
Showing 15 changed files with 19 additions and 699 deletions.
95 changes: 0 additions & 95 deletions core/lib/dal/sqlx-data.json
Original file line number Diff line number Diff line change
Expand Up @@ -2712,38 +2712,6 @@
},
"query": "INSERT INTO eth_txs_history\n (eth_tx_id, base_fee_per_gas, priority_fee_per_gas, tx_hash, signed_raw_tx, created_at, updated_at, confirmed_at)\n VALUES ($1, 0, 0, $2, '\\x00', now(), now(), $3)\n RETURNING id"
},
"393345441797999e9f11b8b5ddce0b64356e1e167056d7f76ef6dfffd3534607": {
"describe": {
"columns": [
{
"name": "name!",
"ordinal": 0,
"type_info": "Varchar"
},
{
"name": "symbol!",
"ordinal": 1,
"type_info": "Varchar"
},
{
"name": "decimals!",
"ordinal": 2,
"type_info": "Int4"
}
],
"nullable": [
null,
null,
null
],
"parameters": {
"Left": [
"Bytea"
]
}
},
"query": "\n SELECT\n COALESCE(token_list_name, name) as \"name!\",\n COALESCE(token_list_symbol, symbol) as \"symbol!\",\n COALESCE(token_list_decimals, decimals) as \"decimals!\"\n FROM tokens WHERE l2_address = $1\n "
},
"394bbd64939d47fda4e1545e2752b208901e872b7234a5c3af456bdf429a6074": {
"describe": {
"columns": [
Expand Down Expand Up @@ -3003,20 +2971,6 @@
},
"query": "DELETE FROM events WHERE miniblock_number > $1"
},
"3de5668eca2211f9701304e374100d45b359b1f7832d4a30b325fa679012c3e7": {
"describe": {
"columns": [],
"nullable": [],
"parameters": {
"Left": [
"Bytea",
"Numeric",
"Timestamp"
]
}
},
"query": "UPDATE tokens SET market_volume = $2, market_volume_updated_at = $3, updated_at = now() WHERE l1_address = $1"
},
"3f6332706376ef4cadda96498872429b6ed28eca5402b03b1aa3b77b8262bccd": {
"describe": {
"columns": [],
Expand Down Expand Up @@ -7691,29 +7645,6 @@
},
"query": "SELECT l1_batch_number FROM initial_writes WHERE hashed_key = $1"
},
"a9b7a880dbde4f7de5a6c2ff4009281527f2d01a547228981af3af2129ffb3f7": {
"describe": {
"columns": [
{
"name": "count!",
"ordinal": 0,
"type_info": "Int8"
}
],
"nullable": [
null
],
"parameters": {
"Left": [
"Bytea",
"Numeric",
"Interval",
"Interval"
]
}
},
"query": "\n SELECT COUNT(*) as \"count!\" FROM tokens\n WHERE l2_address = $1 AND\n market_volume > $2 AND now() - market_volume_updated_at < $3 AND\n usd_price > 0 AND now() - usd_price_updated_at < $4\n "
},
"a9d96d6774af2637173d471f02995652cd4c131c05fdcb3d0e1644bcd1aa1809": {
"describe": {
"columns": [
Expand Down Expand Up @@ -7985,32 +7916,6 @@
},
"query": "\n UPDATE scheduler_witness_jobs\n SET aggregation_result_coords = $1,\n updated_at = now()\n WHERE l1_batch_number = $2\n "
},
"adc9ad2c944f9dacc28b5bd133aa37d9e8ea99eca1c5dfbeef37cda4b793f434": {
"describe": {
"columns": [
{
"name": "market_volume",
"ordinal": 0,
"type_info": "Numeric"
},
{
"name": "market_volume_updated_at",
"ordinal": 1,
"type_info": "Timestamp"
}
],
"nullable": [
true,
true
],
"parameters": {
"Left": [
"Bytea"
]
}
},
"query": "SELECT market_volume, market_volume_updated_at FROM tokens WHERE l2_address = $1"
},
"ae072f51b65d0b5212264be9a34027922e5aedef7e4741517ad8104bf5aa79e9": {
"describe": {
"columns": [],
Expand Down
42 changes: 1 addition & 41 deletions core/lib/dal/src/models/storage_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,9 @@ use sqlx::types::{
BigDecimal,
};

use zksync_types::tokens::{TokenMarketVolume, TokenMetadata, TokenPrice};
use zksync_types::tokens::TokenPrice;
use zksync_utils::big_decimal_to_ratio;

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StorageTokenMetadata {
pub name: String,
pub symbol: String,
pub decimals: i32,
}

impl From<StorageTokenMetadata> for TokenMetadata {
fn from(metadata: StorageTokenMetadata) -> TokenMetadata {
TokenMetadata {
name: metadata.name,
symbol: metadata.symbol,
decimals: metadata.decimals as u8,
}
}
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StorageTokenPrice {
pub usd_price: Option<BigDecimal>,
Expand All @@ -48,26 +31,3 @@ impl From<StorageTokenPrice> for Option<TokenPrice> {
}
}
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StorageTokenMarketVolume {
pub market_volume: Option<BigDecimal>,
pub market_volume_updated_at: Option<NaiveDateTime>,
}

impl From<StorageTokenMarketVolume> for Option<TokenMarketVolume> {
fn from(market_volume: StorageTokenMarketVolume) -> Option<TokenMarketVolume> {
market_volume
.market_volume
.as_ref()
.map(|volume| TokenMarketVolume {
market_volume: big_decimal_to_ratio(volume).unwrap(),
last_updated: DateTime::<Utc>::from_naive_utc_and_offset(
market_volume
.market_volume_updated_at
.expect("If `market_volume` is Some then `updated_at` must be Some"),
Utc,
),
})
}
}
38 changes: 1 addition & 37 deletions core/lib/dal/src/tokens_dal.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use crate::models::storage_token::StorageTokenMarketVolume;
use crate::StorageProcessor;
use num::{rational::Ratio, BigUint};
use sqlx::types::chrono::Utc;
use zksync_types::{
tokens::{TokenInfo, TokenMarketVolume, TokenMetadata, TokenPrice},
tokens::{TokenInfo, TokenMetadata, TokenPrice},
Address, MiniblockNumber, ACCOUNT_CODE_STORAGE_ADDRESS,
FAILED_CONTRACT_DEPLOYMENT_BYTECODE_HASH,
};
Expand Down Expand Up @@ -158,41 +157,6 @@ impl TokensDal<'_, '_> {
}
}

pub async fn set_l1_token_market_volume(
&mut self,
l1_address: &Address,
market_volume: TokenMarketVolume,
) {
{
sqlx::query!(
"UPDATE tokens SET market_volume = $2, market_volume_updated_at = $3, updated_at = now() WHERE l1_address = $1",
l1_address.as_bytes(),
ratio_to_big_decimal(&market_volume.market_volume, STORED_USD_PRICE_PRECISION),
market_volume.last_updated.naive_utc(),
)
.execute(self.storage.conn())
.await
.unwrap();
}
}

pub async fn get_token_market_volume(
&mut self,
l2_address: &Address,
) -> Option<TokenMarketVolume> {
{
let storage_market_volume = sqlx::query_as!(
StorageTokenMarketVolume,
"SELECT market_volume, market_volume_updated_at FROM tokens WHERE l2_address = $1",
l2_address.as_bytes(),
)
.fetch_optional(self.storage.conn())
.await
.unwrap();
storage_market_volume.and_then(Into::into)
}
}

pub async fn rollback_tokens(&mut self, block_number: MiniblockNumber) {
{
sqlx::query!(
Expand Down
70 changes: 1 addition & 69 deletions core/lib/dal/src/tokens_web3_dal.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
use crate::models::storage_token::{StorageTokenMetadata, StorageTokenPrice};
use crate::models::storage_token::StorageTokenPrice;
use crate::SqlxError;
use crate::StorageProcessor;
use num::{rational::Ratio, BigUint};
use sqlx::postgres::types::PgInterval;
use zksync_types::{
tokens::{TokenInfo, TokenMetadata, TokenPrice},
Address,
};
use zksync_utils::ratio_to_big_decimal;

// Precision of the USD price per token
pub(crate) const STORED_USD_PRICE_PRECISION: usize = 6;

#[derive(Debug)]
pub struct TokensWeb3Dal<'a, 'c> {
Expand Down Expand Up @@ -43,45 +37,6 @@ impl TokensWeb3Dal<'_, '_> {
}
}

pub async fn is_token_actively_trading(
&mut self,
l2_token: &Address,
min_volume: &Ratio<BigUint>,
max_acceptable_volume_age_in_secs: u32,
max_acceptable_price_age_in_secs: u32,
) -> Result<bool, SqlxError> {
{
let min_volume = ratio_to_big_decimal(min_volume, STORED_USD_PRICE_PRECISION);
let volume_pg_interval = PgInterval {
months: 0,
days: 0,
microseconds: (max_acceptable_volume_age_in_secs as i64) * 1000000,
};
let price_pg_interval = PgInterval {
months: 0,
days: 0,
microseconds: (max_acceptable_price_age_in_secs as i64) * 1000000,
};
let count = sqlx::query!(
r#"
SELECT COUNT(*) as "count!" FROM tokens
WHERE l2_address = $1 AND
market_volume > $2 AND now() - market_volume_updated_at < $3 AND
usd_price > 0 AND now() - usd_price_updated_at < $4
"#,
l2_token.as_bytes(),
min_volume,
volume_pg_interval,
price_pg_interval
)
.fetch_one(self.storage.conn())
.await
.unwrap()
.count;
Ok(count == 1)
}
}

pub async fn get_token_price(
&mut self,
l2_address: &Address,
Expand All @@ -98,27 +53,4 @@ impl TokensWeb3Dal<'_, '_> {
Ok(storage_price.and_then(Into::into))
}
}

pub async fn get_token_metadata(
&mut self,
l2_address: &Address,
) -> Result<Option<TokenMetadata>, SqlxError> {
{
let storage_token_metadata = sqlx::query_as!(
StorageTokenMetadata,
r#"
SELECT
COALESCE(token_list_name, name) as "name!",
COALESCE(token_list_symbol, symbol) as "symbol!",
COALESCE(token_list_decimals, decimals) as "decimals!"
FROM tokens WHERE l2_address = $1
"#,
l2_address.as_bytes(),
)
.fetch_optional(self.storage.conn())
.await?;

Ok(storage_token_metadata.map(Into::into))
}
}
}
8 changes: 0 additions & 8 deletions core/lib/types/src/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,3 @@ pub struct TokenPrice {
pub usd_price: Ratio<BigUint>,
pub last_updated: DateTime<Utc>,
}

/// Token price known to the zkSync network.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenMarketVolume {
#[serde(with = "UnsignedRatioSerializeAsDecimal")]
pub market_volume: Ratio<BigUint>,
pub last_updated: DateTime<Utc>,
}
27 changes: 16 additions & 11 deletions core/lib/zksync_core/src/api_server/web3/namespaces/zks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use zksync_types::{
L1BatchNumber, MiniblockNumber, Transaction, L1_MESSENGER_ADDRESS, L2_ETH_TOKEN_ADDRESS,
MAX_GAS_PER_PUBDATA_BYTE, REQUIRED_L1_TO_L2_GAS_PER_PUBDATA_BYTE, U256, U64,
};
use zksync_utils::address_to_h256;
use zksync_utils::{address_to_h256, ratio_to_big_decimal_normalized};
use zksync_web3_decl::{
error::Web3Error,
types::{Address, Filter, Log, Token, H256},
Expand All @@ -27,7 +27,6 @@ use zksync_web3_decl::{
use crate::api_server::web3::{
backend_jsonrpc::error::internal_error, metrics::API_METRICS, RpcState,
};
use crate::fee_ticker::{error::TickerError, FeeTicker, TokenPriceRequestType};
use crate::l1_gas_price::L1GasPriceProvider;

#[derive(Debug)]
Expand Down Expand Up @@ -178,6 +177,13 @@ impl<G: L1GasPriceProvider> ZksNamespace<G> {
pub async fn get_token_price_impl(&self, l2_token: Address) -> Result<BigDecimal, Web3Error> {
const METHOD_NAME: &str = "get_token_price";

/// Amount of possible symbols after the decimal dot in the USD.
/// Used to convert `Ratio<BigUint>` to `BigDecimal`.
const USD_PRECISION: usize = 100;
/// Minimum amount of symbols after the decimal dot in the USD.
/// Used to convert `Ratio<BigUint>` to `BigDecimal`.
const MIN_PRECISION: usize = 2;

let method_latency = API_METRICS.start_call(METHOD_NAME);
let token_price_result = {
let mut storage = self
Expand All @@ -186,20 +192,19 @@ impl<G: L1GasPriceProvider> ZksNamespace<G> {
.access_storage_tagged("api")
.await
.unwrap();
let mut tokens_web3_dal = storage.tokens_web3_dal();
FeeTicker::get_l2_token_price(
&mut tokens_web3_dal,
TokenPriceRequestType::USDForOneToken,
&l2_token,
)
.await
storage.tokens_web3_dal().get_token_price(&l2_token).await
};

let result = match token_price_result {
Ok(price) => Ok(price),
Err(TickerError::PriceNotTracked(_)) => Ok(BigDecimal::zero()),
Ok(Some(price)) => Ok(ratio_to_big_decimal_normalized(
&price.usd_price,
USD_PRECISION,
MIN_PRECISION,
)),
Ok(None) => Ok(BigDecimal::zero()),
Err(err) => Err(internal_error(METHOD_NAME, err)),
};

method_latency.observe();
result
}
Expand Down

0 comments on commit 44f7179

Please sign in to comment.