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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
use async_trait::async_trait;
use ethers::{
    abi::{HumanReadableParser, Token, Tokenize},
    prelude::{
        k256::{
            ecdsa::{RecoveryId, Signature as RecoverableSignature},
            schnorr::signature::hazmat::PrehashSigner,
        },
        SignerMiddleware,
    },
    providers::{JsonRpcClient, Middleware, Provider, ProviderError},
    signers::{Signer, Wallet},
    types::{
        transaction::{eip2718::TypedTransaction, eip712::Eip712Error},
        Address, BlockNumber, Eip1559TransactionRequest, Signature, TransactionReceipt, TxHash,
        H256, U256, U64,
    },
};
use ethers_contract::providers::PendingTransaction;
use serde::Serialize;
use serde_json::json;
use std::{collections::HashMap, fmt::Debug, time::Duration};
use tokio::time::Instant;

pub mod types;
use types::Fee;

use crate::{
    eip712::{Eip712Meta, Eip712Transaction, Eip712TransactionRequest},
    zks_utils::{self, DEFAULT_GAS, EIP712_TX_TYPE, MAX_FEE_PER_GAS, MAX_PRIORITY_FEE_PER_GAS},
    zks_wallet::{CallRequest, Overrides},
};

use self::types::{
    BlockDetails, BlockRange, BridgeContracts, DebugTrace, L1BatchDetails, Proof, TokenInfo,
    TracerConfig, Transaction, TransactionDetails,
};

/// This trait wraps every JSON-RPC call specified in zkSync Era's documentation
/// https://era.zksync.io/docs/api/api.html#zksync-era-json-rpc-methods
#[async_trait]
pub trait ZKSProvider {
    type Provider: JsonRpcClient;
    type ZKProvider: JsonRpcClient;

    async fn zk_estimate_gas<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync;

    /// Returns the fee for the transaction.
    async fn estimate_fee<T>(&self, transaction: T) -> Result<Fee, ProviderError>
    where
        T: Debug + Serialize + Send + Sync;

    /// Returns an estimate of the gas required for a L1 to L2 transaction.
    async fn estimate_gas_l1_to_l2<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync;

    /// Returns all balances for confirmed tokens given by an account address.
    async fn get_all_account_balances(
        &self,
        address: Address,
    ) -> Result<HashMap<Address, U256>, ProviderError>;

    /// Returns additional zkSync-specific information about the L2 block.
    /// * `committed`: The batch is closed and the state transition it creates exists on layer 1.
    /// * `proven`: The batch proof has been created, submitted, and accepted on layer 1.
    /// * `executed`: The batch state transition has been executed on L1; meaning the root state has been updated.
    async fn get_block_details<T>(&self, block: T) -> Result<Option<BlockDetails>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Returns L1/L2 addresses of default bridges.
    async fn get_bridge_contracts(&self) -> Result<BridgeContracts, ProviderError>;

    /// Returns bytecode of a transaction given by its hash.
    async fn get_bytecode_by_hash(&self, hash: H256) -> Result<Option<Vec<u8>>, ProviderError>;

    /// Returns [address, symbol, name, and decimal] information of all tokens within a range of ids given by parameters `from` and `limit`.
    ///
    /// **Confirmed** in the method name means the method returns any token bridged to zkSync via the official bridge.
    ///
    /// > This method is mainly used by the zkSync team as it relates to a database query where the primary keys relate to the given ids.
    async fn get_confirmed_tokens(
        &self,
        from: u32,
        limit: u8,
    ) -> Result<Vec<TokenInfo>, ProviderError>;

