Skip to content

Commit

Permalink
Merge branch 'dev' into vd-zks-465-make-it-possible-to-distinguish-be…
Browse files Browse the repository at this point in the history
…tween
  • Loading branch information
dvush committed Feb 12, 2021
2 parents 090747d + 4c69271 commit ef46e74
Show file tree
Hide file tree
Showing 15 changed files with 73 additions and 66 deletions.
4 changes: 4 additions & 0 deletions changelog/js-sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ All notable changes to `zksync.js` will be documented in this file.

### Changed

### Deprecated

- WebSocket provider.

### Fixed

## Version 0.8.4
Expand Down
4 changes: 4 additions & 0 deletions changelog/rust-sdk.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All notable changes to `zksync_rs` will be documented in this file.

## Unreleased

### Added

- Constructor of RpcProvider from address and network.

**Version 0.2.2** is being developed.

### Added
Expand Down
11 changes: 4 additions & 7 deletions core/bin/zksync_api/src/fee_ticker/ticker_api/coingecko.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,13 @@ impl TokenPriceAPI for CoinGeckoAPI {

// If we use 2 day interval we will get hourly prices and not minute by minute which makes
// response faster and smaller
let request = self
let market_chart = self
.client
.get(market_chart_url)
.query(&[("vs_currency", "usd"), ("days", "2")]);

let api_request_future = tokio::time::timeout(REQUEST_TIMEOUT, request.send());

let market_chart = api_request_future
.timeout(REQUEST_TIMEOUT)
.query(&[("vs_currency", "usd"), ("days", "2")])
.send()
.await
.map_err(|_| anyhow::format_err!("CoinGecko API request timeout"))?
.map_err(|err| anyhow::format_err!("CoinGecko API request failed: {}", err))?
.json::<CoinGeckoMarketChart>()
.await?;
Expand Down
11 changes: 6 additions & 5 deletions core/bin/zksync_api/src/fee_ticker/ticker_api/coinmarkercap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,16 @@ impl TokenPriceAPI for CoinMarketCapAPI {
))
.expect("failed to join url path");

let api_request_future =
tokio::time::timeout(REQUEST_TIMEOUT, self.client.get(request_url).send());

let mut api_response = api_request_future
let mut api_response = self
.client
.get(request_url)
.timeout(REQUEST_TIMEOUT)
.send()
.await
.map_err(|_| anyhow::format_err!("Coinmarketcap API request timeout"))?
.map_err(|err| anyhow::format_err!("Coinmarketcap API request failed: {}", err))?
.json::<CoinmarketCapResponse>()
.await?;

