Skip to content

Commit

Permalink
Passed ip everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
StanislavBreadless committed Nov 26, 2021
1 parent 372dd05 commit d6d77e3
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 24 deletions.
4 changes: 2 additions & 2 deletions core/bin/zksync_api/src/api_server/rest/v02/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async fn get_tx_fee(
return Error::from(SubmitError::InappropriateFeeToken).into();
}
data.tx_sender
.get_txs_fee_in_wei(body.tx_type.into(), body.address, body.token_like)
.get_txs_fee_in_wei(body.tx_type.into(), body.address, body.token_like, None)
.await
.map_err(Error::from)
.map(ApiFee::from)
Expand All @@ -70,7 +70,7 @@ async fn get_batch_fee(
.map(|tx| (tx.tx_type.into(), tx.address))
.collect();
data.tx_sender
.get_txs_batch_fee_in_wei(txs, body.token_like)
.get_txs_batch_fee_in_wei(txs, body.token_like, None)
.await
.map_err(Error::from)
.map(ApiFee::from)
Expand Down
4 changes: 2 additions & 2 deletions core/bin/zksync_api/src/api_server/rest/v02/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ async fn submit_tx(
) -> ApiResult<TxHashSerializeWrapper> {
let tx_hash = data
.tx_sender
.submit_tx(body.tx, body.signature)
.submit_tx(body.tx, body.signature, None)
.await
.map_err(Error::from);

Expand All @@ -165,7 +165,7 @@ async fn submit_batch(
) -> ApiResult<SubmitBatchResponse> {
let response = data
.tx_sender
.submit_txs_batch(body.txs, body.signature)
.submit_txs_batch(body.txs, body.signature, None)
.await
.map_err(Error::from);
response.into()
Expand Down
4 changes: 4 additions & 0 deletions core/bin/zksync_api/src/api_server/rpc_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,13 +348,15 @@ impl RpcApp {
mut ticker_request_sender: mpsc::Sender<TickerRequest>,
transactions: Vec<(TxFeeTypes, Address)>,
token: TokenLike,
ip: Option<String>,
) -> Result<ResponseBatchFee> {
let req = oneshot::channel();
ticker_request_sender
.send(TickerRequest::GetBatchTxFee {
transactions,
token: token.clone(),
response: req.0,
ip,
})
.await
.expect("ticker receiver dropped");
Expand All @@ -370,6 +372,7 @@ impl RpcApp {
tx_type: TxFeeTypes,
address: Address,
token: TokenLike,
ip: Option<String>,
) -> Result<ResponseFee> {
let req = oneshot::channel();
ticker_request_sender
Expand All @@ -378,6 +381,7 @@ impl RpcApp {
address,
token: token.clone(),
response: req.0,
ip,
})
.await
.expect("ticker receiver dropped");
Expand Down
15 changes: 10 additions & 5 deletions core/bin/zksync_api/src/api_server/rpc_server/rpc_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,14 @@ impl RpcApp {
) -> Result<TxHash> {
let start = Instant::now();

if let Some(ip) = ip {
if let Some(ip) = ip.clone() {
dbg!("IPPPPPPPPPPPPPPP");
dbg!(ip);
}

let result = self
.tx_sender
.submit_tx_with_separate_fp(*tx, *signature, fast_processing)
.submit_tx_with_separate_fp(*tx, *signature, fast_processing, ip)
.await
.map_err(Error::from);
metrics::histogram!("api.rpc.tx_submit", start.elapsed());
Expand All @@ -150,9 +150,10 @@ impl RpcApp {
ip: Option<String>,
) -> Result<Vec<TxHash>> {
let start = Instant::now();

let result: Result<Vec<TxHash>> = self
.tx_sender
.submit_txs_batch(txs, eth_signatures)
.submit_txs_batch(txs, eth_signatures, ip)
.await
.map_err(Error::from)
.map(|response| {
Expand Down Expand Up @@ -248,8 +249,10 @@ impl RpcApp {
if !token_allowed {
return Err(SubmitError::InappropriateFeeToken.into());
}

let result =
Self::ticker_request(ticker.clone(), tx_type.into(), address, token.clone()).await?;
Self::ticker_request(ticker.clone(), tx_type.into(), address, token.clone(), ip)
.await?;

metrics::histogram!("api.rpc.get_tx_fee", start.elapsed());
Ok(result.normal_fee)
Expand Down Expand Up @@ -283,7 +286,9 @@ impl RpcApp {
.map(|fee_type| fee_type.into())
.zip(addresses.iter().cloned()))
.collect();
let result = Self::ticker_batch_fee_request(ticker, transactions, token.clone()).await?;

let result =
Self::ticker_batch_fee_request(ticker, transactions, token.clone(), ip).await?;

metrics::histogram!("api.rpc.get_txs_batch_fee_in_wei", start.elapsed());
Ok(TotalFee {
Expand Down
17 changes: 15 additions & 2 deletions core/bin/zksync_api/src/api_server/tx_sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ impl TxSender {
mut tx: ZkSyncTx,
signature: TxEthSignatureVariant,
fast_processing: Option<bool>,
ip: Option<String>,
) -> Result<TxHash, SubmitError> {
let fast_processing = fast_processing.unwrap_or(false);
if fast_processing && !tx.is_withdraw() {
Expand All @@ -370,13 +371,14 @@ impl TxSender {
withdraw.fast = fast_processing;
}

self.submit_tx(tx, signature).await
self.submit_tx(tx, signature, ip).await
}

pub async fn submit_tx(
&self,
tx: ZkSyncTx,
signature: TxEthSignatureVariant,
ip: Option<String>,
) -> Result<TxHash, SubmitError> {
if tx.is_close() {
return Err(SubmitError::AccountCloseDisabled);
Expand Down Expand Up @@ -418,7 +420,7 @@ impl TxSender {
}

let required_fee_data =
Self::ticker_request(ticker_request_sender, tx_type, address, token.clone())
Self::ticker_request(ticker_request_sender, tx_type, address, token.clone(), ip)
.await?;

// Converting `BitUint` to `BigInt` is safe.
Expand Down Expand Up @@ -478,6 +480,7 @@ impl TxSender {
&self,
txs: Vec<TxWithSignature>,
eth_signatures: Option<EthBatchSignatures>,
ip: Option<String>,
) -> Result<SubmitBatchResponse, SubmitError> {
// Bring the received signatures into a vector for simplified work.
let eth_signatures = EthBatchSignatures::api_arg_to_vec(eth_signatures);
Expand Down Expand Up @@ -563,6 +566,7 @@ impl TxSender {
self.ticker_requests.clone(),
transaction_types.clone(),
batch_token.into(),
ip,
)
.await?;
let user_provided_fee =
Expand All @@ -585,6 +589,7 @@ impl TxSender {
self.ticker_requests.clone(),
transaction_types,
eth_token.clone(),
ip,
)
.await?
.normal_fee;
Expand Down Expand Up @@ -706,12 +711,14 @@ impl TxSender {
tx_type: TxFeeTypes,
address: Address,
token: TokenLike,
ip: Option<String>,
) -> Result<Fee, SubmitError> {
let resp_fee = Self::ticker_request(
self.ticker_requests.clone(),
tx_type,
address,
token.clone(),
ip,
)
.await?;
Ok(resp_fee.normal_fee)
Expand All @@ -721,11 +728,13 @@ impl TxSender {
&self,
transactions: Vec<(TxFeeTypes, Address)>,
token: TokenLike,
ip: Option<String>,
) -> Result<BatchFee, SubmitError> {
let resp_fee = Self::ticker_batch_fee_request(
self.ticker_requests.clone(),
transactions,
token.clone(),
ip,
)
.await?;
Ok(resp_fee.normal_fee)
Expand Down Expand Up @@ -809,13 +818,15 @@ impl TxSender {
mut ticker_request_sender: mpsc::Sender<TickerRequest>,
transactions: Vec<(TxFeeTypes, Address)>,
token: TokenLike,
ip: Option<String>,
) -> Result<ResponseBatchFee, SubmitError> {
let req = oneshot::channel();
ticker_request_sender
.send(TickerRequest::GetBatchTxFee {
transactions,
token: token.clone(),
response: req.0,
ip,
})
.await
.map_err(SubmitError::internal)?;
Expand All @@ -828,6 +839,7 @@ impl TxSender {
tx_type: TxFeeTypes,
address: Address,
token: TokenLike,
ip: Option<String>,
) -> Result<ResponseFee, SubmitError> {
let req = oneshot::channel();
ticker_request_sender
Expand All @@ -836,6 +848,7 @@ impl TxSender {
address,
token: token.clone(),
response: req.0,
ip,
})
.await
.map_err(SubmitError::internal)?;
Expand Down
33 changes: 32 additions & 1 deletion core/bin/zksync_api/src/fee_ticker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ pub struct TickerConfig {
tokens_risk_factors: HashMap<TokenId, Ratio<BigUint>>,
scale_fee_coefficient: Ratio<BigUint>,
max_blocks_to_aggregate: u32,
subsidized_ips: Vec<String>,
subsidy_cpk_price_usd_cents: u64,
max_subsidy_usd_cents: u64,
subsidy_name: String,
}

#[derive(Debug, PartialEq, Eq)]
Expand All @@ -175,11 +179,13 @@ pub enum TickerRequest {
address: Address,
token: TokenLike,
response: oneshot::Sender<Result<ResponseFee, anyhow::Error>>,
ip: Option<String>,
},
GetBatchTxFee {
transactions: Vec<(TxFeeTypes, Address)>,
token: TokenLike,
response: oneshot::Sender<Result<ResponseBatchFee, anyhow::Error>>,
ip: Option<String>,
},
GetTokenPrice {
token: TokenLike,
Expand Down Expand Up @@ -267,6 +273,10 @@ pub fn run_ticker_task(
config.chain.state_keeper.max_aggregated_blocks_to_commit,
config.chain.state_keeper.max_aggregated_blocks_to_execute,
) as u32,
subsidized_ips: config.ticker.subsidized_ips,
subsidy_cpk_price_usd_cents: config.ticker.subsidy_cpk_price_usd_cents,
max_subsidy_usd_cents: config.ticker.max_subsidy_usd_cents,
subsidy_name: config.ticker.subsidy_name,
};

let cache = (db_pool.clone(), TokenDBCache::new());
Expand Down Expand Up @@ -378,9 +388,10 @@ impl<API: FeeTickerAPI, INFO: FeeTickerInfo, WATCHER: TokenWatcher> FeeTicker<AP
token,
response,
address,
ip,
} => {
let fee = self
.get_fee_from_ticker_in_wei(tx_type, token, address)
.get_fee_from_ticker_in_wei(tx_type, token, address, ip)
.await;
metrics::histogram!("ticker.get_tx_fee", start.elapsed());
response.send(fee).unwrap_or_default()
Expand All @@ -403,6 +414,7 @@ impl<API: FeeTickerAPI, INFO: FeeTickerInfo, WATCHER: TokenWatcher> FeeTicker<AP
transactions,
token,
response,
ip,
} => {
let fee = self.get_batch_from_ticker_in_wei(token, transactions).await;
metrics::histogram!("ticker.get_tx_fee", start.elapsed());
Expand Down Expand Up @@ -436,11 +448,26 @@ impl<API: FeeTickerAPI, INFO: FeeTickerInfo, WATCHER: TokenWatcher> FeeTicker<AP
.map(|price| ratio_to_big_decimal(&(price.usd_price / factor), 100))
}

async fn should_subsidie_cpk(&self, ip: Option<String>) -> bool {
let ip = if let Some(ip_str) = ip {
ip_str
} else {
return false;
};

if self.config.subsidized_ips.contains(&ip) {
true
} else {
false
}
}

async fn get_fee_from_ticker_in_wei(
&mut self,
tx_type: TxFeeTypes,
token: TokenLike,
recipient: Address,
ip: Option<String>,
) -> Result<ResponseFee, anyhow::Error> {
let zkp_cost_chunk = self.config.zkp_cost_chunk_usd.clone();
let token = self.api.get_token(token).await?;
Expand All @@ -467,6 +494,8 @@ impl<API: FeeTickerAPI, INFO: FeeTickerInfo, WATCHER: TokenWatcher> FeeTicker<AP
normal_gas_fee *= self.config.scale_fee_coefficient.clone();
}

if matches!(fee_type, OutputFeeType::ChangePubKey(_)) && self.should_subsidie_cpk(ip) {}

let normal_fee = Fee::new(
fee_type,
zkp_fee,
Expand All @@ -475,6 +504,8 @@ impl<API: FeeTickerAPI, INFO: FeeTickerInfo, WATCHER: TokenWatcher> FeeTicker<AP
gas_price_wei.clone(),
);

//let usd_price_fee =

Ok(ResponseFee { normal_fee })
}

Expand Down
9 changes: 8 additions & 1 deletion core/bin/zksync_api/src/fee_ticker/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ fn get_test_ticker_config() -> TickerConfig {
.collect(),
scale_fee_coefficient: Ratio::new(BigUint::from(150u32), BigUint::from(100u32)),
max_blocks_to_aggregate: 5,
subsidized_ips: vec![],
subsidy_cpk_price_usd_cents: 0,
max_subsidy_usd_cents: 0,
subsidy_name: String::from(""),
}
}

Expand Down Expand Up @@ -290,7 +294,7 @@ fn test_ticker_formula() {
}
ticker.info.remaining_chunks = remaining_chunks;
let fee_in_token =
block_on(ticker.get_fee_from_ticker_in_wei(tx_type, token.clone(), address))
block_on(ticker.get_fee_from_ticker_in_wei(tx_type, token.clone(), address, None))
.expect("failed to get fee in token");
let token_precision = block_on(MockApiProvider.get_token(token.clone()))
.unwrap()
Expand Down Expand Up @@ -545,6 +549,7 @@ fn test_zero_price_token_fee() {
TxFeeTypes::Transfer,
token.id.into(),
Address::default(),
None,
))
.unwrap_err();

Expand Down Expand Up @@ -617,6 +622,7 @@ async fn test_error_coingecko_api() {
TxFeeTypes::FastWithdraw,
token.id.into(),
Address::default(),
None,
)
.await
.unwrap();
Expand Down Expand Up @@ -669,6 +675,7 @@ async fn test_error_api() {
TxFeeTypes::FastWithdraw,
TokenId(1).into(),
Address::default(),
None,
)
.await
.unwrap();
Expand Down
Loading

0 comments on commit d6d77e3

Please sign in to comment.