    /// Returns the range of blocks contained within a batch given by batch number.
    ///
    /// The range is given by beginning/end block numbers in hexadecimal.
    async fn get_l1_batch_block_range<T>(&self, batch: T) -> Result<BlockRange, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Returns data pertaining to a given batch.
    async fn get_l1_batch_details<T>(&self, batch: T) -> Result<L1BatchDetails, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Given a transaction hash, and an index of the L2 to L1 log produced within the
    /// transaction, it returns the proof for the corresponding L2 to L1 log.
    ///
    /// The index of the log that can be obtained from the transaction receipt (it
    /// includes a list of every log produced by the transaction).
    async fn get_l2_to_l1_log_proof(
        &self,
        tx_hash: H256,
        l2_to_l1_log_index: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError>;

    /// Given a block, a sender, a message, and an optional message log index in the
    /// block containing the L1->L2 message, it returns the proof for the message sent
    /// via the L1Messenger system contract.
    async fn get_l2_to_l1_msg_proof<T>(
        &self,
        block: T,
        sender: Address,
        msg: H256,
        l2_log_position: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Returns the address of the zkSync Era contract.
    async fn get_main_contract(&self) -> Result<Address, ProviderError>;

    /// Returns data of transactions in a block.
    async fn get_raw_block_transactions<T>(
        &self,
        block: T,
    ) -> Result<Vec<Transaction>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Returns the address of the [testnet paymaster](https://era.zksync.io/docs/dev/developer-guides/aa.html#testnet-paymaster): the paymaster that is available
    /// on testnets and enables paying fees in ERC-20 compatible tokens.
    async fn get_testnet_paymaster(&self) -> Result<Address, ProviderError>;

    /// Returns the price of a given token in USD.
    async fn get_token_price(&self, address: Address) -> Result<String, ProviderError>;

    /// Returns data from a specific transaction given by the transaction hash.
    async fn get_transaction_details(
        &self,
        hash: H256,
    ) -> Result<Option<TransactionDetails>, ProviderError>;

    /// Returns the latest L1 batch number.
    async fn get_l1_batch_number(&self) -> Result<U256, ProviderError>;

    /// Returns the chain id of the underlying L1.
    async fn get_l1_chain_id(&self) -> Result<U256, ProviderError>;

    /// Returns debug trace of all executed calls contained in a block given by its L2 hash.
    async fn debug_trace_block_by_hash(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>;

    /// Returns debug trace of all executed calls contained in a block given by its L2 block number.
    async fn debug_trace_block_by_number<T>(
        &self,
        block: T,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Returns debug trace containing information on a specific calls given by the call request.
    async fn debug_trace_call<R, T>(
        &self,
        request: R,
        block: Option<T>,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        R: Debug + Serialize + Send + Sync,
        T: Into<U64> + Send + Sync + Serialize + Debug;

    /// Uses the EVM's callTracer to return a debug trace of a specific transaction given by its transaction hash.
    async fn debug_trace_transaction(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>;

    async fn send_eip712<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync;

    async fn send<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::Provider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync;

    async fn wait_for_finalize(
        &self,
        transaction_receipt: TxHash,
        polling_time_in_seconds: Option<Duration>,
        timeout_in_seconds: Option<Duration>,
    ) -> Result<TransactionReceipt, ProviderError>;

    async fn call(&self, request: &CallRequest) -> Result<Vec<Token>, ProviderError>;

    async fn send_transaction_eip712<T, D>(
        &self,
        wallet: &Wallet<D>,
        transaction: T,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        T: TryInto<Eip712TransactionRequest> + Send + Sync + Debug,
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync;
}

#[async_trait]
impl<M: Middleware + ZKSProvider, S: Signer> ZKSProvider for SignerMiddleware<M, S> {
    type Provider = <M as Middleware>::Provider;
    type ZKProvider = <M as ZKSProvider>::ZKProvider;

    async fn zk_estimate_gas<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        <M as ZKSProvider>::zk_estimate_gas(self.inner(), transaction).await
    }

    async fn estimate_fee<T>(&self, transaction: T) -> Result<Fee, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        self.inner().estimate_fee(transaction).await
    }

    async fn estimate_gas_l1_to_l2<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        self.inner().estimate_gas_l1_to_l2(transaction).await
    }

    async fn get_all_account_balances(
        &self,
        address: Address,
    ) -> Result<HashMap<Address, U256>, ProviderError> {
        self.inner().get_all_account_balances(address).await
    }

    async fn get_block_details<T>(&self, block: T) -> Result<Option<BlockDetails>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.inner().get_block_details(block).await
    }

    async fn get_bridge_contracts(&self) -> Result<BridgeContracts, ProviderError> {
        self.inner().get_bridge_contracts().await
    }

    async fn get_bytecode_by_hash(&self, hash: H256) -> Result<Option<Vec<u8>>, ProviderError> {
        self.inner().get_bytecode_by_hash(hash).await
    }

    async fn get_confirmed_tokens(
        &self,
        from: u32,
        limit: u8,
    ) -> Result<Vec<TokenInfo>, ProviderError> {
        self.inner().get_confirmed_tokens(from, limit).await
    }

    async fn get_l1_batch_block_range<T>(&self, batch_id: T) -> Result<BlockRange, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.inner().get_l1_batch_block_range(batch_id).await
    }

    async fn get_l1_batch_details<T>(&self, batch_id: T) -> Result<L1BatchDetails, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.inner().get_l1_batch_details(batch_id).await
    }

    async fn get_l2_to_l1_log_proof(
        &self,
        tx_hash: H256,
        l2_to_l1_log_index: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError> {
        self.inner()
            .get_l2_to_l1_log_proof(tx_hash, l2_to_l1_log_index)
            .await
    }

    async fn get_l2_to_l1_msg_proof<T>(
        &self,
        block: T,
        sender: Address,
        msg: H256,
        l2_log_position: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.inner()
            .get_l2_to_l1_msg_proof(block, sender, msg, l2_log_position)
            .await
    }

    async fn get_main_contract(&self) -> Result<Address, ProviderError> {
        self.inner().get_main_contract().await
    }

    async fn get_raw_block_transactions<T>(
        &self,
        block: T,
    ) -> Result<Vec<Transaction>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.inner().get_raw_block_transactions(block).await
    }

    async fn get_testnet_paymaster(&self) -> Result<Address, ProviderError> {
        self.inner().get_testnet_paymaster().await
    }

    async fn get_token_price(&self, address: Address) -> Result<String, ProviderError> {
        self.inner().get_token_price(address).await
    }

    async fn get_transaction_details(
        &self,
        hash: H256,
    ) -> Result<Option<TransactionDetails>, ProviderError> {
        self.inner().get_transaction_details(hash).await
    }

    async fn get_l1_batch_number(&self) -> Result<U256, ProviderError> {
        self.inner().get_l1_batch_number().await
    }

    async fn get_l1_chain_id(&self) -> Result<U256, ProviderError> {
        self.inner().get_l1_chain_id().await
    }

    async fn debug_trace_block_by_hash(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError> {
        ZKSProvider::debug_trace_block_by_hash(self.inner(), hash, options).await
    }

    async fn debug_trace_block_by_number<T>(
        &self,
        block: T,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        ZKSProvider::debug_trace_block_by_number(self.inner(), block, options).await
    }

    async fn debug_trace_call<R, T>(
        &self,
        request: R,
        block: Option<T>,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        R: Debug + Serialize + Send + Sync,
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        ZKSProvider::debug_trace_call(self.inner(), request, block, options).await
    }

    async fn debug_trace_transaction(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError> {
        ZKSProvider::debug_trace_transaction(self.inner(), hash, options).await
    }

    async fn send_eip712<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        self.inner()
            .send_eip712(
                wallet,
                contract_address,
                function_signature,
                function_parameters,
                overrides,
            )
            .await
    }

    async fn send<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        _overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::Provider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        let tx = build_send_tx(
            self,
            wallet,
            contract_address,
            function_signature,
            function_parameters,
            _overrides,
        )
        .await?;
        self.send_transaction(tx, None)
            .await
            .map_err(|e| ProviderError::CustomError(format!("Error sending transaction: {e:?}")))
    }

    async fn send_transaction_eip712<T, D>(
        &self,
        wallet: &Wallet<D>,
        transaction: T,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        T: TryInto<Eip712TransactionRequest> + Sync + Send + Debug,
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        self.inner()
            .send_transaction_eip712(wallet, transaction)
            .await
    }

    async fn wait_for_finalize(
        &self,
        transaction_receipt: TxHash,
        polling_time_in_seconds: Option<Duration>,
        timeout_in_seconds: Option<Duration>,
    ) -> Result<TransactionReceipt, ProviderError> {
        self.inner()
            .wait_for_finalize(
                transaction_receipt,
                polling_time_in_seconds,
                timeout_in_seconds,
            )
            .await
    }

    async fn call(&self, request: &CallRequest) -> Result<Vec<Token>, ProviderError> {
        ZKSProvider::call(self.inner(), request).await
    }
}

#[async_trait]
impl<P: JsonRpcClient> ZKSProvider for Provider<P> {
    type Provider = P;
    type ZKProvider = P;

    async fn zk_estimate_gas<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        self.request("eth_estimateGas", [transaction]).await
    }

    async fn estimate_fee<T>(&self, transaction: T) -> Result<Fee, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        self.request("zks_estimateFee", [transaction]).await
    }

