1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! This file hold tools used for test-forking other networks.
//!
//! There is ForkStorage (that is a wrapper over InMemoryStorage)
//! And ForkDetails - that parses network address and fork height from arguments.

use std::{
    collections::HashMap,
    convert::{TryFrom, TryInto},
    fmt,
    future::Future,
    marker::PhantomData,
    str::FromStr,
    sync::{Arc, RwLock},
};

use tokio::runtime::Builder;
use zksync_basic_types::{Address, L1BatchNumber, L2BlockNumber, L2ChainId, H256, U256, U64};

use zksync_types::{
    api::{
        Block, BlockDetails, BlockIdVariant, BlockNumber, BridgeAddresses, Transaction,
        TransactionDetails, TransactionVariant,
    },
    fee_model::FeeParams,
    l2::L2Tx,
    url::SensitiveUrl,
    ProtocolVersionId, StorageKey,
};

use zksync_state::ReadStorage;
use zksync_utils::{bytecode::hash_bytecode, h256_to_u256};

use zksync_web3_decl::{
    client::{Client, L2},
    namespaces::ZksNamespaceClient,
};
use zksync_web3_decl::{namespaces::EthNamespaceClient, types::Index};

use crate::{config::cache::CacheConfig, node::TEST_NODE_NETWORK_ID};
use crate::{
    config::gas::{DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR},
    system_contracts,
};
use crate::{deps::InMemoryStorage, http_fork_source::HttpForkSource};

pub fn block_on<F: Future + Send + 'static>(future: F) -> F::Output
where
    F::Output: Send,
{
    std::thread::spawn(move || {
        let runtime = Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("tokio runtime creation failed");
        runtime.block_on(future)
    })
    .join()
    .unwrap()
}

/// The possible networks to fork from.
#[derive(Debug, Clone)]
pub enum ForkNetwork {
    Mainnet,
    SepoliaTestnet,
    GoerliTestnet,
    Other(String),
}

impl ForkNetwork {
    /// Return the URL for the underlying fork source.
    pub fn to_url(&self) -> &str {
        match self {
            ForkNetwork::Mainnet => "https://mainnet.era.zksync.io:443",
            ForkNetwork::SepoliaTestnet => "https://sepolia.era.zksync.dev:443",
            ForkNetwork::GoerliTestnet => "https://testnet.era.zksync.dev:443",
            ForkNetwork::Other(url) => url,
        }
    }

    /// Returns the local gas scale factors currently in use by the upstream network.
    pub fn local_gas_scale_factors(&self) -> (f64, f32) {
        match self {
            ForkNetwork::Mainnet => (1.5, 1.2),
            ForkNetwork::SepoliaTestnet => (2.0, 1.2),
            ForkNetwork::GoerliTestnet => (1.2, 1.2),
            ForkNetwork::Other(_) => (
                DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR,
                DEFAULT_ESTIMATE_GAS_SCALE_FACTOR,
            ),
        }
    }
}

/// In memory storage, that allows 'forking' from other network.
/// If forking is enabled, it reads missing data from remote location.
/// S - is a struct that is used for source of the fork.
#[derive(Debug, Clone)]
pub struct ForkStorage<S> {
    pub inner: Arc<RwLock<ForkStorageInner<S>>>,
    pub chain_id: L2ChainId,
}

#[derive(Debug)]
pub struct ForkStorageInner<S> {
    // Underlying local storage
    pub raw_storage: InMemoryStorage,
    // Cache of data that was read from remote location.
    pub value_read_cache: HashMap<StorageKey, H256>,
    // Cache of factory deps that were read from remote location.
    pub factory_dep_cache: HashMap<H256, Option<Vec<u8>>>,
    // If set - it hold the necessary information on where to fetch the data.
    // If not set - it will simply read from underlying storage.
    pub fork: Option<ForkDetails>,
    // ForkSource type no longer needed but retained to keep the old interface.
    pub dummy: PhantomData<S>,
}

