Skip to content

Commit

Permalink
Merge branch 'dev' into vd-zks-542-allow-subsidies-for-token-add-them-to
Browse files Browse the repository at this point in the history
  • Loading branch information
dvush committed Mar 17, 2021
2 parents 4c8005c + 5735b30 commit c392fe2
Show file tree
Hide file tree
Showing 47 changed files with 810 additions and 802 deletions.
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "sdk/binaryen"]
path = sdk/binaryen
url = [email protected]:WebAssembly/binaryen.git
7 changes: 1 addition & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,7 @@ To learn how to use zkSync, please refer to the [zkSync SDK documentation](https

## Development Documentation

The following guides for developers are available:

- Installing development dependencies: [docs/setup-dev.md](docs/setup-dev.md).
- Launching zkSync locally: [docs/launch.md](docs/launch.md).
- Development guide: [docs/development.md](docs/development.md).
- Repository architecture overview: [docs/architecture.md](docs/architecture.md).
The repository architecture overview is available: [docs/architecture.md](docs/architecture.md).

## Projects

Expand Down
4 changes: 4 additions & 0 deletions changelog/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ All notable changes to the core components will be documented in this file.
operations.
- (`eth_client`): Added `get_tx`, `create_contract` methods to `EthereumGateway`, `get_web3_transport` method to
ETHDirectClient.
- (`api_server`): Support for accounts that don't have to pay fees (e.g. network service accounts) was added.

### Fixed

- (`zksync_api`): Internal error with tokens not listed on CoinGecko.
- Fix wrong block info cache behavior in the `api_server`.

## Release 2021-02-19

### Removed
Expand Down
18 changes: 18 additions & 0 deletions changelog/js-sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,29 @@ All notable changes to `zksync.js` will be documented in this file.

### Added

### Changed

### Deprecated

### Fixed

## Version 0.10.6 (16.03.2021)

### Added

- (`BatchBuilder`) Make it possible to add signed `ChangePubKey` transaction to the batch.

## Version 0.10.4 (08.03.2021)

### Added

- Method for calculation of transaction hash.
- Support for environments without WebAssembly.

### Changed

- Hardcode gas limit for `depositERC20` for each token.

### Deprecated

- `Signer.transferSignBytes` method
Expand Down
2 changes: 2 additions & 0 deletions changelog/rust-sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ All notable changes to `zksync_rs` will be documented in this file.

### Changed

- Hardcode gas limit for `depositERC20` for each token.

### Deprecated

### Fixed
Expand Down
40 changes: 11 additions & 29 deletions core/bin/zksync_api/src/api_server/rest/v1/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,29 @@ use actix_web::{

// Workspace uses
pub use zksync_api_client::rest::v1::{BlockInfo, TransactionInfo};
use zksync_config::ZkSyncConfig;
use zksync_crypto::{convert::FeConvert, Fr};
use zksync_storage::{chain::block::records, ConnectionPool, QueryResult};
use zksync_types::{tx::TxHash, BlockNumber};

// Local uses
use super::{Error as ApiError, JsonResult, Pagination, PaginationQuery};
use crate::{api_server::helpers::try_parse_tx_hash, utils::shared_lru_cache::AsyncLruCache};
use crate::{
api_server::helpers::try_parse_tx_hash, utils::block_details_cache::BlockDetailsCache,
};

/// Shared data between `api/v1/blocks` endpoints.
#[derive(Debug, Clone)]
struct ApiBlocksData {
pool: ConnectionPool,
/// Verified blocks cache.
verified_blocks: AsyncLruCache<BlockNumber, records::BlockDetails>,
verified_blocks: BlockDetailsCache,
}

impl ApiBlocksData {
fn new(pool: ConnectionPool, capacity: usize) -> Self {
fn new(pool: ConnectionPool, verified_blocks: BlockDetailsCache) -> Self {
Self {
pool,
verified_blocks: AsyncLruCache::new(capacity),
verified_blocks,
}
}

Expand All @@ -42,27 +43,7 @@ impl ApiBlocksData {
&self,
block_number: BlockNumber,
) -> QueryResult<Option<records::BlockDetails>> {
if let Some(block) = self.verified_blocks.get(&block_number).await {
return Ok(Some(block));
}

let blocks = self.blocks_range(Some(block_number), 1).await?;
if let Some(block) = blocks.into_iter().next() {
// Check if this is exactly the requested block.
if block.block_number != *block_number as i64 {
return Ok(None);
}

// It makes sense to store in cache only fully verified blocks.
if block.is_verified() {
self.verified_blocks
.insert(block_number, block.clone())
.await;
}
Ok(Some(block))
} else {
Ok(None)
}
self.verified_blocks.get(&self.pool, block_number).await
}

/// Returns the block range up to the given block number.
Expand Down Expand Up @@ -218,8 +199,8 @@ async fn blocks_range(
Ok(Json(range))
}

pub fn api_scope(config: &ZkSyncConfig, pool: ConnectionPool) -> Scope {
let data = ApiBlocksData::new(pool, config.api.common.caches_size);
pub fn api_scope(pool: ConnectionPool, cache: BlockDetailsCache) -> Scope {
let data = ApiBlocksData::new(pool, cache);

web::scope("blocks")
.data(data)
Expand All @@ -241,7 +222,8 @@ mod tests {
let cfg = TestServerConfig::default();
cfg.fill_database().await?;

let (client, server) = cfg.start_server(|cfg| api_scope(&cfg.config, cfg.pool.clone()));
let (client, server) =
cfg.start_server(|cfg| api_scope(cfg.pool.clone(), BlockDetailsCache::new(10)));

// Block requests part
let blocks: Vec<BlockInfo> = {
Expand Down
5 changes: 4 additions & 1 deletion core/bin/zksync_api/src/api_server/rest/v1/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ pub(crate) fn api_scope(tx_sender: TxSender, zk_config: &ZkSyncConfig) -> Scope
tx_sender.core_api_client.clone(),
))
.service(config::api_scope(&zk_config))
.service(blocks::api_scope(&zk_config, tx_sender.pool.clone()))
.service(blocks::api_scope(
tx_sender.pool.clone(),
tx_sender.blocks.clone(),
))
.service(transactions::api_scope(tx_sender.clone()))
.service(operations::api_scope(tx_sender.pool.clone()))
.service(search::api_scope(tx_sender.pool.clone()))
Expand Down
33 changes: 18 additions & 15 deletions core/bin/zksync_api/src/api_server/rest/v1/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use zksync_storage::{ConnectionPool, QueryResult};
use zksync_types::{Token, TokenLike};

use crate::{
fee_ticker::{TickerRequest, TokenPriceRequestType},
fee_ticker::{PriceError, TickerRequest, TokenPriceRequestType},
utils::token_db_cache::TokenDBCache,
};

Expand Down Expand Up @@ -76,17 +76,11 @@ impl ApiTokensData {
})
.await?;

// Ugly hack to distinguish real error from missing token.
match price_receiver.await? {
Ok(price) => Ok(Some(price)),
Err(err) => {
// TODO: Improve ticker API to remove this terrible code snippet. (task number ????)
if err.to_string().contains("Token not found") {
Ok(None)
} else {
Err(err)
}
}
Err(PriceError::TokenNotFound(_)) => Ok(None),
Err(PriceError::DBError(err)) => Err(anyhow::format_err!(err)),
Err(PriceError::ApiError(err)) => Err(anyhow::format_err!(err)),
}
}
}
Expand Down Expand Up @@ -154,6 +148,8 @@ mod tests {

use super::{super::test_utils::TestServerConfig, *};

use zksync_api_client::rest::v1::ClientError;

fn dummy_fee_ticker(prices: &[(TokenLike, BigDecimal)]) -> mpsc::Sender<TickerRequest> {
let (sender, mut receiver) = mpsc::channel(10);

Expand All @@ -175,8 +171,10 @@ mod tests {
let msg = if let Some(price) = prices.get(&token) {
Ok(price.clone())
} else {
// To provide compatibility with the `token_price_usd` hack.
Err(anyhow::format_err!("Token not found: {:?}", token))
Err(PriceError::token_not_found(format!(
"Token not found: {:?}",
token
)))
};

response.send(msg).expect("Unable to send response");
Expand Down Expand Up @@ -226,12 +224,17 @@ mod tests {
.await?,
None
);
// TODO Check error (ZKS-125)
client
let error = client
.token_price(&TokenLike::Id(TokenId(2)), TokenPriceKind::Token)
.await
.unwrap_err();

assert!(
matches!(error, ClientError::BadRequest { .. }),
format!(
"Incorrect error type: got {:?} instead of BadRequest",
error
)
);
// Tokens requests
let expected_tokens = {
let mut storage = cfg.pool.access_storage().await?;
Expand Down
99 changes: 83 additions & 16 deletions core/bin/zksync_api/src/api_server/rest/v1/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,12 @@ mod tests {
async fn new() -> anyhow::Result<(Client, Self)> {
let (core_client, core_server) = submit_txs_loopback();

let cfg = TestServerConfig::default();
let mut cfg = TestServerConfig::default();
cfg.config
.api
.common
.fee_free_accounts
.push(AccountId(0xfee));
let pool = cfg.pool.clone();
cfg.fill_database().await?;

Expand Down Expand Up @@ -492,6 +497,20 @@ mod tests {
}
}

#[actix_rt::test]
#[cfg_attr(
not(feature = "api_test"),
ignore = "Use `zk test rust-api` command to perform this test"
)]
async fn test_rust_api() -> anyhow::Result<()> {
// TODO: ZKS-561
test_transactions_scope().await?;
test_bad_fee_token().await?;
test_fast_processing_flag().await?;
test_fee_free_accounts().await?;
Ok(())
}

#[actix_rt::test]
#[cfg_attr(
not(feature = "api_test"),
Expand All @@ -514,11 +533,6 @@ mod tests {
Ok(())
}

#[actix_rt::test]
#[cfg_attr(
not(feature = "api_test"),
ignore = "Use `zk test rust-api` command to perform this test"
)]
async fn test_transactions_scope() -> anyhow::Result<()> {
let (client, server) = TestServer::new().await?;

Expand Down Expand Up @@ -681,11 +695,6 @@ mod tests {
/// - Attempt to pay fees in an inappropriate token fails for single txs.
/// - Attempt to pay fees in an inappropriate token fails for single batch.
/// - Batch with an inappropriate token still can be processed if the fee is covered with a common token.
#[actix_rt::test]
#[cfg_attr(
not(feature = "api_test"),
ignore = "Use `zk test rust-api` command to perform this test"
)]
async fn test_bad_fee_token() -> anyhow::Result<()> {
let (client, server) = TestServer::new().await?;

Expand Down Expand Up @@ -797,16 +806,74 @@ mod tests {
Ok(())
}

/// This test checks the following:
///
/// Fee free account can pay zero fee in single tx.
/// Not a fee free account can't pay zero fee in single tx.
async fn test_fee_free_accounts() -> anyhow::Result<()> {
let (client, server) = TestServer::new().await?;

let from1 = ZkSyncAccount::rand();
from1.set_account_id(Some(AccountId(0xfee)));
let to1 = ZkSyncAccount::rand();

// Submit transaction with a zero fee by the fee free account
let (tx1, eth_sig1) = from1.sign_transfer(
TokenId(0),
"ETH",
0u64.into(),
0u64.into(),
&to1.address,
Some(Nonce(0)),
false,
Default::default(),
);
let transfer1 = ZkSyncTx::Transfer(Box::new(tx1));
client
.submit_tx(
transfer1.clone(),
eth_sig1.map(TxEthSignature::EthereumSignature),
None,
)
.await
.expect("fee free account transaction fails");

let from2 = ZkSyncAccount::rand();
from2.set_account_id(Some(AccountId(0xbee)));
let to2 = ZkSyncAccount::rand();

// Submit transaction with a zero fee not by the fee free account
let (tx2, eth_sig2) = from2.sign_transfer(
TokenId(0),
"ETH",
0u64.into(),
0u64.into(),
&to2.address,
Some(Nonce(0)),
false,
Default::default(),
);
let transfer2 = ZkSyncTx::Transfer(Box::new(tx2));
client
.submit_tx(
transfer2.clone(),
eth_sig2.map(TxEthSignature::EthereumSignature),
None,
)
.await
.unwrap_err()
.to_string()
.contains("Transaction fee is too low");

server.stop().await;
Ok(())
}

/// This test checks the following criteria:
///
/// - Attempt to submit non-withdraw transaction with the enabled fast-processing.
/// - Attempt to submit non-withdraw transaction with the disabled fast-processing.
/// - Attempt to submit withdraw transaction with the enabled fast-processing.
#[actix_rt::test]
#[cfg_attr(
not(feature = "api_test"),
ignore = "Use `zk test rust-api` command to perform this test"
)]
async fn test_fast_processing_flag() -> anyhow::Result<()> {
let (client, server) = TestServer::new().await?;

Expand Down
Loading

0 comments on commit c392fe2

Please sign in to comment.