-
Notifications
You must be signed in to change notification settings - Fork 76
/
eth.rs
3504 lines (3184 loc) · 127 KB
/
eth.rs
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashSet;
use anyhow::Context as _;
use colored::Colorize;
use futures::FutureExt;
use itertools::Itertools;
use zksync_multivm::interface::ExecutionResult;
use zksync_multivm::vm_latest::constants::ETH_CALL_GAS_LIMIT;
use zksync_types::{
api::{Block, BlockIdVariant, BlockNumber, TransactionVariant},
fee::Fee,
get_code_key, get_nonce_key,
l2::L2Tx,
transaction_request::TransactionRequest,
utils::storage_key_for_standard_token_balance,
PackedEthSignature, StorageKey, L2_BASE_TOKEN_ADDRESS, MAX_L1_TRANSACTION_GAS_LIMIT,
};
use zksync_types::{
web3::{self, Bytes},
AccountTreeId, Address, H160, H256, U256, U64,
};
use zksync_utils::{h256_to_u256, u256_to_h256};
use zksync_web3_decl::{
error::Web3Error,
types::{FeeHistory, Filter, FilterChanges, SyncState},
};
use crate::{
filters::{FilterType, LogFilter},
fork::ForkSource,
namespaces::{EthNamespaceT, EthTestNodeNamespaceT, RpcResult},
node::{InMemoryNode, TransactionResult, MAX_TX_SIZE, PROTOCOL_VERSION},
utils::{
self, h256_to_u64, into_jsrpc_error, not_implemented, report_into_jsrpc_error,
IntoBoxedFuture, TransparentError,
},
};
impl<S: ForkSource + std::fmt::Debug + Clone + Send + Sync + 'static> InMemoryNode<S> {
fn call_impl(
&self,
req: zksync_types::transaction_request::CallRequest,
) -> Result<Bytes, Web3Error> {
let system_contracts = self.system_contracts_for_l2_call()?;
let allow_no_target = system_contracts.evm_emulator.is_some();
let mut tx = L2Tx::from_request(req.into(), MAX_TX_SIZE, allow_no_target)?;
tx.common_data.fee.gas_limit = ETH_CALL_GAS_LIMIT.into();
let call_result = self
.run_l2_call(tx, system_contracts)
.context("Invalid data due to invalid name")?;
match call_result {
ExecutionResult::Success { output } => Ok(output.into()),
ExecutionResult::Revert { output } => {
let message = output.to_user_friendly_string();
let pretty_message = format!(
"execution reverted{}{}",
if message.is_empty() { "" } else { ": " },
message
);
tracing::info!("{}", pretty_message.on_red());
Err(Web3Error::SubmitTransactionError(
pretty_message,
output.encoded_data(),
))
}
ExecutionResult::Halt { reason } => {
let message = reason.to_string();
let pretty_message = format!(
"execution halted {}{}",
if message.is_empty() { "" } else { ": " },
message
);
tracing::info!("{}", pretty_message.on_red());
Err(Web3Error::SubmitTransactionError(pretty_message, vec![]))
}
}
}
fn send_raw_transaction_impl(&self, tx_bytes: Bytes) -> Result<H256, Web3Error> {
let chain_id = self
.get_inner()
.read()
.map_err(|_| anyhow::anyhow!("Failed to acquire read lock for chain ID retrieval"))?
.fork_storage
.chain_id;
let (tx_req, hash) = TransactionRequest::from_bytes(&tx_bytes.0, chain_id)?;
let system_contracts = self.system_contracts_for_tx(tx_req.from.unwrap_or_default())?;
let allow_no_target = system_contracts.evm_emulator.is_some();
let mut l2_tx = L2Tx::from_request(tx_req, MAX_TX_SIZE, allow_no_target)?;
l2_tx.set_input(tx_bytes.0, hash);
if hash != l2_tx.hash() {
let err = anyhow::anyhow!(
"Invalid transaction data: computed hash does not match the provided hash."
);
return Err(err.into());
};
self.run_l2_tx(l2_tx, system_contracts).map_err(|err| {
Web3Error::SubmitTransactionError(
format!("Execution error: {err}"),
hash.as_bytes().to_vec(),
)
})?;
Ok(hash)
}
fn send_transaction_impl(
&self,
tx: zksync_types::transaction_request::CallRequest,
) -> Result<H256, Web3Error> {
let (chain_id, l1_gas_price) = {
let reader = self
.inner
.read()
.map_err(|_| anyhow::anyhow!("Failed to acquire read lock"))?;
(
reader.fork_storage.chain_id,
reader.fee_input_provider.l1_gas_price,
)
};
let mut tx_req = TransactionRequest::from(tx.clone());
// Users might expect a "sensible default"
if tx.gas.is_none() {
tx_req.gas = U256::from(MAX_L1_TRANSACTION_GAS_LIMIT);
}
tx_req.chain_id = Some(chain_id.as_u64());
// EIP-1559 gas fields should be processed separately
if tx.gas_price.is_some() {
if tx.max_fee_per_gas.is_some() || tx.max_priority_fee_per_gas.is_some() {
let err = "Transaction contains unsupported fields: max_fee_per_gas or max_priority_fee_per_gas";
tracing::error!("{err}");
return Err(TransparentError(err.into()).into());
}
} else {
tx_req.gas_price = tx.max_fee_per_gas.unwrap_or(U256::from(l1_gas_price));
tx_req.max_priority_fee_per_gas = tx.max_priority_fee_per_gas;
if tx_req.transaction_type.is_none() {
tx_req.transaction_type = Some(zksync_types::EIP_1559_TX_TYPE.into());
}
}
// Needed to calculate hash
tx_req.r = Some(U256::default());
tx_req.s = Some(U256::default());
tx_req.v = Some(U64::from(27));
let hash = tx_req.get_tx_hash()?;
let bytes = tx_req.get_signed_bytes(&PackedEthSignature::from_rsv(
&H256::default(),
&H256::default(),
27,
))?;
let system_contracts = self.system_contracts_for_tx(tx_req.from.unwrap_or_default())?;
let allow_no_target = system_contracts.evm_emulator.is_some();
let mut l2_tx: L2Tx = L2Tx::from_request(tx_req, MAX_TX_SIZE, allow_no_target)?;
// `v` was overwritten with 0 during converting into l2 tx
let mut signature = vec![0u8; 65];
signature[64] = 27;
l2_tx.common_data.signature = signature;
l2_tx.set_input(bytes, hash);
{
let reader = self
.inner
.read()
.map_err(|_| anyhow::anyhow!("Failed to acquire read lock for accounts."))?;
if !reader
.impersonated_accounts
.contains(&l2_tx.common_data.initiator_address)
{
let err = format!(
"Initiator address {:?} is not allowed to perform transactions",
l2_tx.common_data.initiator_address
);
tracing::error!("{err}");
return Err(TransparentError(err).into());
}
}
self.run_l2_tx(l2_tx, system_contracts).map_err(|err| {
Web3Error::SubmitTransactionError(
format!("Execution error: {err}"),
hash.as_bytes().to_vec(),
)
})?;
Ok(hash)
}
}
impl<S: ForkSource + std::fmt::Debug + Clone + Send + Sync + 'static> EthNamespaceT
for InMemoryNode<S>
{
/// Returns the chain ID of the node.
fn chain_id(&self) -> RpcResult<zksync_types::U64> {
match self.get_inner().read() {
Ok(inner) => Ok(U64::from(inner.fork_storage.chain_id.as_u64())).into_boxed_future(),
Err(_) => Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for chain ID retrieval"),
)))
.into_boxed_future(),
}
}
/// Calls the specified function on the L2 contract with the given arguments.
///
/// # Arguments
///
/// * `req` - The call request containing the function name and arguments.
/// * `_block` - The block ID variant (unused).
///
/// # Returns
///
/// A boxed future containing the result of the function call.
fn call(
&self,
req: zksync_types::transaction_request::CallRequest,
_block: Option<BlockIdVariant>,
) -> RpcResult<Bytes> {
self.call_impl(req)
.map_err(into_jsrpc_error)
.into_boxed_future()
}
/// Returns the balance of the specified address.
///
/// # Arguments
///
/// * `address` - The address to get the balance of.
/// * `_block` - The block ID variant (optional).
///
/// # Returns
///
/// A `BoxFuture` that resolves to a `Result` containing the balance of the specified address as a `U256` or a `jsonrpc_core::Error` if an error occurred.
fn get_balance(&self, address: Address, _block: Option<BlockIdVariant>) -> RpcResult<U256> {
let inner = self.get_inner().clone();
Box::pin(async move {
let balance_key = storage_key_for_standard_token_balance(
AccountTreeId::new(L2_BASE_TOKEN_ADDRESS),
&address,
);
match inner.write() {
Ok(inner_guard) => {
match inner_guard.fork_storage.read_value_internal(&balance_key) {
Ok(balance) => Ok(h256_to_u256(balance)),
Err(error) => Err(report_into_jsrpc_error(error)),
}
}
Err(_) => {
let error_message = "Error acquiring write lock for balance retrieval";
let web3_error = Web3Error::InternalError(anyhow::Error::msg(error_message));
Err(into_jsrpc_error(web3_error))
}
}
})
}
/// Returns a block by its number.
///
/// # Arguments
///
/// * `block_number` - A `BlockNumber` enum variant representing the block number to retrieve.
/// * `full_transactions` - A boolean value indicating whether to retrieve full transactions or not.
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `Option` of `Block<TransactionVariant>`.
fn get_block_by_number(
&self,
block_number: BlockNumber,
full_transactions: bool,
) -> RpcResult<Option<Block<TransactionVariant>>> {
let inner = self.get_inner().clone();
Box::pin(async move {
let maybe_block = {
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for block retrieval"),
)))
}
};
let number =
utils::to_real_block_number(block_number, U64::from(reader.current_miniblock))
.as_u64();
reader
.block_hashes
.get(&number)
.and_then(|hash| reader.blocks.get(hash))
.cloned()
.or_else(|| {
reader
.fork_storage
.inner
.read()
.expect("failed reading fork storage")
.fork
.as_ref()
.and_then(|fork| {
fork.fork_source
.get_block_by_number(block_number, true)
.ok()
.flatten()
})
})
};
match maybe_block {
Some(mut block) => {
let block_hash = block.hash;
block.transactions = block
.transactions
.into_iter()
.map(|transaction| match &transaction {
TransactionVariant::Full(inner) => {
if full_transactions {
transaction
} else {
TransactionVariant::Hash(inner.hash)
}
}
TransactionVariant::Hash(_) => {
if full_transactions {
panic!(
"unexpected non full transaction for block {}",
block_hash
)
} else {
transaction
}
}
})
.collect();
Ok(Some(block))
}
None => Ok(None),
}
})
}
/// Returns the code stored at the specified address.
///
/// # Arguments
///
/// * `address` - The address to retrieve the code from.
/// * `_block` - An optional block ID variant.
///
/// # Returns
///
/// A `BoxFuture` containing the result of the operation, which is a `jsonrpc_core::Result` containing
/// the code as a `Bytes` object.
fn get_code(
&self,
address: zksync_types::Address,
_block: Option<BlockIdVariant>,
) -> RpcResult<Bytes> {
let inner = self.get_inner().clone();
Box::pin(async move {
let code_key = get_code_key(&address);
match inner.write() {
Ok(guard) => match guard.fork_storage.read_value_internal(&code_key) {
Ok(code_hash) => {
match guard.fork_storage.load_factory_dep_internal(code_hash) {
Ok(raw_code) => {
let code = raw_code.unwrap_or_default();
Ok(Bytes::from(code))
}
Err(error) => Err(report_into_jsrpc_error(error)),
}
}
Err(error) => Err(report_into_jsrpc_error(error)),
},
Err(_) => Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for code retrieval"),
))),
}
})
}
/// Returns the transaction count for a given address.
///
/// # Arguments
///
/// * `address` - The address to get the transaction count for.
/// * `_block` - Optional block ID variant.
///
/// # Returns
///
/// Returns a `BoxFuture` containing the transaction count as a `U256` wrapped in a `jsonrpc_core::Result`.
fn get_transaction_count(
&self,
address: zksync_types::Address,
_block: Option<BlockIdVariant>,
) -> RpcResult<U256> {
let inner = self.get_inner().clone();
Box::pin(async move {
let nonce_key = get_nonce_key(&address);
match inner.write() {
Ok(guard) => match guard.fork_storage.read_value_internal(&nonce_key) {
Ok(result) => Ok(h256_to_u64(result).into()),
Err(error) => Err(report_into_jsrpc_error(error)),
},
Err(_) => Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for nonce retrieval"),
))),
}
})
}
/// Retrieves the transaction receipt for a given transaction hash.
///
/// # Arguments
///
/// * `hash` - The hash of the transaction to retrieve the receipt for.
///
/// # Returns
///
/// A `BoxFuture` that resolves to an `Option` of a `TransactionReceipt` or an error.
fn get_transaction_receipt(
&self,
hash: zksync_types::H256,
) -> RpcResult<Option<zksync_types::api::TransactionReceipt>> {
let inner = self.get_inner().clone();
Box::pin(async move {
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg(
"Failed to acquire read lock for transaction receipt retrieval",
),
)))
}
};
let receipt = reader
.tx_results
.get(&hash)
.map(|info| info.receipt.clone());
Ok(receipt)
})
}
/// Sends a raw transaction to the L2 network.
///
/// # Arguments
///
/// * `tx_bytes` - The transaction bytes to send.
///
/// # Returns
///
/// A future that resolves to the hash of the transaction if successful, or an error if the transaction is invalid or execution fails.
fn send_raw_transaction(&self, tx_bytes: Bytes) -> RpcResult<H256> {
self.send_raw_transaction_impl(tx_bytes)
.map_err(into_jsrpc_error)
.into_boxed_future()
}
/// Returns a block by its hash. Currently, only hashes for blocks in memory are supported.
///
/// # Arguments
///
/// * `hash` - A `H256` type representing the hash of the block to retrieve.
/// * `full_transactions` - A boolean value indicating whether to retrieve full transactions or not.
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `Option` of `Block<TransactionVariant>`.
fn get_block_by_hash(
&self,
hash: zksync_types::H256,
full_transactions: bool,
) -> RpcResult<Option<Block<TransactionVariant>>> {
let inner = self.get_inner().clone();
Box::pin(async move {
let maybe_block = {
let reader = inner.read().map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire read lock for block retrieval.",
)))
})?;
// try retrieving block from memory, and if unavailable subsequently from the fork
reader.blocks.get(&hash).cloned().or_else(|| {
reader
.fork_storage
.inner
.read()
.expect("failed reading fork storage")
.fork
.as_ref()
.and_then(|fork| {
fork.fork_source
.get_block_by_hash(hash, true)
.ok()
.flatten()
})
})
};
match maybe_block {
Some(mut block) => {
let block_hash = block.hash;
block.transactions = block
.transactions
.into_iter()
.map(|transaction| match &transaction {
TransactionVariant::Full(inner) => {
if full_transactions {
transaction
} else {
TransactionVariant::Hash(inner.hash)
}
}
TransactionVariant::Hash(_) => {
if full_transactions {
panic!(
"unexpected non full transaction for block {}",
block_hash
)
} else {
transaction
}
}
})
.collect();
Ok(Some(block))
}
None => Ok(None),
}
})
}
/// Returns a future that resolves to an optional transaction with the given hash.
///
/// # Arguments
///
/// * `hash` - A 32-byte hash of the transaction.
///
/// # Returns
///
/// A `jsonrpc_core::BoxFuture` that resolves to a `jsonrpc_core::Result` containing an optional `zksync_types::api::Transaction`.
fn get_transaction_by_hash(
&self,
hash: zksync_types::H256,
) -> RpcResult<Option<zksync_types::api::Transaction>> {
let inner = self.get_inner().clone();
Box::pin(async move {
let reader = inner.read().map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire read lock for transaction retrieval.",
)))
})?;
let maybe_result = {
// try retrieving transaction from memory, and if unavailable subsequently from the fork
reader.tx_results.get(&hash).and_then(|TransactionResult { info, .. }| {
let input_data = info.tx.common_data.input.clone().or(None)?;
let chain_id = info.tx.common_data.extract_chain_id().or(None)?;
Some(zksync_types::api::Transaction {
hash,
nonce: U256::from(info.tx.common_data.nonce.0),
block_hash: Some(hash),
block_number: Some(U64::from(info.miniblock_number)),
transaction_index: Some(U64::from(0)),
from: Some(info.tx.initiator_account()),
to: info.tx.recipient_account(),
value: info.tx.execute.value,
gas_price: Some(U256::from(0)),
gas: Default::default(),
input: input_data.data.into(),
v: Some(chain_id.into()),
r: Some(U256::zero()),
s: Some(U256::zero()),
raw: None,
transaction_type: {
let tx_type = match info.tx.common_data.transaction_type {
zksync_types::l2::TransactionType::LegacyTransaction => 0,
zksync_types::l2::TransactionType::EIP2930Transaction => 1,
zksync_types::l2::TransactionType::EIP1559Transaction => 2,
zksync_types::l2::TransactionType::EIP712Transaction => 113,
zksync_types::l2::TransactionType::PriorityOpTransaction => 255,
zksync_types::l2::TransactionType::ProtocolUpgradeTransaction => 254,
};
Some(tx_type.into())
},
access_list: None,
max_fee_per_gas: Some(info.tx.common_data.fee.max_fee_per_gas),
max_priority_fee_per_gas: Some(
info.tx.common_data.fee.max_priority_fee_per_gas,
),
chain_id: U256::from(chain_id),
l1_batch_number: Some(U64::from(info.batch_number as u64)),
l1_batch_tx_index: None,
})
}).or_else(|| {
reader
.fork_storage
.inner
.read()
.expect("failed reading fork storage")
.fork
.as_ref()
.and_then(|fork| {
fork.fork_source
.get_transaction_by_hash(hash)
.ok()
.flatten()
})
})
};
Ok(maybe_result)
})
}
/// Returns the current block number as a `U64` wrapped in a `BoxFuture`.
fn get_block_number(&self) -> RpcResult<zksync_types::U64> {
let inner = self.get_inner().clone();
Box::pin(async move {
let reader = inner.read().map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire read lock for block retrieval",
)))
})?;
Ok(U64::from(reader.current_miniblock))
})
}
/// Estimates the gas required for a given call request.
///
/// # Arguments
///
/// * `req` - A `CallRequest` struct representing the call request to estimate gas for.
/// * `_block` - An optional `BlockNumber` struct representing the block number to estimate gas for.
///
/// # Returns
///
/// A `BoxFuture` containing a `Result` with a `U256` representing the estimated gas required.
fn estimate_gas(
&self,
req: zksync_types::transaction_request::CallRequest,
_block: Option<BlockNumber>,
) -> RpcResult<U256> {
let inner = self.get_inner().clone();
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for gas estimation."),
)))
.boxed()
}
};
let result: jsonrpc_core::Result<Fee> = reader.estimate_gas_impl(req);
match result {
Ok(fee) => Ok(fee.gas_limit).into_boxed_future(),
Err(err) => return futures::future::err(err).boxed(),
}
}
/// Returns the current gas price in U256 format.
fn gas_price(&self) -> RpcResult<U256> {
let fair_l2_gas_price: u64 = self
.get_inner()
.read()
.expect("Failed to acquire read lock")
.fee_input_provider
.l2_gas_price;
Ok(U256::from(fair_l2_gas_price)).into_boxed_future()
}
/// Creates a filter object, based on filter options, to notify when the state changes (logs).
/// To check if the state has changed, call `eth_getFilterChanges`.
///
/// # Arguments
///
/// * `filter`: The filter options -
/// fromBlock: - Integer block number, or the string "latest", "earliest" or "pending".
/// toBlock: - Integer block number, or the string "latest", "earliest" or "pending".
/// address: - Contract address or a list of addresses from which the logs should originate.
/// topics: - [H256] topics. Topics are order-dependent. Each topic can also be an array with "or" options.
///
/// If the from `fromBlock` or `toBlock` option are equal to "latest" the filter continually appends logs for newly mined blocks.
/// Topics are order-dependent. A transaction with a log with topics [A, B] will be matched by the following topic filters:
/// * \[\] "anything"
/// * \[A\] "A in first position (and anything after)"
/// * \[null, B\] "anything in first position AND B in second position (and anything after)"
/// * \[A, B\] "A in first position AND B in second position (and anything after)"
/// * \[\[A, B\], \[A, B\]\] "(A OR B) in first position AND (A OR B) in second position (and anything after)"
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `U256` filter id.
fn new_filter(&self, filter: Filter) -> RpcResult<U256> {
let inner = self.get_inner().clone();
let mut writer = match inner.write() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for filter creation"),
)))
.boxed()
}
};
let from_block = filter.from_block.unwrap_or(BlockNumber::Latest);
let to_block = filter.to_block.unwrap_or(BlockNumber::Latest);
let addresses = filter.address.unwrap_or_default().0;
let mut topics: [Option<HashSet<H256>>; 4] = Default::default();
if let Some(filter_topics) = filter.topics {
filter_topics
.into_iter()
.take(4)
.enumerate()
.for_each(|(i, maybe_topic_set)| {
if let Some(topic_set) = maybe_topic_set {
topics[i] = Some(topic_set.0.into_iter().collect());
}
})
}
writer
.filters
.add_log_filter(from_block, to_block, addresses, topics)
.map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire write lock for new filter.",
)))
})
.into_boxed_future()
}
/// Creates a filter in the node, to notify when a new block arrives.
/// To check if the state has changed, call `eth_getFilterChanges`.
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `U256` filter id.
fn new_block_filter(&self) -> RpcResult<U256> {
let inner = self.get_inner().clone();
let mut writer = match inner.write() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for new filter."),
)))
.boxed()
}
};
writer
.filters
.add_block_filter()
.map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire write lock for new block filter.",
)))
})
.into_boxed_future()
}
/// Creates a filter in the node, to notify when new pending transactions arrive.
/// To check if the state has changed, call `eth_getFilterChanges`.
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `U256` filter id.
fn new_pending_transaction_filter(&self) -> RpcResult<U256> {
let inner = self.get_inner().clone();
let mut writer = match inner.write() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for transaction filter."),
)))
.boxed()
}
};
writer
.filters
.add_pending_transaction_filter()
.map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire write lock for transaction filter.",
)))
})
.into_boxed_future()
}
/// Uninstalls a filter with given id. Should always be called when watch is no longer needed.
///
/// # Arguments
///
/// * `id`: The filter id
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an `U256` filter id.
fn uninstall_filter(&self, id: U256) -> RpcResult<bool> {
let inner = self.get_inner().clone();
let mut writer = match inner.write() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for uninstalling filter."),
)))
.boxed()
}
};
let result = writer.filters.remove_filter(id);
Ok(result).into_boxed_future()
}
/// Returns an array of all logs matching a given filter.
///
/// # Arguments
///
/// * `filter`: The filter options -
/// fromBlock - Integer block number, or the string "latest", "earliest" or "pending".
/// toBlock - Integer block number, or the string "latest", "earliest" or "pending".
/// address - Contract address or a list of addresses from which the logs should originate.
/// topics - [H256] topics. Topics are order-dependent. Each topic can also be an array with "or" options.
/// See `new_filter` documention for how to specify topics.
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an array of logs.
fn get_logs(&self, filter: Filter) -> RpcResult<Vec<zksync_types::api::Log>> {
let inner = self.get_inner();
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for logs."),
)))
.boxed()
}
};
let from_block = filter.from_block.unwrap_or(BlockNumber::Earliest);
let to_block = filter.to_block.unwrap_or(BlockNumber::Latest);
let addresses = filter.address.unwrap_or_default().0;
let mut topics: [Option<HashSet<H256>>; 4] = Default::default();
if let Some(filter_topics) = filter.topics {
filter_topics
.into_iter()
.take(4)
.enumerate()
.for_each(|(i, maybe_topic_set)| {
if let Some(topic_set) = maybe_topic_set {
topics[i] = Some(topic_set.0.into_iter().collect());
}
})
}
let log_filter = LogFilter::new(from_block, to_block, addresses, topics);
let latest_block_number = U64::from(reader.current_miniblock);
let logs = reader
.tx_results
.values()
.flat_map(|tx_result| {
tx_result
.receipt
.logs
.iter()
.filter(|log| log_filter.matches(log, latest_block_number))
.cloned()
})
.collect_vec();
Ok(logs).into_boxed_future()
}
/// Returns an array of all logs matching filter with given id.
///
/// # Arguments
///
/// * `id`: The filter id
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an array of logs.
fn get_filter_logs(&self, id: U256) -> RpcResult<FilterChanges> {
let inner = self.get_inner();
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for get filter logs."),
)))
.boxed()
}
};
let latest_block_number = U64::from(reader.current_miniblock);
let logs = match reader.filters.get_filter(id) {
Some(FilterType::Log(f)) => reader
.tx_results
.values()
.flat_map(|tx_result| {
tx_result
.receipt
.logs
.iter()
.filter(|log| f.matches(log, latest_block_number))
.cloned()
})
.collect_vec(),
_ => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire read lock for filter logs."),
)))
.boxed()
}
};
Ok(FilterChanges::Logs(logs)).into_boxed_future()
}
/// Polling method for a filter, which returns an array of logs, block hashes, or transaction hashes,
/// depending on the filter type, which occurred since last poll.
///
/// # Arguments
///
/// * `id`: The filter id
///
/// # Returns
///
/// A `BoxFuture` containing a `jsonrpc_core::Result` that resolves to an array of logs, block hashes, or transaction hashes,
/// depending on the filter type, which occurred since last poll.
/// * Filters created with `eth_newFilter` return [zksync_types::api::Log] objects.
/// * Filters created with `eth_newBlockFilter` return block hashes.
/// * Filters created with `eth_newPendingTransactionFilter` return transaction hashes.
fn get_filter_changes(&self, id: U256) -> RpcResult<FilterChanges> {
let inner = self.get_inner().clone();
let mut writer = match inner.write() {
Ok(r) => r,
Err(_) => {
return futures::future::err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg("Failed to acquire write lock for filtered changes"),
)))
.boxed()
}
};
writer
.filters
.get_new_changes(id)
.map_err(|_| {
into_jsrpc_error(Web3Error::InternalError(anyhow::Error::msg(
"Failed to acquire write lock for filtered changes.",
)))
})
.into_boxed_future()
}
fn get_block_transaction_count_by_number(
&self,
block_number: BlockNumber,
) -> RpcResult<Option<U256>> {
let inner = self.get_inner().clone();
Box::pin(async move {
let maybe_result = {
let reader = match inner.read() {
Ok(r) => r,
Err(_) => {
return Err(into_jsrpc_error(Web3Error::InternalError(
anyhow::Error::msg(