impl<S: ForkSource> ForkStorage<S> {
    pub fn new(
        fork: Option<ForkDetails>,
        system_contracts_options: &system_contracts::Options,
    ) -> Self {
        let chain_id = fork
            .as_ref()
            .and_then(|d| d.overwrite_chain_id)
            .unwrap_or(L2ChainId::from(TEST_NODE_NETWORK_ID));
        tracing::info!("Starting network with chain id: {:?}", chain_id);

        ForkStorage {
            inner: Arc::new(RwLock::new(ForkStorageInner {
                raw_storage: InMemoryStorage::with_system_contracts_and_chain_id(
                    chain_id,
                    hash_bytecode,
                    system_contracts_options,
                ),
                value_read_cache: Default::default(),
                fork,
                factory_dep_cache: Default::default(),
                dummy: Default::default(),
            })),
            chain_id,
        }
    }

    pub fn get_cache_config(&self) -> Result<CacheConfig, String> {
        let reader = self
            .inner
            .read()
            .map_err(|e| format!("Failed to acquire read lock: {}", e))?;
        let cache_config = if let Some(ref fork_details) = reader.fork {
            fork_details.cache_config.clone()
        } else {
            CacheConfig::default()
        };
        Ok(cache_config)
    }

    pub fn get_fork_url(&self) -> Result<String, String> {
        let reader = self
            .inner
            .read()
            .map_err(|e| format!("Failed to acquire read lock: {}", e))?;
        if let Some(ref fork_details) = reader.fork {
            fork_details
                .fork_source
                .get_fork_url()
                .map_err(|e| e.to_string())
        } else {
            Err("not forked".to_string())
        }
    }

    pub fn read_value_internal(
        &self,
        key: &StorageKey,
    ) -> eyre::Result<zksync_types::StorageValue> {
        let mut mutator = self.inner.write().unwrap();
        let local_storage = mutator.raw_storage.read_value(key);

        if let Some(fork) = &mutator.fork {
            if !H256::is_zero(&local_storage) {
                return Ok(local_storage);
            }

            if let Some(value) = mutator.value_read_cache.get(key) {
                return Ok(*value);
            }
            let l2_miniblock = fork.l2_miniblock;
            let key_ = *key;

            let result = fork.fork_source.get_storage_at(
                *key_.account().address(),
                h256_to_u256(*key_.key()),
                Some(BlockIdVariant::BlockNumber(BlockNumber::Number(U64::from(
                    l2_miniblock,
                )))),
            )?;

            mutator.value_read_cache.insert(*key, result);
            Ok(result)
        } else {
            Ok(local_storage)
        }
    }

    pub fn load_factory_dep_internal(&self, hash: H256) -> eyre::Result<Option<Vec<u8>>> {
        let mut mutator = self.inner.write().unwrap();
        let local_storage = mutator.raw_storage.load_factory_dep(hash);
        if let Some(fork) = &mutator.fork {
            if local_storage.is_some() {
                return Ok(local_storage);
            }
            if let Some(value) = mutator.factory_dep_cache.get(&hash) {
                return Ok(value.clone());
            }

            let result = fork.fork_source.get_bytecode_by_hash(hash)?;
            mutator.factory_dep_cache.insert(hash, result.clone());
            Ok(result)
        } else {
            Ok(local_storage)
        }
    }

    /// Check if this is the first time when we're ever writing to this key.
    /// This has impact on amount of pubdata that we have to spend for the write.
    pub fn is_write_initial_internal(&self, key: &StorageKey) -> eyre::Result<bool> {
        // Currently we don't have the zks API to return us the information on whether a given
        // key was written to before a given block.
        // This means, we have to depend on the following heuristic: we'll read the value of the slot.
        //  - if value != 0 -> this means that the slot was written to in the past (so we can return intitial_write = false)
        //  - but if the value = 0 - there is a chance, that slot was written to in the past - and later was reset.
        //                            but unfortunately we cannot detect that with the current zks api, so we'll attempt to do it
        //                           only on local storage.
        let value = self.read_value_internal(key)?;
        if value != H256::zero() {
            return Ok(false);
        }

        // If value was 0, there is still a chance, that the slot was written to in the past - and only now set to 0.
        // We unfortunately don't have the API to check it on the fork, but we can at least try to check it on local storage.
        let mut mutator = self.inner.write().unwrap();
        Ok(mutator.raw_storage.is_write_initial(key))
    }

    /// Retrieves the enumeration index for a given `key`.
    fn get_enumeration_index_internal(&self, _key: &StorageKey) -> Option<u64> {
        // TODO: Update this file to use proper enumeration index value once it's exposed for forks via API
        Some(0_u64)
    }
}