    async fn estimate_gas_l1_to_l2<T>(&self, transaction: T) -> Result<U256, ProviderError>
    where
        T: Debug + Serialize + Send + Sync,
    {
        self.request("zks_estimateGasL1ToL2", [transaction]).await
    }

    async fn get_all_account_balances(
        &self,
        address: Address,
    ) -> Result<HashMap<Address, U256>, ProviderError> {
        self.request("zks_getAllAccountBalances", [address]).await
    }

    async fn get_block_details<T>(&self, block: T) -> Result<Option<BlockDetails>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request("zks_getBlockDetails", [block]).await
    }

    async fn get_bridge_contracts(&self) -> Result<BridgeContracts, ProviderError> {
        self.request("zks_getBridgeContracts", ()).await
    }

    async fn get_bytecode_by_hash(&self, hash: H256) -> Result<Option<Vec<u8>>, ProviderError> {
        self.request("zks_getBytecodeByHash", [hash]).await
    }

    async fn get_confirmed_tokens(
        &self,
        from: u32,
        limit: u8,
    ) -> Result<Vec<TokenInfo>, ProviderError> {
        self.request("zks_getConfirmedTokens", [from, limit.into()])
            .await
    }

    async fn get_l1_batch_block_range<T>(&self, batch: T) -> Result<BlockRange, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request("zks_getL1BatchBlockRange", [batch]).await
    }

    async fn get_l1_batch_details<T>(&self, batch: T) -> Result<L1BatchDetails, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request("zks_getL1BatchDetails", [batch]).await
    }

    async fn get_l2_to_l1_log_proof(
        &self,
        tx_hash: H256,
        l2_to_l1_log_index: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError> {
        self.request(
            "zks_getL2ToL1LogProof",
            json!([tx_hash, l2_to_l1_log_index]),
        )
        .await
    }

    async fn get_l2_to_l1_msg_proof<T>(
        &self,
        block: T,
        sender: Address,
        msg: H256,
        l2_log_position: Option<u64>,
    ) -> Result<Option<Proof>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request(
            "zks_getL2ToL1MsgProof",
            json!([block, sender, msg, l2_log_position]),
        )
        .await
    }

    async fn get_main_contract(&self) -> Result<Address, ProviderError> {
        self.request("zks_getMainContract", ()).await
    }

    async fn get_raw_block_transactions<T>(
        &self,
        block: T,
    ) -> Result<Vec<Transaction>, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request("zks_getRawBlockTransactions", [block]).await
    }

    async fn get_testnet_paymaster(&self) -> Result<Address, ProviderError> {
        self.request("zks_getTestnetPaymaster", ()).await
    }

    async fn get_token_price(&self, address: Address) -> Result<String, ProviderError> {
        self.request("zks_getTokenPrice", [address]).await
    }

    async fn get_transaction_details(
        &self,
        hash: H256,
    ) -> Result<Option<TransactionDetails>, ProviderError> {
        self.request("zks_getTransactionDetails", [hash]).await
    }

    async fn get_l1_batch_number(&self) -> Result<U256, ProviderError> {
        self.request("zks_L1BatchNumber", ()).await
    }

    async fn get_l1_chain_id(&self) -> Result<U256, ProviderError> {
        self.request("zks_L1ChainId", ()).await
    }

    async fn debug_trace_block_by_hash(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError> {
        let processable_response = self
            .request::<serde_json::Value, serde_json::Value>(
                "debug_traceBlockByHash",
                json!([hash, options]),
            )
            .await?
            .get(0)
            .ok_or(ProviderError::CustomError(
                "error on debug_trace_block_by_hash".to_owned(),
            ))?
            .get("result")
            .ok_or(ProviderError::CustomError(
                "error on debug_trace_block_by_hash".to_owned(),
            ))?
            .clone();
        serde_json::from_value(processable_response).map_err(ProviderError::SerdeJson)
    }

    async fn debug_trace_block_by_number<T>(
        &self,
        block: T,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        let processable_response = self
            .request::<serde_json::Value, serde_json::Value>(
                "debug_traceBlockByNumber",
                json!([block, options]),
            )
            .await?
            .get(0)
            .ok_or(ProviderError::CustomError(
                "error on debug_trace_block_by_hash".to_owned(),
            ))?
            .get("result")
            .ok_or(ProviderError::CustomError(
                "error on debug_trace_block_by_hash".to_owned(),
            ))?
            .clone();
        serde_json::from_value(processable_response).map_err(ProviderError::SerdeJson)
    }

    async fn debug_trace_call<R, T>(
        &self,
        request: R,
        block: Option<T>,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError>
    where
        R: Debug + Serialize + Send + Sync,
        T: Into<U64> + Send + Sync + Serialize + Debug,
    {
        self.request("debug_traceCall", json!([request, block, options]))
            .await
    }

    async fn debug_trace_transaction(
        &self,
        hash: H256,
        options: Option<TracerConfig>,
    ) -> Result<DebugTrace, ProviderError> {
        self.request("debug_traceTransaction", json!([hash, options]))
            .await
    }

    async fn send_transaction_eip712<T, D>(
        &self,
        wallet: &Wallet<D>,
        transaction: T,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        T: TryInto<Eip712TransactionRequest> + Sync + Send + Debug,
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        let mut request: Eip712TransactionRequest = transaction.try_into().map_err(|_e| {
            ProviderError::CustomError("error on send_transaction_eip712".to_owned())
        })?;

        let gas_price = self.get_gas_price().await?;
        request = request
            .from(wallet.address())
            .chain_id(wallet.chain_id())
            .nonce(self.get_transaction_count(wallet.address(), None).await?)
            .gas_price(gas_price)
            .max_fee_per_gas(gas_price);

        let custom_data = request.clone().custom_data;
        let fee = self.estimate_fee(request.clone()).await?;
        request = request
            .max_priority_fee_per_gas(fee.max_priority_fee_per_gas)
            .max_fee_per_gas(fee.max_fee_per_gas)
            .gas_limit(fee.gas_limit);
        let signable_data: Eip712Transaction = request
            .clone()
            .try_into()
            .map_err(|e: Eip712Error| ProviderError::CustomError(e.to_string()))?;
        let signature: Signature = wallet
            .sign_typed_data(&signable_data)
            .await
            .map_err(|e| ProviderError::CustomError(format!("error signing transaction: {e}")))?;
        request = request.custom_data(custom_data.custom_signature(signature.to_vec()));
        let encoded_rlp = &*request
            .rlp_signed(signature)
            .map_err(|e| ProviderError::CustomError(format!("Error in the rlp encoding {e}")))?;

        self.send_raw_transaction([&[EIP712_TX_TYPE], encoded_rlp].concat().into())
            .await
    }

    async fn send_eip712<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::ZKProvider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        // Note: We couldn't implement ProviderError::LexerError because ethers-rs's LexerError is not exposed.
        // TODO check for ECADD precompile address to get the function signature.
        let function = HumanReadableParser::parse_function(function_signature)
            .map_err(|e| ProviderError::CustomError(e.to_string()))?;

        let mut send_request = if let Some(overrides) = overrides {
            Eip712TransactionRequest::from_overrides(overrides)
        } else {
            Eip712TransactionRequest::new()
        };

        let function_args = if let Some(function_args) = function_parameters {
            function
                .decode_input(
                    &zks_utils::encode_args(&function, &function_args)
                        .map_err(|e| ProviderError::CustomError(e.to_string()))?,
                )
                .map_err(|e| ProviderError::CustomError(e.to_string()))?
        } else {
            vec![]
        };

        send_request = send_request
            .r#type(EIP712_TX_TYPE)
            .from(wallet.address())
            .to(contract_address)
            .chain_id(wallet.chain_id())
            .nonce(self.get_transaction_count(wallet.address(), None).await?)
            .gas_price(self.get_gas_price().await?)
            .max_fee_per_gas(self.get_gas_price().await?)
            .data(if !function_args.is_empty() {
                function
                    .encode_input(&function_args)
                    .map_err(|e| ProviderError::CustomError(e.to_string()))?
            } else {
                function.short_signature().into()
            });

        let fee = self.estimate_fee(send_request.clone()).await?;
        send_request = send_request
            .max_priority_fee_per_gas(fee.max_priority_fee_per_gas)
            .max_fee_per_gas(fee.max_fee_per_gas)
            .gas_limit(fee.gas_limit);

        let signable_data: Eip712Transaction = send_request
            .clone()
            .try_into()
            .map_err(|e: Eip712Error| ProviderError::CustomError(e.to_string()))?;
        let signature: Signature = wallet
            .sign_typed_data(&signable_data)
            .await
            .map_err(|e| ProviderError::CustomError(format!("error signing transaction: {e}")))?;
        send_request =
            send_request.custom_data(Eip712Meta::new().custom_signature(signature.to_vec()));

        let encoded_rlp = &*send_request
            .rlp_signed(signature)
            .map_err(|e| ProviderError::CustomError(format!("error encoding transaction: {e}")))?;
        self.send_raw_transaction([&[EIP712_TX_TYPE], encoded_rlp].concat().into())
            .await
    }

    async fn send<D>(
        &self,
        wallet: &Wallet<D>,
        contract_address: Address,
        function_signature: &str,
        function_parameters: Option<Vec<String>>,
        _overrides: Option<Overrides>,
    ) -> Result<PendingTransaction<Self::Provider>, ProviderError>
    where
        D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
    {
        let tx = build_send_tx(
            self,
            wallet,
            contract_address,
            function_signature,
            function_parameters,
            _overrides,
        )
        .await?;
        self.send_transaction(tx, None).await
    }

    async fn wait_for_finalize(
        &self,
        tx_hash: TxHash,
        polling_time_in_seconds: Option<Duration>,
        timeout_in_seconds: Option<Duration>,
    ) -> Result<TransactionReceipt, ProviderError> {
        let polling_time_in_seconds = polling_time_in_seconds.unwrap_or(Duration::from_secs(2));
        let mut timer = tokio::time::interval(polling_time_in_seconds);
        let start = Instant::now();

        let transaction_receipt =
            self.get_transaction_receipt(tx_hash)
                .await?
                .ok_or(ProviderError::CustomError(
                    "No transaction receipt".to_owned(),
                ))?;

        loop {
            timer.tick().await;

            if let Some(timeout) = timeout_in_seconds {
                if start.elapsed() >= timeout {
                    return Err(ProviderError::CustomError(
                        "Error waiting for transaction to be included into the finalized block"
                            .to_owned(),
                    ));
                }
            }

            // Wait for transaction to be included into the finalized block.
            let latest_block =
                self.get_block(BlockNumber::Finalized)
                    .await?
                    .ok_or(ProviderError::CustomError(
                        "Error getting finalized block".to_owned(),
                    ))?;

            if transaction_receipt.block_number <= latest_block.number {
                return Ok(transaction_receipt);
            }
        }
    }

    async fn call(&self, request: &CallRequest) -> Result<Vec<Token>, ProviderError> {
        let function = request
            .get_parsed_function()
            .map_err(|e| ProviderError::CustomError(format!("Failed to parse function: {e}")))?;
        let request: Eip1559TransactionRequest = request
            .clone()
            .try_into()
            .map_err(|e| ProviderError::CustomError(format!("Failed to convert request: {e}")))?;
        let transaction: TypedTransaction = request.into();

        let encoded_output = Middleware::call(self, &transaction, None).await?;
        let decoded_output = function.decode_output(&encoded_output).map_err(|e| {
            ProviderError::CustomError(format!("failed to decode output: {e}\n{encoded_output}"))
        })?;

        Ok(if decoded_output.is_empty() {
            encoded_output.into_tokens()
        } else {
            decoded_output
        })
    }
}