let mut token_info = api_response
.data
.remove(&TokenLike::Symbol(token_symbol.to_string()))
Expand Down
15 changes: 8 additions & 7 deletions core/bin/zksync_api/src/fee_ticker/validator/watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,15 @@ impl UniswapTokenWatcher {

let query = format!("{{token(id: \"{:#x}\"){{tradeVolumeUSD}}}}", address);

let request = self.client.post(&self.addr).json(&serde_json::json!({
"query": query.clone(),
}));
let api_request_future = tokio::time::timeout(REQUEST_TIMEOUT, request.send());

let response: GraphqlResponse = api_request_future
let response = self
.client
.post(&self.addr)
.json(&serde_json::json!({
"query": query.clone(),
}))
.timeout(REQUEST_TIMEOUT)
.send()
.await
.map_err(|_| anyhow::format_err!("Uniswap API request timeout"))?
.map_err(|err| anyhow::format_err!("Uniswap API request failed: {}", err))?
.json::<GraphqlResponse>()
.await?;
Expand Down
4 changes: 2 additions & 2 deletions core/tests/ts-tests/tests/batch-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Tester.prototype.testBatchBuilderChangePubKey = async function (

const balanceBefore = await sender.getBalance(token);
const handles = await wallet.submitSignedTransactionsBatch(sender.provider, batch.txs, [batch.signature]);
await Promise.all(handles.map((handle) => handle.awaitVerifyReceipt()));
await Promise.all(handles.map((handle) => handle.awaitReceipt()));
expect(await sender.isSigningKeySet(), 'ChangePubKey failed').to.be.true;
const balanceAfter = await sender.getBalance(token);
expect(balanceBefore.sub(balanceAfter).eq(amount.add(totalFee)), 'Wrong amount in wallet after withdraw').to.be
Expand Down Expand Up @@ -154,7 +154,7 @@ Tester.prototype.testBatchBuilderGenericUsage = async function (
const senderBefore = await sender.getBalance(token);
const receiverBefore = await receiver.getBalance(token);
const handles = await wallet.submitSignedTransactionsBatch(sender.provider, batch.txs, [batch.signature]);
await Promise.all(handles.map((handle) => handle.awaitVerifyReceipt()));
await Promise.all(handles.map((handle) => handle.awaitReceipt()));
const senderAfter = await sender.getBalance(token);
const receiverAfter = await receiver.getBalance(token);
const targetBalance = await target.getBalance(token);
Expand Down
13 changes: 1 addition & 12 deletions core/tests/ts-tests/tests/forced-exit.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Tester } from './tester';
import { expect } from 'chai';
import { Wallet, types } from 'zksync';
import { sleep } from 'zksync/build/utils';

type TokenLike = types.TokenLike;

Expand Down Expand Up @@ -32,17 +31,7 @@ Tester.prototype.testVerifiedForcedExit = async function (

// Checking that there are some complete withdrawals tx hash for this ForcedExit
// we should wait some time for `completeWithdrawals` transaction to be processed
let withdrawalTxHash = null;
const polling_interval = 200; // ms
const polling_timeout = 35000; // ms
const polling_iterations = polling_timeout / polling_interval;
for (let i = 0; i < polling_iterations; i++) {
withdrawalTxHash = await this.syncProvider.getEthTxForWithdrawal(handle.txHash);
if (withdrawalTxHash != null) {
break;
}
await sleep(polling_interval);
}
const withdrawalTxHash = await this.syncProvider.getEthTxForWithdrawal(handle.txHash);
expect(withdrawalTxHash, 'Withdrawal was not processed onchain').to.exist;

await this.ethProvider.waitForTransaction(withdrawalTxHash as string);
Expand Down
22 changes: 11 additions & 11 deletions core/tests/ts-tests/tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,6 @@ describe(`ZkSync integration tests (token: ${token}, transport: ${transport})`,
await tester.testRejectedBatch(alice, bob, token, TX_AMOUNT);
});

step('should execute a withdrawal', async () => {
await tester.testVerifiedWithdraw(alice, token, TX_AMOUNT);
});

step('should execute a ForcedExit', async () => {
if (onlyBasic) {
return;
}
await tester.testVerifiedForcedExit(alice, bob, token);
});

step('should test batch-builder', async () => {
// We will pay with different token.
const feeToken = token == 'ETH' ? 'wBTC' : 'ETH';
Expand Down Expand Up @@ -152,6 +141,17 @@ describe(`ZkSync integration tests (token: ${token}, transport: ${transport})`,
await tester.testBackwardCompatibleEthMessages(alice, david, token, TX_AMOUNT);
});

step('should execute a withdrawal', async () => {
await tester.testVerifiedWithdraw(alice, token, TX_AMOUNT);
});

step('should execute a ForcedExit', async () => {
if (onlyBasic) {
return;
}
await tester.testVerifiedForcedExit(alice, bob, token);
});

it('should check collected fees', async () => {
const collectedFee = (await tester.operatorBalance(token)).sub(operatorBalance);
expect(collectedFee.eq(tester.runningFee), `Fee collection failed, expected: ${tester.runningFee.toString()}, got: ${collectedFee.toString()}`).to.be.true;
Expand Down
4 changes: 2 additions & 2 deletions core/tests/ts-tests/tests/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ Tester.prototype.testMultipleBatchSigners = async function (wallets: Wallet[], t

const senderBefore = await batchSender.getBalance(token);
const handles = await submitSignedTransactionsBatch(batchSender.provider, batch, ethSignatures);
await Promise.all(handles.map((handle) => handle.awaitVerifyReceipt()));
await Promise.all(handles.map((handle) => handle.awaitReceipt()));
const senderAfter = await batchSender.getBalance(token);
// Sender paid totalFee for this cycle.
expect(senderBefore.sub(senderAfter).eq(totalFee), 'Batched transfer failed').to.be.true;
Expand Down Expand Up @@ -233,6 +233,6 @@ Tester.prototype.testBackwardCompatibleEthMessages = async function (

const handles = await submitSignedTransactionsBatch(to.provider, batch, ethSignatures);
// We only expect that API doesn't reject this batch due to Eth signature error.
await Promise.all(handles.map((handle) => handle.awaitVerifyReceipt()));
await Promise.all(handles.map((handle) => handle.awaitReceipt()));
this.runningFee = this.runningFee.add(totalFee);
};
15 changes: 1 addition & 14 deletions core/tests/ts-tests/tests/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Tester } from './tester';
import { expect } from 'chai';
import { Wallet, types } from 'zksync';
import { BigNumber } from 'ethers';
import { sleep } from 'zksync/build/utils';

type TokenLike = types.TokenLike;

Expand All @@ -28,19 +27,7 @@ Tester.prototype.testVerifiedWithdraw = async function (
// Await for verification with a timeout set (through mocha's --timeout)
await handle.awaitVerifyReceipt();

// Checking that there are some complete withdrawals tx hash for this withdrawal
// we should wait some time for `completeWithdrawals` transaction to be processed
let withdrawalTxHash = null;
const polling_interval = 200; // ms
const polling_timeout = 35000; // ms
const polling_iterations = polling_timeout / polling_interval;
for (let i = 0; i < polling_iterations; i++) {
withdrawalTxHash = await this.syncProvider.getEthTxForWithdrawal(handle.txHash);
if (withdrawalTxHash != null) {
break;
}
await sleep(polling_interval);
}
const withdrawalTxHash = await this.syncProvider.getEthTxForWithdrawal(handle.txHash);
expect(withdrawalTxHash, 'Withdrawal was not processed onchain').to.exist;

await this.ethProvider.waitForTransaction(withdrawalTxHash as string);
Expand Down
9 changes: 9 additions & 0 deletions sdk/zksync-rs/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ impl RpcProvider {
}
}

/// Creates a new `Provider` object connected to a custom address and the desired zkSync network.
pub fn from_addr_and_network(rpc_addr: impl Into<String>, network: Network) -> Self {
Self {
rpc_addr: rpc_addr.into(),
client: reqwest::Client::new(),
network,
}
}

/// Submits a batch transaction to the zkSync network.
/// Returns the hashes of the created transactions.
pub async fn send_txs_batch(
Expand Down
6 changes: 6 additions & 0 deletions sdk/zksync.js/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import {
import { isTokenETH, sleep, SYNC_GOV_CONTRACT_INTERFACE, TokenSet } from './utils';

export async function getDefaultProvider(network: Network, transport: 'WS' | 'HTTP' = 'HTTP'): Promise<Provider> {
if (transport === 'WS') {
console.warn('Websocket support will be removed in future. Use HTTP transport instead.');
}
if (network === 'localhost') {
if (transport === 'WS') {
return await Provider.newWebsocketProvider('ws://127.0.0.1:3031');
Expand Down Expand Up @@ -67,6 +70,9 @@ export class Provider {

private constructor(public transport: AbstractJSONRPCTransport) {}

/**
* @deprecated Websocket support will be removed in future. Use HTTP transport instead.
*/
static async newWebsocketProvider(address: string): Promise<Provider> {
const transport = await WSTransport.connect(address);
const provider = new Provider(transport);
Expand Down
3 changes: 3 additions & 0 deletions sdk/zksync.js/src/transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ export class HTTPTransport extends AbstractJSONRPCTransport {
async disconnect() {}
}

/**
* @deprecated Websocket support will be removed in future. Use HTTP transport instead.
*/
export class WSTransport extends AbstractJSONRPCTransport {
ws: WebSocketAsPromised;
private subscriptionCallback: Map<string, (data: any) => void>;
Expand Down
7 changes: 6 additions & 1 deletion sdk/zksync.js/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ export const ERC20_APPROVE_TRESHOLD = BigNumber.from(
'57896044618658097711785492504343953926634992332820282019728792003956564819968'
); // 2^255

export const ERC20_DEPOSIT_GAS_LIMIT = BigNumber.from('300000'); // 300k
// Gas limit that is set for eth deposit by default. For default EOA accounts 60k should be enough, but we reserve
// more gas for smart-contract wallets
export const ETH_RECOMMENDED_DEPOSIT_GAS_LIMIT = BigNumber.from('90000'); // 90k
// For normal wallet/erc20 token 90k gas for deposit should be enough, but for some tokens this can go as high as ~200k
// we try to be safe by default
export const ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT = BigNumber.from('300000'); // 300k

const AMOUNT_EXPONENT_BIT_WIDTH = 5;
const AMOUNT_MANTISSA_BIT_WIDTH = 35;
Expand Down
11 changes: 6 additions & 5 deletions sdk/zksync.js/src/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,13 @@ import {
isTokenETH,
MAX_ERC20_APPROVE_AMOUNT,
SYNC_MAIN_CONTRACT_INTERFACE,
ERC20_DEPOSIT_GAS_LIMIT,
ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT,
signMessagePersonalAPI,
getSignedBytesFromMessage,
getChangePubkeyMessage,
MAX_TIMESTAMP,
getEthereumBalance
getEthereumBalance,
ETH_RECOMMENDED_DEPOSIT_GAS_LIMIT
} from './utils';

const EthersErrorCode = ErrorCode;
Expand Down Expand Up @@ -816,7 +817,7 @@ export class Wallet {
try {
ethTransaction = await mainZkSyncContract.depositETH(deposit.depositTo, {
value: BigNumber.from(deposit.amount),
gasLimit: BigNumber.from('200000'),
gasLimit: BigNumber.from(ETH_RECOMMENDED_DEPOSIT_GAS_LIMIT),
gasPrice,
...deposit.ethTxOptions
});
Expand Down Expand Up @@ -858,9 +859,9 @@ export class Wallet {
(estimate) => estimate,
() => BigNumber.from('0')
);
txRequest.gasLimit = gasEstimate.gte(ERC20_DEPOSIT_GAS_LIMIT)
txRequest.gasLimit = gasEstimate.gte(ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT)
? gasEstimate
: ERC20_DEPOSIT_GAS_LIMIT;
: ERC20_RECOMMENDED_DEPOSIT_GAS_LIMIT;
args[args.length - 1] = txRequest;
} catch (e) {
this.modifyEthersError(e);
Expand Down

0 comments on commit ef46e74

Please sign in to comment.