impl<S: std::fmt::Debug + ForkSource> ReadStorage for ForkStorage<S> {
    fn is_write_initial(&mut self, key: &StorageKey) -> bool {
        self.is_write_initial_internal(key).unwrap()
    }

    fn load_factory_dep(&mut self, hash: H256) -> Option<Vec<u8>> {
        self.load_factory_dep_internal(hash).unwrap()
    }

    fn read_value(&mut self, key: &StorageKey) -> zksync_types::StorageValue {
        self.read_value_internal(key).unwrap()
    }

    fn get_enumeration_index(&mut self, key: &StorageKey) -> Option<u64> {
        self.get_enumeration_index_internal(key)
    }
}

impl<S: std::fmt::Debug + ForkSource> ReadStorage for &ForkStorage<S> {
    fn read_value(&mut self, key: &StorageKey) -> zksync_types::StorageValue {
        self.read_value_internal(key).unwrap()
    }

    fn is_write_initial(&mut self, key: &StorageKey) -> bool {
        self.is_write_initial_internal(key).unwrap()
    }

    fn load_factory_dep(&mut self, hash: H256) -> Option<Vec<u8>> {
        self.load_factory_dep_internal(hash).unwrap()
    }

    fn get_enumeration_index(&mut self, key: &StorageKey) -> Option<u64> {
        self.get_enumeration_index_internal(key)
    }
}

impl<S> ForkStorage<S> {
    pub fn set_value(&mut self, key: StorageKey, value: zksync_types::StorageValue) {
        let mut mutator = self.inner.write().unwrap();
        mutator.raw_storage.set_value(key, value)
    }
    pub fn store_factory_dep(&mut self, hash: H256, bytecode: Vec<u8>) {
        let mut mutator = self.inner.write().unwrap();
        mutator.raw_storage.store_factory_dep(hash, bytecode)
    }
}

/// Trait that provides necessary data when
/// forking a remote chain.
/// The method signatures are similar to methods from ETHNamespace and ZKNamespace.
pub trait ForkSource {
    /// Returns the forked URL.
    fn get_fork_url(&self) -> eyre::Result<String>;

    /// Returns the Storage value at a given index for given address.
    fn get_storage_at(
        &self,
        address: Address,
        idx: U256,
        block: Option<BlockIdVariant>,
    ) -> eyre::Result<H256>;

    /// Returns the bytecode stored under this hash (if available).
    fn get_bytecode_by_hash(&self, hash: H256) -> eyre::Result<Option<Vec<u8>>>;

    /// Returns the transaction for a given hash.
    fn get_transaction_by_hash(&self, hash: H256) -> eyre::Result<Option<Transaction>>;

    /// Returns the transaction details for a given hash.
    fn get_transaction_details(&self, hash: H256) -> eyre::Result<Option<TransactionDetails>>;

    /// Gets all transactions that belong to a given miniblock.
    fn get_raw_block_transactions(
        &self,
        block_number: L2BlockNumber,
    ) -> eyre::Result<Vec<zksync_types::Transaction>>;

    /// Returns the block for a given hash.
    fn get_block_by_hash(
        &self,
        hash: H256,
        full_transactions: bool,
    ) -> eyre::Result<Option<Block<TransactionVariant>>>;

    /// Returns the block for a given number.
    fn get_block_by_number(
        &self,
        block_number: zksync_types::api::BlockNumber,
        full_transactions: bool,
    ) -> eyre::Result<Option<Block<TransactionVariant>>>;

    /// Returns the block details for a given miniblock number.
    fn get_block_details(&self, miniblock: L2BlockNumber) -> eyre::Result<Option<BlockDetails>>;

    /// Returns fee parameters for the give source.
    fn get_fee_params(&self) -> eyre::Result<FeeParams>;

    /// Returns the  transaction count for a given block hash.
    fn get_block_transaction_count_by_hash(&self, block_hash: H256) -> eyre::Result<Option<U256>>;

    /// Returns the transaction count for a given block number.
    fn get_block_transaction_count_by_number(
        &self,
        block_number: zksync_types::api::BlockNumber,
    ) -> eyre::Result<Option<U256>>;