async fn build_send_tx<D>(
    provider: &impl Middleware,
    wallet: &Wallet<D>,
    contract_address: Address,
    function_signature: &str,
    function_parameters: Option<Vec<String>>,
    _overrides: Option<Overrides>,
) -> Result<TypedTransaction, ProviderError>
where
    D: PrehashSigner<(RecoverableSignature, RecoveryId)> + Send + Sync,
{
    let function = HumanReadableParser::parse_function(function_signature)
        .map_err(|e| ProviderError::CustomError(e.to_string()))?;

    let function_args = if let Some(function_args) = function_parameters {
        function
            .decode_input(
                &zks_utils::encode_args(&function, &function_args)
                    .map_err(|e| ProviderError::CustomError(e.to_string()))?,
            )
            .map_err(|e| ProviderError::CustomError(e.to_string()))?
    } else {
        vec![]
    };

    // Sending transaction calling the main contract.
    let send_request = Eip1559TransactionRequest::new()
        .from(wallet.address())
        .to(contract_address)
        .chain_id(wallet.chain_id())
        .nonce(
            provider
                .get_transaction_count(wallet.address(), None)
                .await
                .map_err(|e| ProviderError::CustomError(e.to_string()))?,
        )
        .data(if !function_args.is_empty() {
            function
                .encode_input(&function_args)
                .map_err(|e| ProviderError::CustomError(e.to_string()))?
        } else {
            function.short_signature().into()
        })
        .value(0_u8)
        //FIXME we should use default calculation for gas related fields.
        .gas(DEFAULT_GAS)
        .max_fee_per_gas(MAX_FEE_PER_GAS)
        .max_priority_fee_per_gas(MAX_PRIORITY_FEE_PER_GAS);

    Ok(send_request.into())
}