    /// Returns information about a transaction by block hash and transaction index position.
    fn get_transaction_by_block_hash_and_index(
        &self,
        block_hash: H256,
        index: Index,
    ) -> eyre::Result<Option<Transaction>>;

    /// Returns information about a transaction by block number and transaction index position.
    fn get_transaction_by_block_number_and_index(
        &self,
        block_number: BlockNumber,
        index: Index,
    ) -> eyre::Result<Option<Transaction>>;

    /// Returns addresses of the default bridge contracts.
    fn get_bridge_contracts(&self) -> eyre::Result<BridgeAddresses>;

    /// Returns confirmed tokens
    fn get_confirmed_tokens(
        &self,
        from: u32,
        limit: u8,
    ) -> eyre::Result<Vec<zksync_web3_decl::types::Token>>;
}

/// Holds the information about the original chain.
pub struct ForkDetails {
    // Source of the fork data (for example HttpForkSource)
    pub fork_source: Box<dyn ForkSource + Send + Sync>,
    // Block number at which we forked (the next block to create is l1_block + 1)
    pub l1_block: L1BatchNumber,
    // The actual L2 block
    pub l2_block: zksync_types::api::Block<zksync_types::api::TransactionVariant>,
    pub l2_miniblock: u64,
    pub l2_miniblock_hash: H256,
    pub block_timestamp: u64,
    pub overwrite_chain_id: Option<L2ChainId>,
    pub l1_gas_price: u64,
    pub l2_fair_gas_price: u64,
    /// L1 Gas Price Scale Factor for gas estimation.
    pub estimate_gas_price_scale_factor: f64,
    /// The factor by which to scale the gasLimit.
    pub estimate_gas_scale_factor: f32,
    pub fee_params: Option<FeeParams>,
    pub cache_config: CacheConfig,
}

const SUPPORTED_VERSIONS: &[ProtocolVersionId] = &[
    ProtocolVersionId::Version9,
    ProtocolVersionId::Version10,
    ProtocolVersionId::Version11,
    ProtocolVersionId::Version12,
    ProtocolVersionId::Version13,
    ProtocolVersionId::Version14,
    ProtocolVersionId::Version15,
    ProtocolVersionId::Version16,
    ProtocolVersionId::Version17,
    ProtocolVersionId::Version18,
    ProtocolVersionId::Version19,
    ProtocolVersionId::Version20,
    ProtocolVersionId::Version21,
    ProtocolVersionId::Version22,
    ProtocolVersionId::Version23,
    ProtocolVersionId::Version24,
    ProtocolVersionId::Version25,
];

pub fn supported_protocol_versions(version: ProtocolVersionId) -> bool {
    SUPPORTED_VERSIONS.contains(&version)
}

pub fn supported_versions_to_string() -> String {
    let versions: Vec<String> = SUPPORTED_VERSIONS
        .iter()
        .map(|v| format!("{:?}", v))
        .collect();
    versions.join(", ")
}

impl fmt::Debug for ForkDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ForkDetails")
            .field("l1_block", &self.l1_block)
            .field("l2_block", &self.l2_block)
            .field("l2_miniblock", &self.l2_miniblock)
            .field("l2_miniblock_hash", &self.l2_miniblock_hash)
            .field("block_timestamp", &self.block_timestamp)
            .field("overwrite_chain_id", &self.overwrite_chain_id)
            .field("l1_gas_price", &self.l1_gas_price)
            .field("l2_fair_gas_price", &self.l2_fair_gas_price)
            .finish()
    }
}

impl ForkDetails {
    pub async fn from_network_and_miniblock_and_chain(
        network: ForkNetwork,
        client: Client<L2>,
        miniblock: u64,
        chain_id: Option<L2ChainId>,
        cache_config: CacheConfig,
    ) -> Self {
        let url = network.to_url();
        let block_details = client
            .get_block_details(L2BlockNumber(miniblock as u32))
            .await
            .unwrap()
            .unwrap_or_else(|| panic!("Could not find block {:?} in {:?}", miniblock, url));

        let root_hash = block_details
            .base
            .root_hash
            .unwrap_or_else(|| panic!("fork block #{} missing root hash", miniblock));
        let block = client
            .get_block_by_hash(root_hash, true)
            .await
            .expect("failed retrieving block")
            .unwrap_or_else(|| {
                panic!(
                    "Could not find block #{:?} ({:#x}) in {:?}",
                    miniblock, root_hash, url
                )
            });
        let l1_batch_number = block_details.l1_batch_number;

        tracing::info!(
            "Creating fork from {:?} L1 block: {:?} L2 block: {:?} with timestamp {:?}, L1 gas price {:?}, L2 fair gas price {:?} and protocol version: {:?}" ,
            url, l1_batch_number, miniblock, block_details.base.timestamp, block_details.base.l1_gas_price, block_details.base.l2_fair_gas_price, block_details.protocol_version
        );

        if !block_details
            .protocol_version
            .map(supported_protocol_versions)
            .unwrap_or(false)
        {
            panic!(
                "This block is using the unsupported protocol version: {:?}. This binary supports versions {}.",
                block_details.protocol_version,
                supported_versions_to_string()
            );
        }

        let (estimate_gas_price_scale_factor, estimate_gas_scale_factor) =
            network.local_gas_scale_factors();
        let fee_params = client.get_fee_params().await.ok();

        ForkDetails {
            fork_source: Box::new(HttpForkSource::new(url.to_owned(), cache_config.clone())),
            l1_block: l1_batch_number,
            l2_block: block,
            block_timestamp: block_details.base.timestamp,
            l2_miniblock: miniblock,
            l2_miniblock_hash: root_hash,
            overwrite_chain_id: chain_id,
            l1_gas_price: block_details.base.l1_gas_price,
            l2_fair_gas_price: block_details.base.l2_fair_gas_price,
            estimate_gas_price_scale_factor,
            estimate_gas_scale_factor,
            fee_params,
            cache_config,
        }
    }
    /// Create a fork from a given network at a given height.
    pub async fn from_network(fork: &str, fork_at: Option<u64>, cache_config: CacheConfig) -> Self {
        let (network, client) = Self::fork_network_and_client(fork);
        let l2_miniblock = if let Some(fork_at) = fork_at {
            fork_at
        } else {
            client.get_block_number().await.unwrap().as_u64()
        };
        Self::from_network_and_miniblock_and_chain(
            network,
            client,
            l2_miniblock,
            None,
            cache_config,
        )
        .await
    }

    /// Create a fork from a given network, at a height BEFORE a transaction.
    /// This will allow us to apply this transaction locally on top of this fork.
    pub async fn from_network_tx(fork: &str, tx: H256, cache_config: CacheConfig) -> Self {
        let (network, client) = Self::fork_network_and_client(fork);
        let tx_details = client.get_transaction_by_hash(tx).await.unwrap().unwrap();
        let overwrite_chain_id = Some(
            L2ChainId::try_from(tx_details.chain_id.as_u64()).unwrap_or_else(|err| {
                panic!("erroneous chain id {}: {:?}", tx_details.chain_id, err,)
            }),
        );
        let miniblock_number = L2BlockNumber(tx_details.block_number.unwrap().as_u32());
        // We have to sync to the one-miniblock before the one where transaction is.
        let l2_miniblock = miniblock_number.saturating_sub(1) as u64;

        Self::from_network_and_miniblock_and_chain(
            network,
            client,
            l2_miniblock,
            overwrite_chain_id,
            cache_config,
        )
        .await
    }

    /// Return URL and HTTP client for `hardhat_reset`.
    pub fn from_url(
        url: String,
        fork_at: Option<u64>,
        cache_config: CacheConfig,
    ) -> eyre::Result<Self> {
        let parsed_url = SensitiveUrl::from_str(&url)?;
        let builder = match Client::http(parsed_url) {
            Ok(b) => b,
            Err(error) => {
                return Err(eyre::Report::msg(error));
            }
        };
        let client = builder.build();

        block_on(async move {
            let l2_miniblock = if let Some(fork_at) = fork_at {
                fork_at
            } else {
                client.get_block_number().await?.as_u64()
            };

            Ok(Self::from_network_and_miniblock_and_chain(
                ForkNetwork::Other(url),
                client,
                l2_miniblock,
                None,
                cache_config,
            )
            .await)
        })
    }

    /// Return [`ForkNetwork`] and HTTP client for a given fork name.
    pub fn fork_network_and_client(fork: &str) -> (ForkNetwork, Client<L2>) {
        let network = match fork {
            "mainnet" => ForkNetwork::Mainnet,
            "sepolia-testnet" => ForkNetwork::SepoliaTestnet,
            "goerli-testnet" => ForkNetwork::GoerliTestnet,
            _ => ForkNetwork::Other(fork.to_string()),
        };

        let url = network.to_url();
        let parsed_url = SensitiveUrl::from_str(url)
            .unwrap_or_else(|_| panic!("Unable to parse client URL: {}", &url));
        let client = Client::http(parsed_url)
            .unwrap_or_else(|_| panic!("Unable to create a client for fork: {}", &url))
            .build();

        (network, client)
    }

    /// Returns transactions that are in the same L2 miniblock as replay_tx, but were executed before it.
    pub async fn get_earlier_transactions_in_same_block(&self, replay_tx: H256) -> Vec<L2Tx> {
        let tx_details = self
            .fork_source
            .get_transaction_by_hash(replay_tx)
            .unwrap()
            .unwrap();
        let miniblock = L2BlockNumber(tx_details.block_number.unwrap().as_u32());

        // And we're fetching all the transactions from this miniblock.
        let block_transactions = self
            .fork_source
            .get_raw_block_transactions(miniblock)
            .unwrap();

        let mut tx_to_apply = Vec::new();

        for tx in block_transactions {
            let h = tx.hash();
            let l2_tx: L2Tx = tx.try_into().unwrap();
            tx_to_apply.push(l2_tx);

            if h == replay_tx {
                return tx_to_apply;
            }
        }
        panic!(
            "Cound not find tx {:?} in miniblock: {:?}",
            replay_tx, miniblock
        );
    }
}

#[cfg(test)]
mod tests {
    use zksync_basic_types::{AccountTreeId, L1BatchNumber, H256};
    use zksync_state::ReadStorage;
    use zksync_types::{api::TransactionVariant, StorageKey};

    use crate::config::cache::CacheConfig;
    use crate::config::gas::{
        DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR,
        DEFAULT_L2_GAS_PRICE,
    };
    use crate::{deps::InMemoryStorage, system_contracts, testing};

    use super::{ForkDetails, ForkStorage};

    #[test]
    fn test_initial_writes() {
        let account = AccountTreeId::default();
        let never_written_key = StorageKey::new(account, H256::from_low_u64_be(1));
        let key_with_some_value = StorageKey::new(account, H256::from_low_u64_be(2));
        let key_with_value_0 = StorageKey::new(account, H256::from_low_u64_be(3));
        let mut in_memory_storage = InMemoryStorage::default();
        in_memory_storage.set_value(key_with_some_value, H256::from_low_u64_be(13));
        in_memory_storage.set_value(key_with_value_0, H256::from_low_u64_be(0));

        let external_storage = testing::ExternalStorage {
            raw_storage: in_memory_storage,
        };

        let options = system_contracts::Options::default();

        let fork_details = ForkDetails {
            fork_source: Box::new(external_storage),
            l1_block: L1BatchNumber(1),
            l2_block: zksync_types::api::Block::<TransactionVariant>::default(),
            l2_miniblock: 1,
            l2_miniblock_hash: H256::zero(),
            block_timestamp: 0,
            overwrite_chain_id: None,
            l1_gas_price: 100,
            l2_fair_gas_price: DEFAULT_L2_GAS_PRICE,
            estimate_gas_price_scale_factor: DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR,
            estimate_gas_scale_factor: DEFAULT_ESTIMATE_GAS_SCALE_FACTOR,
            fee_params: None,
            cache_config: CacheConfig::None,
        };

        let mut fork_storage: ForkStorage<testing::ExternalStorage> =
            ForkStorage::new(Some(fork_details), &options);

        assert!(fork_storage.is_write_initial(&never_written_key));
        assert!(!fork_storage.is_write_initial(&key_with_some_value));
        // This is the current limitation of the sytem. In theory, this should return false - as the value was written, but we don't have the API to the
        // backend to get this information.
        assert!(fork_storage.is_write_initial(&key_with_value_0));

        // But writing any value there in the local storage (even 0) - should make it non-initial write immediately.
        fork_storage.set_value(key_with_value_0, H256::zero());
        assert!(!fork_storage.is_write_initial(&key_with_value_0));
    }
}