diff --git a/Cargo.lock b/Cargo.lock index d20aa6eb..954769ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,20 +38,6 @@ dependencies = [ "cpufeatures", ] -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if 1.0.0", - "getrandom 0.2.15", - "once_cell", - "serde", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.3" @@ -61,48 +47,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "allocator-api2" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" - -[[package]] -name = "alloy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea8ebf106e84a1c37f86244df7da0c7587e697b71a0d565cce079449b85ac6f8" -dependencies = [ - "alloy-consensus", - "alloy-contract", - "alloy-core", - "alloy-eips", - "alloy-genesis", - "alloy-network", - "alloy-provider", - "alloy-pubsub", - "alloy-rpc-client", - "alloy-rpc-types", - "alloy-serde", - "alloy-signer", - "alloy-signer-local", - "alloy-transport", - "alloy-transport-http", - "alloy-transport-ipc", - "alloy-transport-ws", -] - -[[package]] -name = "alloy-chains" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18c5c520273946ecf715c0010b4e3503d7eba9893cd9ce6b7fff5654c4a3c470" -dependencies = [ - "alloy-primitives", - "num_enum 0.7.3", - "strum", -] - [[package]] name = "alloy-consensus" version = "0.5.4" @@ -119,57 +63,6 @@ dependencies = [ "serde", ] -[[package]] -name = "alloy-contract" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460ab80ce4bda1c80bcf96fe7460520476f2c7b734581c6567fac2708e2a60ef" -dependencies = [ - "alloy-dyn-abi", - "alloy-json-abi", - "alloy-network", - "alloy-network-primitives", - "alloy-primitives", - "alloy-provider", - "alloy-pubsub", - "alloy-rpc-types-eth", - "alloy-sol-types", - "alloy-transport", - "futures 0.3.31", - "futures-util", - "thiserror", -] - -[[package]] -name = "alloy-core" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8d22df68fa7d9744be0b1a9be3260e9aa089fbf41903ab182328333061ed186" -dependencies = [ - "alloy-dyn-abi", - "alloy-json-abi", - "alloy-primitives", - "alloy-rlp", - "alloy-sol-types", -] - -[[package]] -name = "alloy-dyn-abi" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cf633ae9a1f0c82fdb9e559ed2be1c8e415c3e48fc47e1feaf32c6078ec0cdd" -dependencies = [ - "alloy-json-abi", - "alloy-primitives", - "alloy-sol-type-parser", - "alloy-sol-types", - "const-hex", - "itoa", - "serde", - "serde_json", - "winnow 0.6.20", -] - [[package]] name = "alloy-eip2930" version = "0.1.0" @@ -190,7 +83,6 @@ dependencies = [ "alloy-primitives", "alloy-rlp", "derive_more 1.0.0", - "k256 0.13.4", "serde", ] @@ -212,29 +104,6 @@ dependencies = [ "sha2 0.10.8", ] -[[package]] -name = "alloy-genesis" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dde15e14944a88bd6a57d325e9a49b75558746fe16aaccc79713ae50a6a9574c" -dependencies = [ - "alloy-primitives", - "alloy-serde", - "serde", -] - -[[package]] -name = "alloy-json-abi" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a500037938085feed8a20dbfc8fce58c599db68c948cfae711147175dee392c" -dependencies = [ - "alloy-primitives", - "alloy-sol-type-parser", - "serde", - "serde_json", -] - [[package]] name = "alloy-json-rpc" version = "0.5.4" @@ -311,65 +180,6 @@ dependencies = [ "tiny-keccak 2.0.2", ] -[[package]] -name = "alloy-provider" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4814d141ede360bb6cd1b4b064f1aab9de391e7c4d0d4d50ac89ea4bc1e25fbd" -dependencies = [ - "alloy-chains", - "alloy-consensus", - "alloy-eips", - "alloy-json-rpc", - "alloy-network", - "alloy-network-primitives", - "alloy-primitives", - "alloy-pubsub", - "alloy-rpc-client", - "alloy-rpc-types-eth", - "alloy-transport", - "alloy-transport-http", - "alloy-transport-ipc", - "alloy-transport-ws", - "async-stream", - "async-trait", - "auto_impl", - "dashmap", - "futures 0.3.31", - "futures-utils-wasm", - "lru", - "parking_lot 0.12.3", - "pin-project", - "reqwest 0.12.9", - "schnellru", - "serde", - "serde_json", - "thiserror", - "tokio", - "tracing", - "url", - "wasmtimer", -] - -[[package]] -name = "alloy-pubsub" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96ba46eb69ddf7a9925b81f15229cb74658e6eebe5dd30a5b74e2cd040380573" -dependencies = [ - "alloy-json-rpc", - "alloy-primitives", - "alloy-transport", - "bimap", - "futures 0.3.31", - "serde", - "serde_json", - "tokio", - "tokio-stream", - "tower 0.5.1", - "tracing", -] - [[package]] name = "alloy-rlp" version = "0.3.9" @@ -392,61 +202,6 @@ dependencies = [ "syn 2.0.89", ] -[[package]] -name = "alloy-rpc-client" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fc2bd1e7403463a5f2c61e955bcc9d3072b63aa177442b0f9aa6a6d22a941e3" -dependencies = [ - "alloy-json-rpc", - "alloy-primitives", - "alloy-pubsub", - "alloy-transport", - "alloy-transport-http", - "alloy-transport-ipc", - "alloy-transport-ws", - "futures 0.3.31", - "pin-project", - "reqwest 0.12.9", - "serde", - "serde_json", - "tokio", - "tokio-stream", - "tower 0.5.1", - "tracing", - "url", - "wasmtimer", -] - -[[package]] -name = "alloy-rpc-types" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eea9bf1abdd506f985a53533f5ac01296bcd6102c5e139bbc5d40bc468d2c916" -dependencies = [ - "alloy-primitives", - "alloy-rpc-types-engine", - "alloy-rpc-types-eth", - "alloy-serde", - "serde", -] - -[[package]] -name = "alloy-rpc-types-engine" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "886d22d41992287a235af2f3af4299b5ced2bcafb81eb835572ad35747476946" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-primitives", - "alloy-rlp", - "alloy-serde", - "derive_more 1.0.0", - "serde", - "strum", -] - [[package]] name = "alloy-rpc-types-eth" version = "0.5.4" @@ -529,7 +284,6 @@ version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4feea540fc8233df2ad1156efd744b2075372f43a8f942a68b3b19c8a00e2c12" dependencies = [ - "alloy-json-abi", "alloy-sol-macro-input", "const-hex", "heck", @@ -548,110 +302,24 @@ version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a0ad281f3d1b613af814b66977ee698e443d4644a1510962d0241f26e0e53ae" dependencies = [ - "alloy-json-abi", "const-hex", "dunce", "heck", "proc-macro2", "quote", - "serde_json", "syn 2.0.89", "syn-solidity", ] -[[package]] -name = "alloy-sol-type-parser" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96eff16c797438add6c37bb335839d015b186c5421ee5626f5559a7bfeb38ef5" -dependencies = [ - "serde", - "winnow 0.6.20", -] - [[package]] name = "alloy-sol-types" version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cff34e0682d6665da243a3e81da96f07a2dd50f7e64073e382b1a141f5a2a2f6" dependencies = [ - "alloy-json-abi", "alloy-primitives", "alloy-sol-macro", "const-hex", - "serde", -] - -[[package]] -name = "alloy-transport" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be77579633ebbc1266ae6fd7694f75c408beb1aeb6865d0b18f22893c265a061" -dependencies = [ - "alloy-json-rpc", - "base64 0.22.1", - "futures-util", - "futures-utils-wasm", - "serde", - "serde_json", - "thiserror", - "tokio", - "tower 0.5.1", - "tracing", - "url", - "wasmtimer", -] - -[[package]] -name = "alloy-transport-http" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fd1a5d0827939847983b46f2f79510361f901dc82f8e3c38ac7397af142c6e" -dependencies = [ - "alloy-json-rpc", - "alloy-transport", - "reqwest 0.12.9", - "serde_json", - "tower 0.5.1", - "tracing", - "url", -] - -[[package]] -name = "alloy-transport-ipc" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8073d1186bfeeb8fbdd1292b6f1a0731f3aed8e21e1463905abfae0b96a887a6" -dependencies = [ - "alloy-json-rpc", - "alloy-pubsub", - "alloy-transport", - "bytes", - "futures 0.3.31", - "interprocess", - "pin-project", - "serde_json", - "tokio", - "tokio-util 0.7.12", - "tracing", -] - -[[package]] -name = "alloy-transport-ws" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61f27837bb4a1d6c83a28231c94493e814882f0e9058648a97e908a5f3fc9fcf" -dependencies = [ - "alloy-pubsub", - "alloy-transport", - "futures 0.3.31", - "http 1.1.0", - "rustls 0.23.19", - "serde_json", - "tokio", - "tokio-tungstenite 0.24.0", - "tracing", - "ws_stream_wasm", ] [[package]] @@ -722,43 +390,75 @@ dependencies = [ name = "anvil-zksync" version = "0.2.1" dependencies = [ - "alloy", + "alloy-signer-local", + "anvil_zksync_config", + "anvil_zksync_core", + "anyhow", + "clap", + "colored", + "eyre", + "futures 0.3.31", + "hex", + "itertools 0.13.0", + "jsonrpc-core", + "jsonrpc-http-server", + "rand 0.8.5", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", + "zksync_types", + "zksync_web3_decl", +] + +[[package]] +name = "anvil_zksync_config" +version = "0.2.1" +dependencies = [ "alloy-signer", "alloy-signer-local", + "clap", + "colored", + "hex", + "rand 0.8.5", + "serde", + "serde_json", + "tracing", + "zksync_types", + "zksync_vm_interface", +] + +[[package]] +name = "anvil_zksync_core" +version = "0.2.1" +dependencies = [ + "anvil_zksync_config", "anyhow", "bigdecimal 0.3.1", "chrono", - "clap", "colored", "ethabi 16.0.0", "ethers", "eyre", "flate2", - "fs2", "futures 0.3.31", "hex", "httptest", "indexmap 2.6.0", - "itertools 0.10.5", + "itertools 0.13.0", "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", - "jsonrpc-http-server", - "jsonschema", "lazy_static", "maplit", "once_cell", - "openrpc-types", - "openssl-sys", - "rand 0.8.5", "reqwest 0.11.27", "rustc-hash 1.1.0", - "schemars", "serde", "serde_json", "tempdir", "test-case", - "test-log", "thiserror", "time", "tokio", @@ -1160,12 +860,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "bimap" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "230c5f1ca6a325a32553f8640d31ac9b49f2411e901e427570154868b46da4f7" - [[package]] name = "bincode" version = "1.3.3" @@ -1204,16 +898,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" dependencies = [ - "bit-vec 0.6.3", -] - -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec 0.8.0", + "bit-vec", ] [[package]] @@ -1225,12 +910,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - [[package]] name = "bitflags" version = "1.3.2" @@ -1364,12 +1043,6 @@ dependencies = [ "zksync_pairing", ] -[[package]] -name = "borrow-or-share" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eeab4423108c5d7c744f4d234de88d18d636100093ae04caf4825134b9c3a32" - [[package]] name = "bs58" version = "0.5.1" @@ -1413,12 +1086,6 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" -[[package]] -name = "bytecount" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce89b21cab1437276d2650d57e971f9d548a2d9037cc231abdc0562b97498ce" - [[package]] name = "byteorder" version = "1.5.0" @@ -2112,26 +1779,12 @@ dependencies = [ [[package]] name = "darling_macro" version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" -dependencies = [ - "darling_core", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "dashmap" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core 0.9.10", +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +dependencies = [ + "darling_core", + "quote", + "syn 1.0.109", ] [[package]] @@ -2306,12 +1959,6 @@ dependencies = [ "syn 2.0.89", ] -[[package]] -name = "doctest-file" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac81fa3e28d21450aa4d2ac065992ba96a1d7303efbce51a95f4fd175b67562" - [[package]] name = "dtoa" version = "1.0.9" @@ -2324,12 +1971,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" -[[package]] -name = "dyn-clone" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" - [[package]] name = "ecdsa" version = "0.14.8" @@ -2411,15 +2052,6 @@ dependencies = [ "stable_deref_trait", ] -[[package]] -name = "email_address" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" -dependencies = [ - "serde", -] - [[package]] name = "ena" version = "0.14.3" @@ -2468,15 +2100,6 @@ dependencies = [ "syn 2.0.89", ] -[[package]] -name = "env_filter" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" -dependencies = [ - "log", -] - [[package]] name = "env_logger" version = "0.10.2" @@ -2490,18 +2113,6 @@ dependencies = [ "termcolor", ] -[[package]] -name = "env_logger" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "log", -] - [[package]] name = "envy" version = "0.4.2" @@ -2826,7 +2437,7 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tokio-tungstenite 0.20.1", + "tokio-tungstenite", "tracing", "tracing-futures", "url", @@ -2897,17 +2508,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "fancy-regex" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" -dependencies = [ - "bit-set 0.8.0", - "regex-automata 0.4.9", - "regex-syntax 0.8.5", -] - [[package]] name = "fastrand" version = "2.2.0" @@ -3003,17 +2603,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "fluent-uri" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1918b65d96df47d3591bed19c5cca17e3fa5d0707318e4b5ef2eae01764df7e5" -dependencies = [ - "borrow-or-share", - "ref-cast", - "serde", -] - [[package]] name = "fnv" version = "1.0.7" @@ -3050,16 +2639,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fraction" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f158e3ff0a1b334408dc9fb811cd99b446986f4d8b741bb08f9df1604085ae7" -dependencies = [ - "lazy_static", - "num", -] - [[package]] name = "fs2" version = "0.4.3" @@ -3396,26 +2975,12 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - [[package]] name = "hashbrown" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" dependencies = [ - "allocator-api2", - "equivalent", "foldhash", "serde", ] @@ -3994,21 +3559,6 @@ dependencies = [ "cfg-if 1.0.0", ] -[[package]] -name = "interprocess" -version = "2.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "894148491d817cb36b6f778017b8ac46b17408d522dd90f539d677ea938362eb" -dependencies = [ - "doctest-file", - "futures-core", - "libc", - "recvmsg", - "tokio", - "widestring", - "windows-sys 0.52.0", -] - [[package]] name = "ipnet" version = "2.10.1" @@ -4381,31 +3931,6 @@ dependencies = [ "url", ] -[[package]] -name = "jsonschema" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "893d6229c7315763ca0df9b29ab7661ee419f286577a02847c5521b462e071af" -dependencies = [ - "ahash", - "base64 0.22.1", - "bytecount", - "email_address", - "fancy-regex", - "fraction", - "idna", - "itoa", - "num-cmp", - "once_cell", - "percent-encoding", - "referencing", - "regex-syntax 0.8.5", - "reqwest 0.12.9", - "serde", - "serde_json", - "uuid-simd", -] - [[package]] name = "jsonwebtoken" version = "8.3.0" @@ -4472,7 +3997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55cb077ad656299f160924eb2912aa147d7339ea7d69e1b5517326fdcec3c1ca" dependencies = [ "ascii-canvas", - "bit-set 0.5.3", + "bit-set", "ena", "itertools 0.11.0", "lalrpop-util", @@ -4599,15 +4124,6 @@ dependencies = [ "logos-codegen", ] -[[package]] -name = "lru" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" -dependencies = [ - "hashbrown 0.15.2", -] - [[package]] name = "maplit" version = "1.0.2" @@ -4792,12 +4308,6 @@ dependencies = [ "serde", ] -[[package]] -name = "num-cmp" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa" - [[package]] name = "num-complex" version = "0.4.6" @@ -4973,19 +4483,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "openrpc-types" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e54da72d1ed8d0127cacaa31afbc2b6e6b22a31a6d2b55cf5f7b22f17711d89" -dependencies = [ - "schemars", - "semver 1.0.23", - "serde", - "serde_json", - "url", -] - [[package]] name = "openssl" version = "0.10.68" @@ -5018,15 +4515,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" -[[package]] -name = "openssl-src" -version = "300.4.1+3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa4eac4138c62414b5622d1b31c5c304f34b406b013c079c2bbc652fdd6678c" -dependencies = [ - "cc", -] - [[package]] name = "openssl-sys" version = "0.9.104" @@ -5035,7 +4523,6 @@ checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741" dependencies = [ "cc", "libc", - "openssl-src", "pkg-config", "vcpkg", ] @@ -5092,7 +4579,7 @@ dependencies = [ "opentelemetry-http", "opentelemetry-proto", "opentelemetry_sdk", - "prost 0.13.3", + "prost 0.13.4", "reqwest 0.12.9", "thiserror", "tokio", @@ -5107,7 +4594,7 @@ checksum = "30ee9f20bff9c984511a02f082dc8ede839e4a9bf15cc2487c8d6fea5ad850d9" dependencies = [ "opentelemetry", "opentelemetry_sdk", - "prost 0.13.3", + "prost 0.13.4", "tonic", ] @@ -5164,12 +4651,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "outref" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4030760ffd992bef45b0ae3f10ce1aba99e33464c90d14dd7c039884963ddc7a" - [[package]] name = "overload" version = "0.1.1" @@ -5687,8 +5168,8 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c2511913b88df1637da85cc8d96ec8e43a3f8bb8ccb71ee1ac240d6f3df58d" dependencies = [ - "bit-set 0.5.3", - "bit-vec 0.6.3", + "bit-set", + "bit-vec", "bitflags 2.6.0", "lazy_static", "num-traits", @@ -5713,12 +5194,12 @@ dependencies = [ [[package]] name = "prost" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0487d90e047de87f984913713b85c601c05609aad5b0df4b4573fbf69aa13f" +checksum = "2c0fef6c4230e4ccf618a35c59d7ede15dea37de8427500f50aff708806e42ec" dependencies = [ "bytes", - "prost-derive 0.13.3", + "prost-derive 0.13.4", ] [[package]] @@ -5757,9 +5238,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9552f850d5f0964a4e4d0bf306459ac29323ddfbae05e35a7c0d35cb0803cc5" +checksum = "157c5a9d7ea5c2ed2d9fb8f495b64759f7816c7eaea54ba3978f0d63000162e3" dependencies = [ "anyhow", "itertools 0.13.0", @@ -5994,12 +5475,6 @@ dependencies = [ "rand_core 0.3.1", ] -[[package]] -name = "recvmsg" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" - [[package]] name = "redox_syscall" version = "0.2.16" @@ -6029,39 +5504,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "ref-cast" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.89", -] - -[[package]] -name = "referencing" -version = "0.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb853437e467c693ac1dc8c1520105a31b8c2588544ff2f3cfa5a7c706c6c069" -dependencies = [ - "ahash", - "fluent-uri", - "once_cell", - "percent-encoding", - "serde_json", -] - [[package]] name = "regex" version = "1.11.1" @@ -6565,41 +6007,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "schemars" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" -dependencies = [ - "dyn-clone", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 2.0.89", -] - -[[package]] -name = "schnellru" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9a8ef13a93c54d20580de1e5c413e624e53121d42fc7e2c11d10ef7f8b02367" -dependencies = [ - "ahash", - "cfg-if 1.0.0", - "hashbrown 0.13.2", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -6890,17 +6297,6 @@ dependencies = [ "syn 2.0.89", ] -[[package]] -name = "serde_derive_internals" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.89", -] - [[package]] name = "serde_json" version = "1.0.133" @@ -7479,28 +6875,6 @@ dependencies = [ "test-case-core", ] -[[package]] -name = "test-log" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dffced63c2b5c7be278154d76b479f9f9920ed34e7574201407f0b14e2bbb93" -dependencies = [ - "env_logger 0.11.5", - "test-log-macros", - "tracing-subscriber", -] - -[[package]] -name = "test-log-macros" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5999e24eaa32083191ba4e425deb75cdf25efefabe5aaccb7446dd0d4122a3f5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.89", -] - [[package]] name = "thiserror" version = "1.0.69" @@ -7631,6 +7005,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.52.0", ] @@ -7699,26 +7074,10 @@ dependencies = [ "rustls 0.21.12", "tokio", "tokio-rustls 0.24.1", - "tungstenite 0.20.1", + "tungstenite", "webpki-roots 0.25.4", ] -[[package]] -name = "tokio-tungstenite" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" -dependencies = [ - "futures-util", - "log", - "rustls 0.23.19", - "rustls-pki-types", - "tokio", - "tokio-rustls 0.26.0", - "tungstenite 0.24.0", - "webpki-roots 0.26.7", -] - [[package]] name = "tokio-util" version = "0.6.10" @@ -7821,7 +7180,7 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "prost 0.13.3", + "prost 0.13.4", "socket2", "tokio", "tokio-stream", @@ -8007,26 +7366,6 @@ dependencies = [ "utf-8", ] -[[package]] -name = "tungstenite" -version = "0.24.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" -dependencies = [ - "byteorder", - "bytes", - "data-encoding", - "http 1.1.0", - "httparse", - "log", - "rand 0.8.5", - "rustls 0.23.19", - "rustls-pki-types", - "sha1", - "thiserror", - "utf-8", -] - [[package]] name = "typenum" version = "1.17.0" @@ -8192,17 +7531,6 @@ dependencies = [ "serde", ] -[[package]] -name = "uuid-simd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8" -dependencies = [ - "outref", - "uuid 1.11.0", - "vsimd", -] - [[package]] name = "valuable" version = "0.1.0" @@ -8259,12 +7587,6 @@ dependencies = [ "syn 2.0.89", ] -[[package]] -name = "vsimd" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" - [[package]] name = "wait-timeout" version = "0.2.0" @@ -8372,20 +7694,6 @@ version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" -[[package]] -name = "wasmtimer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7ed9d8b15c7fb594d72bfb4b5a276f3d2029333cd93a932f376f5937f6f80ee" -dependencies = [ - "futures 0.3.31", - "js-sys", - "parking_lot 0.12.3", - "pin-utils", - "slab", - "wasm-bindgen", -] - [[package]] name = "web-sys" version = "0.3.72" @@ -8433,12 +7741,6 @@ dependencies = [ "rustix", ] -[[package]] -name = "widestring" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311" - [[package]] name = "winapi" version = "0.3.9" @@ -9122,7 +8424,7 @@ checksum = "15bc9b106393359ac013c2527db318ced4ca838d26ef03488233af557ebe5da8" dependencies = [ "async-trait", "clap", - "env_logger 0.10.2", + "env_logger", "ethers", "ethers-contract", "hex", @@ -9162,7 +8464,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ffa03efe9bdb137a4b36b97d1a74237e18c9ae42b755163d903a9d48c1a5d80" dependencies = [ "arrayvec 0.7.6", - "bit-vec 0.6.3", + "bit-vec", "blake2s_simd", "byteorder", "cfg-if 1.0.0", @@ -9363,7 +8665,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abd55c64f54cb10967a435422f66ff5880ae14a232b245517c7ce38da32e0cab" dependencies = [ "anyhow", - "bit-vec 0.6.3", + "bit-vec", "once_cell", "prost 0.12.6", "prost-reflect", diff --git a/Cargo.toml b/Cargo.toml index df601295..78c2c531 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,44 +1,69 @@ -[package] -name = "anvil-zksync" +[workspace] +members = [ + "crates/cli", + "crates/config", + "crates/core", +] +resolver = "2" + +[profile.dev] +debug = 0 + +[workspace.package] version = "0.2.1" -edition = "2018" +edition = "2021" authors = ["The Matter Labs Team "] homepage = "https://zksync.io/" repository = "https://github.com/matter-labs/anvil-zksync" license = "MIT OR Apache-2.0" keywords = ["blockchain", "zksync"] categories = ["cryptography"] -publish = false # We don't want to publish our binaries. -[dependencies] +[workspace.dependencies] +######################### +# ZKsync dependencies # +######################### zksync_multivm = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" } zksync_contracts = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" } zksync_types = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" } zksync_utils = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" } +zksync_vm_interface = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec" } zksync_web3_decl = { git = "https://github.com/matter-labs/zksync-era.git", rev = "6c034f6e180cc92e99766f14c8840c90efa56cec", features = [ "server", ] } -# alloy +######################### +# External dependencies # +######################### +anyhow = "1.0" alloy-signer-local = { version = "0.5.4", features = ["mnemonic"] } alloy-signer = { version = "0.5.4", default-features = false } - -openssl-sys = { version = "0.9", features = ["vendored"] } - -anyhow = "1.0" -tokio = { version = "1", features = ["time", "rt"] } +bigdecimal = { version = "0.3.0", features = ["serde"] } +chrono = { version = "0.4.31", default-features = false } +clap = { version = "4.2.4", features = ["derive", "env"] } +colored = "2" +ethabi = "16.0.0" +eyre = "0.6" +flate2 = "1.0" futures = { version = "0.3", features = ["compat"] } -once_cell = "1.7" - +hex = "0.4" +indexmap = "2.0.1" +itertools = "0.13" jsonrpc-http-server = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" } jsonrpc-core = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" } jsonrpc-core-client = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" } jsonrpc-derive = { git = "https://github.com/matter-labs/jsonrpc.git", branch = "master" } - -clap = { version = "4.2.4", features = ["derive", "env"] } +lazy_static = "1.4" +once_cell = "1.7" +rand = "0.8" reqwest = { version = "0.11", features = ["blocking"] } +rustc-hash = "1.1.0" serde = { version = "1.0", features = ["derive"] } -tracing = { version = "0.1.26", features = ["log"] } +serde_json = "1.0" +thiserror = "1" +time = "0.3.36" +tokio = { version = "1", features = ["full", "tracing"] } +tracing = { version = "0.1", features = ["log"] } tracing-subscriber = { version = "0.3", features = [ "fmt", "env-filter", @@ -46,35 +71,9 @@ tracing-subscriber = { version = "0.3", features = [ "json", "local-time", ] } -colored = "2.0" -lazy_static = "1.4" -eyre = "0.6" -serde_json = "1.0.67" -bigdecimal = { version = "0.3.0", features = ["serde"] } -hex = "0.4" -ethabi = "16.0.0" -itertools = "0.10.5" -rustc-hash = "1.1.0" -indexmap = "2.0.1" -chrono = { version = "0.4.31", default-features = false } -time = "0.3.36" -rand = "0.8" -flate2 = "1.0" -thiserror = "1" - -[dev-dependencies] -httptest = "0.15.4" -tempdir = "0.3.7" -maplit = "1.0.2" -zksync-web3-rs = "0.1.1" -ethers = { version = "2.0.4", features = ["rustls"] } -jsonschema = "0.26.0" -schemars = "0.8.21" -openrpc-types = "0.4.0" -alloy = { version = "0.5", features = ["full"] } -test-log = "0.2.16" -fs2 = "0.4.3" -test-case = "3.3.1" -[profile.dev] -debug = 0 +######################### +# Local dependencies # +######################### +anvil_zksync_config = { path = "crates/config" } +anvil_zksync_core = { path = "crates/core" } diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml new file mode 100644 index 00000000..1958d3b5 --- /dev/null +++ b/crates/cli/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "anvil-zksync" # Compatible with the legacy bin crate name +description = "anvil-zksync CLI" +version.workspace = true +edition.workspace = true +authors.workspace = true +homepage.workspace = true +repository.workspace = true +license.workspace = true +keywords.workspace = true +categories.workspace = true + +[dependencies] +anvil_zksync_core.workspace = true +anvil_zksync_config.workspace = true + +zksync_types.workspace = true +zksync_web3_decl.workspace = true + +alloy-signer-local.workspace = true +anyhow.workspace = true +clap.workspace = true +colored.workspace = true +eyre.workspace = true +hex.workspace = true +itertools.workspace = true +jsonrpc-core.workspace = true +jsonrpc-http-server.workspace = true +futures.workspace = true +rand.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true diff --git a/src/bytecode_override.rs b/crates/cli/src/bytecode_override.rs similarity index 95% rename from src/bytecode_override.rs rename to crates/cli/src/bytecode_override.rs index 28badf5f..85e1d2ed 100644 --- a/src/bytecode_override.rs +++ b/crates/cli/src/bytecode_override.rs @@ -1,7 +1,7 @@ use std::fs; -use crate::fork::ForkSource; -use crate::node::InMemoryNode; +use anvil_zksync_core::fork::ForkSource; +use anvil_zksync_core::node::InMemoryNode; use eyre::Context; use hex::FromHex; use serde::Deserialize; diff --git a/src/config/cli.rs b/crates/cli/src/cli.rs similarity index 97% rename from src/config/cli.rs rename to crates/cli/src/cli.rs index 1ffee7c3..92633007 100644 --- a/src/config/cli.rs +++ b/crates/cli/src/cli.rs @@ -1,21 +1,19 @@ -use std::env; -use std::time::Duration; - -use clap::{arg, command, Parser, Subcommand}; -use rand::{rngs::StdRng, SeedableRng}; -use zksync_types::{H256, U256}; - -use super::DEFAULT_DISK_CACHE_DIR; -use crate::config::constants::{DEFAULT_MNEMONIC, TEST_NODE_NETWORK_ID}; -use crate::config::{ - AccountGenerator, CacheConfig, CacheType, Genesis, ShowCalls, ShowGasDetails, ShowStorageLogs, - ShowVMDetails, TestNodeConfig, -}; -use crate::observability::LogLevel; -use crate::system_contracts::Options as SystemContractsOptions; use crate::utils::parse_genesis_file; use alloy_signer_local::coins_bip39::{English, Mnemonic}; +use anvil_zksync_config::constants::{ + DEFAULT_DISK_CACHE_DIR, DEFAULT_MNEMONIC, TEST_NODE_NETWORK_ID, +}; +use anvil_zksync_config::types::{ + AccountGenerator, CacheConfig, CacheType, Genesis, LogLevel, ShowCalls, ShowGasDetails, + ShowStorageLogs, ShowVMDetails, SystemContractsOptions, +}; +use anvil_zksync_config::TestNodeConfig; +use clap::{arg, command, Parser, Subcommand}; +use rand::{rngs::StdRng, SeedableRng}; +use std::env; use std::net::IpAddr; +use std::time::Duration; +use zksync_types::{H256, U256}; #[derive(Debug, Parser, Clone)] #[command( @@ -433,7 +431,7 @@ fn duration_from_secs_f64(s: &str) -> Result { #[cfg(test)] mod tests { - use crate::config::cli::Cli; + use super::Cli; use clap::Parser; use std::{ env, diff --git a/src/logging_middleware.rs b/crates/cli/src/logging_middleware.rs similarity index 100% rename from src/logging_middleware.rs rename to crates/cli/src/logging_middleware.rs diff --git a/src/main.rs b/crates/cli/src/main.rs similarity index 91% rename from src/main.rs rename to crates/cli/src/main.rs index 80bd4792..b0c88c97 100644 --- a/src/main.rs +++ b/crates/cli/src/main.rs @@ -1,62 +1,46 @@ -use crate::observability::Observability; -use anvil_zksync::config::constants::DEFAULT_L1_GAS_PRICE; -use anyhow::anyhow; -use bytecode_override::override_bytecodes; -use clap::Parser; -use config::cli::{Cli, Command}; -use config::constants::{ +use crate::bytecode_override::override_bytecodes; +use crate::cli::{Cli, Command}; +use crate::utils::update_with_fork_details; +use anvil_zksync_config::constants::{ DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, - DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L2_GAS_PRICE, LEGACY_RICH_WALLETS, RICH_WALLETS, - TEST_NODE_NETWORK_ID, + DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L1_GAS_PRICE, DEFAULT_L2_GAS_PRICE, LEGACY_RICH_WALLETS, + RICH_WALLETS, TEST_NODE_NETWORK_ID, }; -use config::ForkPrintInfo; -use fork::{ForkDetails, ForkSource}; -use http_fork_source::HttpForkSource; -use logging_middleware::LoggingMiddleware; -use tracing_subscriber::filter::LevelFilter; - -mod bootloader_debug; -mod bytecode_override; -mod cache; -mod config; -mod console_log; -mod deps; -mod filters; -mod fork; -mod formatter; -mod http_fork_source; -mod logging_middleware; -mod namespaces; -mod node; -mod observability; -mod resolver; -mod system_contracts; -mod testing; -mod utils; - -use node::InMemoryNode; -use std::fs::File; -use std::{env, net::SocketAddr, str::FromStr}; -use zksync_types::fee_model::{FeeModelConfigV2, FeeParams}; -use zksync_web3_decl::namespaces::ZksNamespaceClient; - +use anvil_zksync_config::types::SystemContractsOptions; +use anvil_zksync_config::ForkPrintInfo; +use anvil_zksync_core::fork::{ForkDetails, ForkSource}; +use anvil_zksync_core::http_fork_source::HttpForkSource; +use anvil_zksync_core::namespaces::{ + AnvilNamespaceT, ConfigurationApiNamespaceT, DebugNamespaceT, EthNamespaceT, + EthTestNodeNamespaceT, EvmNamespaceT, HardhatNamespaceT, NetNamespaceT, Web3NamespaceT, + ZksNamespaceT, +}; +use anvil_zksync_core::node::{ + BlockProducer, BlockSealer, BlockSealerMode, ImpersonationManager, InMemoryNode, + TimestampManager, TxPool, +}; +use anvil_zksync_core::observability::Observability; +use anvil_zksync_core::system_contracts::SystemContracts; +use anyhow::anyhow; +use clap::Parser; use futures::{ channel::oneshot, future::{self}, FutureExt, }; use jsonrpc_core::MetaIoHandler; +use logging_middleware::LoggingMiddleware; +use std::fs::File; +use std::{env, net::SocketAddr, str::FromStr}; +use tracing_subscriber::filter::LevelFilter; +use zksync_types::fee_model::{FeeModelConfigV2, FeeParams}; use zksync_types::H160; +use zksync_web3_decl::namespaces::ZksNamespaceClient; -use crate::namespaces::{ - AnvilNamespaceT, ConfigurationApiNamespaceT, DebugNamespaceT, EthNamespaceT, - EthTestNodeNamespaceT, EvmNamespaceT, HardhatNamespaceT, NetNamespaceT, Web3NamespaceT, - ZksNamespaceT, -}; -use crate::node::{ - BlockProducer, BlockSealer, BlockSealerMode, ImpersonationManager, TimestampManager, TxPool, -}; -use crate::system_contracts::SystemContracts; +mod bytecode_override; +mod cli; +mod logging_middleware; +mod utils; #[allow(clippy::too_many_arguments)] async fn build_json_http< @@ -103,7 +87,7 @@ async fn build_json_http< let server = builder.start_http(&addr).unwrap(); server.wait(); - let _ = sender; + drop(sender); }); tokio::spawn(recv.map(drop)) @@ -212,7 +196,7 @@ async fn main() -> anyhow::Result<()> { .await }; - config.update_with_fork_details(fork_details_result).await? + update_with_fork_details(&mut config, fork_details_result).await? } Command::ReplayTx(replay_tx) => { let fork_details_result = ForkDetails::from_network_tx( @@ -222,7 +206,7 @@ async fn main() -> anyhow::Result<()> { ) .await; - config.update_with_fork_details(fork_details_result).await? + update_with_fork_details(&mut config, fork_details_result).await? } }; @@ -249,7 +233,7 @@ async fn main() -> anyhow::Result<()> { if matches!( config.system_contracts_options, - system_contracts::Options::Local + SystemContractsOptions::Local ) { if let Some(path) = env::var_os("ZKSYNC_HOME") { tracing::info!("+++++ Reading local contracts from {:?} +++++", path); @@ -292,7 +276,7 @@ async fn main() -> anyhow::Result<()> { } else if let Some(block_time) = config.block_time { BlockSealerMode::fixed_time(config.max_transactions, block_time) } else { - BlockSealerMode::immediate(config.max_transactions) + BlockSealerMode::immediate(config.max_transactions, pool.add_tx_listener()) }; let block_sealer = BlockSealer::new(sealing_mode); diff --git a/crates/cli/src/utils.rs b/crates/cli/src/utils.rs new file mode 100644 index 00000000..bc25a507 --- /dev/null +++ b/crates/cli/src/utils.rs @@ -0,0 +1,46 @@ +use anvil_zksync_config::types::Genesis; +use anvil_zksync_config::TestNodeConfig; +use anvil_zksync_core::fork::ForkDetails; +use std::fs; + +/// Parses the genesis file from the given path. +pub fn parse_genesis_file(path: &str) -> Result { + let file_content = + fs::read_to_string(path).map_err(|err| format!("Failed to read file: {err}"))?; + serde_json::from_str(&file_content).map_err(|err| format!("Failed to parse JSON: {err}")) +} + +/// Updates the configuration from fork details. +pub async fn update_with_fork_details( + config: &mut TestNodeConfig, + fork_details_result: Result, +) -> Result, anyhow::Error> { + match fork_details_result { + Ok(fd) => { + let l1_gas_price = config.l1_gas_price.or(Some(fd.l1_gas_price)); + let l2_gas_price = config.l2_gas_price.or(Some(fd.l2_fair_gas_price)); + let l1_pubdata_price = config.l1_pubdata_price.or(Some(fd.fair_pubdata_price)); + let price_scale = config + .price_scale_factor + .or(Some(fd.estimate_gas_price_scale_factor)); + let gas_limit_scale = config + .limit_scale_factor + .or(Some(fd.estimate_gas_scale_factor)); + let chain_id = config.chain_id.or(Some(fd.chain_id.as_u64() as u32)); + + config + .update_l1_gas_price(l1_gas_price) + .update_l2_gas_price(l2_gas_price) + .update_l1_pubdata_price(l1_pubdata_price) + .update_price_scale(price_scale) + .update_gas_limit_scale(gas_limit_scale) + .update_chain_id(chain_id); + + Ok(Some(fd)) + } + Err(error) => { + tracing::error!("Error while attempting to fork: {:?}", error); + Err(anyhow::anyhow!(error)) + } + } +} diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml new file mode 100644 index 00000000..7d53e7da --- /dev/null +++ b/crates/config/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "anvil_zksync_config" +description = "anvil-zksync configuration" +version.workspace = true +edition.workspace = true +authors.workspace = true +homepage.workspace = true +repository.workspace = true +license.workspace = true +keywords.workspace = true +categories.workspace = true + +[dependencies] +zksync_types.workspace = true +zksync_vm_interface.workspace = true + +alloy-signer.workspace = true +alloy-signer-local.workspace = true +clap.workspace = true +colored.workspace = true +hex.workspace = true +rand.workspace = true +serde.workspace = true +serde_json.workspace = true +tracing.workspace = true diff --git a/src/config/mod.rs b/crates/config/src/config.rs similarity index 84% rename from src/config/mod.rs rename to crates/config/src/config.rs index 28bfae82..d33592e1 100644 --- a/src/config/mod.rs +++ b/crates/config/src/config.rs @@ -1,36 +1,15 @@ -use crate::fork::ForkDetails; -use crate::{observability, system_contracts}; -use anyhow::anyhow; -use std::net::{IpAddr, Ipv4Addr}; -use zksync_multivm::interface::L1BatchEnv; -use zksync_types::api::TransactionVariant; - -use crate::config::{ - cache::{CacheConfig, CacheType}, - constants::*, - show_details::*, -}; +use crate::constants::*; +use crate::types::*; use crate::utils::{format_eth, format_gwei}; -use alloy_signer::Signer; -use alloy_signer_local::{ - coins_bip39::{English, Mnemonic}, - MnemonicBuilder, PrivateKeySigner, -}; +use alloy_signer_local::PrivateKeySigner; use colored::{Colorize, CustomColor}; -use observability::LogLevel; -use rand::thread_rng; -use serde::Deserialize; use serde_json::{json, to_writer, Value}; use std::collections::HashMap; use std::fs::File; +use std::net::{IpAddr, Ipv4Addr}; use std::time::Duration; use zksync_types::fee_model::FeeModelConfigV2; -use zksync_types::{Bloom, H256, U256}; - -pub mod cache; -pub mod cli; -pub mod constants; -pub mod show_details; +use zksync_types::U256; pub const VERSION_MESSAGE: &str = concat!(env!("CARGO_PKG_VERSION")); @@ -82,7 +61,7 @@ pub struct TestNodeConfig { /// Don’t print anything on startup if true pub silent: bool, /// Configuration for system contracts - pub system_contracts_options: system_contracts::Options, + pub system_contracts_options: SystemContractsOptions, /// Directory to override bytecodes pub override_bytecodes_dir: Option, /// Enables EVM emulation mode @@ -242,14 +221,10 @@ impl TestNodeConfig { if let Some(ref generator) = self.account_generator { tracing::info!("Wallet"); tracing::info!("========================"); - tracing::info!("Mnemonic: {}", generator.phrase.green()); + tracing::info!("Mnemonic: {}", generator.get_phrase().green()); tracing::info!( "Derivation path: {}", - generator - .derivation_path - .as_deref() - .unwrap_or(DERIVATION_PATH) - .green() + generator.get_derivation_path().green() ); } println!("\n"); @@ -461,7 +436,7 @@ impl TestNodeConfig { /// Set the system contracts configuration option #[must_use] - pub fn with_system_contracts(mut self, option: Option) -> Self { + pub fn with_system_contracts(mut self, option: Option) -> Self { if let Some(option) = option { self.system_contracts_options = option; } @@ -469,7 +444,7 @@ impl TestNodeConfig { } /// Get the system contracts configuration option - pub fn get_system_contracts(&self) -> system_contracts::Options { + pub fn get_system_contracts(&self) -> SystemContractsOptions { self.system_contracts_options } @@ -881,40 +856,6 @@ impl TestNodeConfig { self.health_check_endpoint } - /// Updates the configuration from fork details. - pub async fn update_with_fork_details( - &mut self, - fork_details_result: Result, - ) -> Result, anyhow::Error> { - match fork_details_result { - Ok(fd) => { - let l1_gas_price = self.l1_gas_price.or(Some(fd.l1_gas_price)); - let l2_gas_price = self.l2_gas_price.or(Some(fd.l2_fair_gas_price)); - let l1_pubdata_price = self.l1_pubdata_price.or(Some(fd.fair_pubdata_price)); - let price_scale = self - .price_scale_factor - .or(Some(fd.estimate_gas_price_scale_factor)); - let gas_limit_scale = self - .limit_scale_factor - .or(Some(fd.estimate_gas_scale_factor)); - let chain_id = self.chain_id.or(Some(fd.chain_id.as_u64() as u32)); - - self.update_l1_gas_price(l1_gas_price) - .update_l2_gas_price(l2_gas_price) - .update_l1_pubdata_price(l1_pubdata_price) - .update_price_scale(price_scale) - .update_gas_limit_scale(gas_limit_scale) - .update_chain_id(chain_id); - - Ok(Some(fd)) - } - Err(error) => { - tracing::error!("Error while attempting to fork: {:?}", error); - Err(anyhow!(error)) - } - } - } - /// Set the block time #[must_use] pub fn with_block_time(mut self, block_time: Option) -> Self { @@ -929,94 +870,3 @@ impl TestNodeConfig { self } } - -/// Account Generator -/// Manages the generation of accounts for anvil-zksync -#[derive(Clone, Debug, Deserialize)] -pub struct AccountGenerator { - chain_id: u32, - amount: usize, - phrase: String, - derivation_path: Option, -} - -impl AccountGenerator { - pub fn new(amount: usize) -> Self { - Self { - chain_id: TEST_NODE_NETWORK_ID, - amount, - phrase: Mnemonic::::new(&mut thread_rng()).to_phrase(), - derivation_path: None, - } - } - - #[must_use] - pub fn phrase(mut self, phrase: impl Into) -> Self { - self.phrase = phrase.into(); - self - } - - fn get_phrase(&self) -> &str { - &self.phrase - } - - #[must_use] - pub fn chain_id(mut self, chain_id: impl Into) -> Self { - self.chain_id = chain_id.into(); - self - } - - #[must_use] - pub fn derivation_path(mut self, derivation_path: impl Into) -> Self { - let mut derivation_path = derivation_path.into(); - if !derivation_path.ends_with('/') { - derivation_path.push('/'); - } - self.derivation_path = Some(derivation_path); - self - } - - fn get_derivation_path(&self) -> &str { - self.derivation_path.as_deref().unwrap_or(DERIVATION_PATH) - } - - pub fn gen(&self) -> Vec { - let builder = MnemonicBuilder::::default().phrase(self.phrase.as_str()); - - let derivation_path = self.derivation_path.as_deref().unwrap_or(DERIVATION_PATH); - - (0..self.amount) - .map(|idx| { - let builder = builder - .clone() - .derivation_path(format!("{derivation_path}{idx}")) - .unwrap(); - builder - .build() - .unwrap() - .with_chain_id(Some(self.chain_id.into())) - }) - .collect() - } -} - -/// Genesis -#[derive(Deserialize, Clone, Debug)] -pub struct Genesis { - /// The hash of the genesis block. If not provided, it can be computed. - pub hash: Option, - /// The parent hash of the genesis block. Usually zero. - pub parent_hash: Option, - /// The block number of the genesis block. Usually zero. - pub block_number: Option, - /// The timestamp of the genesis block. - pub timestamp: Option, - /// The L1 batch environment. - pub l1_batch_env: Option, - /// The transactions included in the genesis block. - pub transactions: Option>, - /// The amount of gas used. - pub gas_used: Option, - /// The logs bloom filter. - pub logs_bloom: Option, -} diff --git a/src/config/constants.rs b/crates/config/src/constants.rs similarity index 98% rename from src/config/constants.rs rename to crates/config/src/constants.rs index f2bc3c42..b89bdea4 100644 --- a/src/config/constants.rs +++ b/crates/config/src/constants.rs @@ -23,7 +23,7 @@ pub const DEFAULT_MNEMONIC: &str = "test test test test test test test test test /// Timestamp of the first block (if not running in fork mode). pub const NON_FORK_FIRST_BLOCK_TIMESTAMP: u64 = 1_000; /// Default account balance for the dev accounts -#[cfg(test)] +// TODO: Test-only constant, move to a test utils crate pub const DEFAULT_ACCOUNT_BALANCE: u128 = 1_000 * 10u128.pow(18); // List of wallets (address, private key, mnemonic) that we seed with tokens at start. pub const RICH_WALLETS: [(&str, &str, &str); 10] = [ diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs new file mode 100644 index 00000000..9a25065d --- /dev/null +++ b/crates/config/src/lib.rs @@ -0,0 +1,6 @@ +mod config; +pub mod constants; +pub mod types; +pub mod utils; + +pub use config::{ForkPrintInfo, TestNodeConfig}; diff --git a/crates/config/src/types/account_generator.rs b/crates/config/src/types/account_generator.rs new file mode 100644 index 00000000..ffa7a65f --- /dev/null +++ b/crates/config/src/types/account_generator.rs @@ -0,0 +1,75 @@ +use crate::constants::{DERIVATION_PATH, TEST_NODE_NETWORK_ID}; +use alloy_signer::Signer; +use alloy_signer_local::coins_bip39::{English, Mnemonic}; +use alloy_signer_local::{MnemonicBuilder, PrivateKeySigner}; +use serde::Deserialize; + +/// Account Generator +/// Manages the generation of accounts for anvil-zksync +#[derive(Clone, Debug, Deserialize)] +pub struct AccountGenerator { + chain_id: u32, + amount: usize, + phrase: String, + derivation_path: Option, +} + +impl AccountGenerator { + pub fn new(amount: usize) -> Self { + Self { + chain_id: TEST_NODE_NETWORK_ID, + amount, + phrase: Mnemonic::::new(&mut rand::thread_rng()).to_phrase(), + derivation_path: None, + } + } + + #[must_use] + pub fn phrase(mut self, phrase: impl Into) -> Self { + self.phrase = phrase.into(); + self + } + + pub fn get_phrase(&self) -> &str { + &self.phrase + } + + #[must_use] + pub fn chain_id(mut self, chain_id: impl Into) -> Self { + self.chain_id = chain_id.into(); + self + } + + #[must_use] + pub fn derivation_path(mut self, derivation_path: impl Into) -> Self { + let mut derivation_path = derivation_path.into(); + if !derivation_path.ends_with('/') { + derivation_path.push('/'); + } + self.derivation_path = Some(derivation_path); + self + } + + pub fn get_derivation_path(&self) -> &str { + self.derivation_path.as_deref().unwrap_or(DERIVATION_PATH) + } + + pub fn gen(&self) -> Vec { + let builder = MnemonicBuilder::::default().phrase(self.phrase.as_str()); + + let derivation_path = self.derivation_path.as_deref().unwrap_or(DERIVATION_PATH); + + (0..self.amount) + .map(|idx| { + let builder = builder + .clone() + .derivation_path(format!("{derivation_path}{idx}")) + .unwrap(); + builder + .build() + .unwrap() + .with_chain_id(Some(self.chain_id.into())) + }) + .collect() + } +} diff --git a/src/config/cache.rs b/crates/config/src/types/cache.rs similarity index 92% rename from src/config/cache.rs rename to crates/config/src/types/cache.rs index 1c49343b..c19cc3cd 100644 --- a/src/config/cache.rs +++ b/crates/config/src/types/cache.rs @@ -1,4 +1,4 @@ -use crate::config::constants::DEFAULT_DISK_CACHE_DIR; +use crate::constants::DEFAULT_DISK_CACHE_DIR; use clap::ValueEnum; use serde::Deserialize; diff --git a/crates/config/src/types/genesis.rs b/crates/config/src/types/genesis.rs new file mode 100644 index 00000000..55857ff7 --- /dev/null +++ b/crates/config/src/types/genesis.rs @@ -0,0 +1,25 @@ +use serde::Deserialize; +use zksync_types::api::TransactionVariant; +use zksync_types::{Bloom, H256, U256}; +use zksync_vm_interface::L1BatchEnv; + +/// Genesis +#[derive(Deserialize, Clone, Debug)] +pub struct Genesis { + /// The hash of the genesis block. If not provided, it can be computed. + pub hash: Option, + /// The parent hash of the genesis block. Usually zero. + pub parent_hash: Option, + /// The block number of the genesis block. Usually zero. + pub block_number: Option, + /// The timestamp of the genesis block. + pub timestamp: Option, + // /// The L1 batch environment. + pub l1_batch_env: Option, + /// The transactions included in the genesis block. + pub transactions: Option>, + /// The amount of gas used. + pub gas_used: Option, + /// The logs bloom filter. + pub logs_bloom: Option, +} diff --git a/crates/config/src/types/log.rs b/crates/config/src/types/log.rs new file mode 100644 index 00000000..33aa0ab7 --- /dev/null +++ b/crates/config/src/types/log.rs @@ -0,0 +1,40 @@ +use clap::ValueEnum; +use core::fmt; +use serde::{Deserialize, Serialize}; +use tracing::level_filters::LevelFilter; + +/// Log filter level for the node. +#[derive(Default, Debug, Copy, Clone, ValueEnum, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum LogLevel { + Trace, + Debug, + #[default] + Info, + Warn, + Error, +} + +impl fmt::Display for LogLevel { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + LogLevel::Trace => f.pad("TRACE"), + LogLevel::Debug => f.pad("DEBUG"), + LogLevel::Info => f.pad("INFO"), + LogLevel::Warn => f.pad("WARN"), + LogLevel::Error => f.pad("ERROR"), + } + } +} + +impl From for LevelFilter { + fn from(value: LogLevel) -> Self { + match value { + LogLevel::Trace => LevelFilter::TRACE, + LogLevel::Debug => LevelFilter::DEBUG, + LogLevel::Info => LevelFilter::INFO, + LogLevel::Warn => LevelFilter::WARN, + LogLevel::Error => LevelFilter::ERROR, + } + } +} diff --git a/crates/config/src/types/mod.rs b/crates/config/src/types/mod.rs new file mode 100644 index 00000000..2c216f4d --- /dev/null +++ b/crates/config/src/types/mod.rs @@ -0,0 +1,24 @@ +mod account_generator; +mod cache; +mod genesis; +mod log; +mod show_details; + +pub use account_generator::AccountGenerator; +pub use cache::{CacheConfig, CacheType}; +use clap::ValueEnum; +pub use genesis::Genesis; +pub use log::LogLevel; +use serde::Deserialize; +pub use show_details::{ShowCalls, ShowGasDetails, ShowStorageLogs, ShowVMDetails}; + +#[derive(Deserialize, Default, Debug, Copy, Clone, PartialEq, ValueEnum)] +pub enum SystemContractsOptions { + // Use the compiled-in contracts + #[default] + BuiltIn, + // Load the contracts bytecode at runtime from ZKSYNC_HOME + Local, + // Don't verify the signatures and return transaction result on calls (used only for testing - for example Forge). + BuiltInWithoutSecurity, +} diff --git a/src/config/show_details.rs b/crates/config/src/types/show_details.rs similarity index 100% rename from src/config/show_details.rs rename to crates/config/src/types/show_details.rs diff --git a/crates/config/src/utils.rs b/crates/config/src/utils.rs new file mode 100644 index 00000000..6488ae2b --- /dev/null +++ b/crates/config/src/utils.rs @@ -0,0 +1,23 @@ +use zksync_types::U256; + +// TODO: look to remove in favour of alloy-primitives utils +/// Formats a `U256` value as Ether without capping decimal points. +pub fn format_eth(value: U256) -> String { + let wei_per_eth = U256::from(10).pow(U256::from(18)); + let whole_eth = value / wei_per_eth; + let remainder_wei = value % wei_per_eth; + let fractional_eth = remainder_wei.as_u128() as f64 / 1e18; + + format!("{} ETH", whole_eth.as_u128() as f64 + fractional_eth) +} +// TODO: look to remove in favour of alloy-primitives utils +/// Formats a `U256` value as Gwei without capping decimal points. +pub fn format_gwei(value: U256) -> String { + let gwei_value = value / U256::exp10(9); + let fractional = value % U256::exp10(9); + + let fractional_part = fractional.as_u128() as f64 / 1e9; + let full_gwei = gwei_value.as_u128() as f64 + fractional_part; + + format!("{:.8} gwei", full_gwei) +} diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml new file mode 100644 index 00000000..6945a7cf --- /dev/null +++ b/crates/core/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "anvil_zksync_core" +version.workspace = true +edition.workspace = true +authors.workspace = true +homepage.workspace = true +repository.workspace = true +license.workspace = true +keywords.workspace = true +categories.workspace = true + +[dependencies] +anvil_zksync_config.workspace = true + +zksync_multivm.workspace = true +zksync_contracts.workspace = true +zksync_types.workspace = true +zksync_utils.workspace = true +zksync_web3_decl.workspace = true + +anyhow.workspace = true +tokio.workspace = true +futures.workspace = true +once_cell.workspace = true + +jsonrpc-core.workspace = true +jsonrpc-core-client.workspace = true +jsonrpc-derive.workspace = true + +reqwest.workspace = true +serde.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +colored.workspace = true +lazy_static.workspace = true +eyre.workspace = true +serde_json.workspace = true +bigdecimal.workspace = true +hex.workspace = true +ethabi.workspace = true +itertools.workspace = true +rustc-hash.workspace = true +indexmap.workspace = true +chrono.workspace = true +time.workspace = true +flate2.workspace = true +thiserror.workspace = true + +[dev-dependencies] +httptest = "0.15.4" +tempdir = "0.3.7" +maplit = "1.0.2" +zksync-web3-rs = "0.1.1" +ethers = { version = "2.0.4", features = ["rustls"] } +test-case = "3.3.1" diff --git a/src/bootloader_debug.rs b/crates/core/src/bootloader_debug.rs similarity index 100% rename from src/bootloader_debug.rs rename to crates/core/src/bootloader_debug.rs diff --git a/src/cache.rs b/crates/core/src/cache.rs similarity index 99% rename from src/cache.rs rename to crates/core/src/cache.rs index c6a99a18..765b5f7a 100644 --- a/src/cache.rs +++ b/crates/core/src/cache.rs @@ -1,3 +1,4 @@ +use anvil_zksync_config::types::CacheConfig; use rustc_hash::FxHashMap; use serde::Serialize; use std::fs; @@ -10,8 +11,6 @@ use zksync_types::api::{Block, BridgeAddresses, Transaction, TransactionVariant} use zksync_types::Transaction as RawTransaction; use zksync_types::H256; -use crate::config::cache::CacheConfig; - /// Caches full blocks by their hashes const CACHE_TYPE_BLOCKS_FULL: &str = "blocks_full"; /// Caches minimal blocks by their hashes diff --git a/src/console_log.rs b/crates/core/src/console_log.rs similarity index 100% rename from src/console_log.rs rename to crates/core/src/console_log.rs diff --git a/src/data/abi_map.json b/crates/core/src/data/abi_map.json similarity index 100% rename from src/data/abi_map.json rename to crates/core/src/data/abi_map.json diff --git a/src/data/address_map.json b/crates/core/src/data/address_map.json similarity index 100% rename from src/data/address_map.json rename to crates/core/src/data/address_map.json diff --git a/src/deps/contracts/AccountCodeStorage.json b/crates/core/src/deps/contracts/AccountCodeStorage.json similarity index 100% rename from src/deps/contracts/AccountCodeStorage.json rename to crates/core/src/deps/contracts/AccountCodeStorage.json diff --git a/src/deps/contracts/BootloaderUtilities.json b/crates/core/src/deps/contracts/BootloaderUtilities.json similarity index 100% rename from src/deps/contracts/BootloaderUtilities.json rename to crates/core/src/deps/contracts/BootloaderUtilities.json diff --git a/src/deps/contracts/CodeOracle.yul.zbin b/crates/core/src/deps/contracts/CodeOracle.yul.zbin similarity index 100% rename from src/deps/contracts/CodeOracle.yul.zbin rename to crates/core/src/deps/contracts/CodeOracle.yul.zbin diff --git a/src/deps/contracts/ComplexUpgrader.json b/crates/core/src/deps/contracts/ComplexUpgrader.json similarity index 100% rename from src/deps/contracts/ComplexUpgrader.json rename to crates/core/src/deps/contracts/ComplexUpgrader.json diff --git a/src/deps/contracts/Compressor.json b/crates/core/src/deps/contracts/Compressor.json similarity index 100% rename from src/deps/contracts/Compressor.json rename to crates/core/src/deps/contracts/Compressor.json diff --git a/src/deps/contracts/ContractDeployer.json b/crates/core/src/deps/contracts/ContractDeployer.json similarity index 100% rename from src/deps/contracts/ContractDeployer.json rename to crates/core/src/deps/contracts/ContractDeployer.json diff --git a/src/deps/contracts/Create2Factory.json b/crates/core/src/deps/contracts/Create2Factory.json similarity index 100% rename from src/deps/contracts/Create2Factory.json rename to crates/core/src/deps/contracts/Create2Factory.json diff --git a/src/deps/contracts/DefaultAccount.json b/crates/core/src/deps/contracts/DefaultAccount.json similarity index 100% rename from src/deps/contracts/DefaultAccount.json rename to crates/core/src/deps/contracts/DefaultAccount.json diff --git a/src/deps/contracts/DefaultAccountNoSecurity.json b/crates/core/src/deps/contracts/DefaultAccountNoSecurity.json similarity index 100% rename from src/deps/contracts/DefaultAccountNoSecurity.json rename to crates/core/src/deps/contracts/DefaultAccountNoSecurity.json diff --git a/src/deps/contracts/EcAdd.yul.zbin b/crates/core/src/deps/contracts/EcAdd.yul.zbin similarity index 100% rename from src/deps/contracts/EcAdd.yul.zbin rename to crates/core/src/deps/contracts/EcAdd.yul.zbin diff --git a/src/deps/contracts/EcMul.yul.zbin b/crates/core/src/deps/contracts/EcMul.yul.zbin similarity index 100% rename from src/deps/contracts/EcMul.yul.zbin rename to crates/core/src/deps/contracts/EcMul.yul.zbin diff --git a/src/deps/contracts/EcPairing.yul.zbin b/crates/core/src/deps/contracts/EcPairing.yul.zbin similarity index 100% rename from src/deps/contracts/EcPairing.yul.zbin rename to crates/core/src/deps/contracts/EcPairing.yul.zbin diff --git a/src/deps/contracts/Ecrecover.yul.zbin b/crates/core/src/deps/contracts/Ecrecover.yul.zbin similarity index 100% rename from src/deps/contracts/Ecrecover.yul.zbin rename to crates/core/src/deps/contracts/Ecrecover.yul.zbin diff --git a/src/deps/contracts/EmptyContract.json b/crates/core/src/deps/contracts/EmptyContract.json similarity index 100% rename from src/deps/contracts/EmptyContract.json rename to crates/core/src/deps/contracts/EmptyContract.json diff --git a/src/deps/contracts/EventWriter.yul.zbin b/crates/core/src/deps/contracts/EventWriter.yul.zbin similarity index 100% rename from src/deps/contracts/EventWriter.yul.zbin rename to crates/core/src/deps/contracts/EventWriter.yul.zbin diff --git a/src/deps/contracts/ImmutableSimulator.json b/crates/core/src/deps/contracts/ImmutableSimulator.json similarity index 100% rename from src/deps/contracts/ImmutableSimulator.json rename to crates/core/src/deps/contracts/ImmutableSimulator.json diff --git a/src/deps/contracts/Keccak256.yul.zbin b/crates/core/src/deps/contracts/Keccak256.yul.zbin similarity index 100% rename from src/deps/contracts/Keccak256.yul.zbin rename to crates/core/src/deps/contracts/Keccak256.yul.zbin diff --git a/src/deps/contracts/KnownCodesStorage.json b/crates/core/src/deps/contracts/KnownCodesStorage.json similarity index 100% rename from src/deps/contracts/KnownCodesStorage.json rename to crates/core/src/deps/contracts/KnownCodesStorage.json diff --git a/src/deps/contracts/L1Messenger.json b/crates/core/src/deps/contracts/L1Messenger.json similarity index 100% rename from src/deps/contracts/L1Messenger.json rename to crates/core/src/deps/contracts/L1Messenger.json diff --git a/src/deps/contracts/L2BaseToken.json b/crates/core/src/deps/contracts/L2BaseToken.json similarity index 100% rename from src/deps/contracts/L2BaseToken.json rename to crates/core/src/deps/contracts/L2BaseToken.json diff --git a/src/deps/contracts/MsgValueSimulator.json b/crates/core/src/deps/contracts/MsgValueSimulator.json similarity index 100% rename from src/deps/contracts/MsgValueSimulator.json rename to crates/core/src/deps/contracts/MsgValueSimulator.json diff --git a/src/deps/contracts/NonceHolder.json b/crates/core/src/deps/contracts/NonceHolder.json similarity index 100% rename from src/deps/contracts/NonceHolder.json rename to crates/core/src/deps/contracts/NonceHolder.json diff --git a/src/deps/contracts/P256Verify.yul.zbin b/crates/core/src/deps/contracts/P256Verify.yul.zbin similarity index 100% rename from src/deps/contracts/P256Verify.yul.zbin rename to crates/core/src/deps/contracts/P256Verify.yul.zbin diff --git a/src/deps/contracts/PubdataChunkPublisher.json b/crates/core/src/deps/contracts/PubdataChunkPublisher.json similarity index 100% rename from src/deps/contracts/PubdataChunkPublisher.json rename to crates/core/src/deps/contracts/PubdataChunkPublisher.json diff --git a/src/deps/contracts/SHA256.yul.zbin b/crates/core/src/deps/contracts/SHA256.yul.zbin similarity index 100% rename from src/deps/contracts/SHA256.yul.zbin rename to crates/core/src/deps/contracts/SHA256.yul.zbin diff --git a/src/deps/contracts/SystemContext.json b/crates/core/src/deps/contracts/SystemContext.json similarity index 100% rename from src/deps/contracts/SystemContext.json rename to crates/core/src/deps/contracts/SystemContext.json diff --git a/src/deps/contracts/TimestampAsserter.json b/crates/core/src/deps/contracts/TimestampAsserter.json similarity index 100% rename from src/deps/contracts/TimestampAsserter.json rename to crates/core/src/deps/contracts/TimestampAsserter.json diff --git a/src/deps/contracts/fee_estimate.yul.zbin b/crates/core/src/deps/contracts/fee_estimate.yul.zbin similarity index 100% rename from src/deps/contracts/fee_estimate.yul.zbin rename to crates/core/src/deps/contracts/fee_estimate.yul.zbin diff --git a/src/deps/contracts/fee_estimate_impersonating.yul.zbin b/crates/core/src/deps/contracts/fee_estimate_impersonating.yul.zbin similarity index 100% rename from src/deps/contracts/fee_estimate_impersonating.yul.zbin rename to crates/core/src/deps/contracts/fee_estimate_impersonating.yul.zbin diff --git a/src/deps/contracts/gas_test.yul.zbin b/crates/core/src/deps/contracts/gas_test.yul.zbin similarity index 100% rename from src/deps/contracts/gas_test.yul.zbin rename to crates/core/src/deps/contracts/gas_test.yul.zbin diff --git a/src/deps/contracts/playground_batch.yul.zbin b/crates/core/src/deps/contracts/playground_batch.yul.zbin similarity index 100% rename from src/deps/contracts/playground_batch.yul.zbin rename to crates/core/src/deps/contracts/playground_batch.yul.zbin diff --git a/src/deps/contracts/proved_batch.yul.zbin b/crates/core/src/deps/contracts/proved_batch.yul.zbin similarity index 100% rename from src/deps/contracts/proved_batch.yul.zbin rename to crates/core/src/deps/contracts/proved_batch.yul.zbin diff --git a/src/deps/contracts/proved_batch_impersonating.yul.zbin b/crates/core/src/deps/contracts/proved_batch_impersonating.yul.zbin similarity index 100% rename from src/deps/contracts/proved_batch_impersonating.yul.zbin rename to crates/core/src/deps/contracts/proved_batch_impersonating.yul.zbin diff --git a/src/deps/mod.rs b/crates/core/src/deps/mod.rs similarity index 96% rename from src/deps/mod.rs rename to crates/core/src/deps/mod.rs index acdcb450..9c52ca99 100644 --- a/src/deps/mod.rs +++ b/crates/core/src/deps/mod.rs @@ -1,11 +1,13 @@ +use anvil_zksync_config::types::SystemContractsOptions; use std::collections::HashMap; -pub mod system_contracts; +use zksync_multivm::interface::storage::ReadStorage; use zksync_types::{ get_code_key, get_system_context_init_logs, L2ChainId, StorageKey, StorageLog, StorageValue, H256, }; + pub mod storage_view; -use zksync_multivm::interface::storage::ReadStorage; +pub mod system_contracts; /// In-memory storage. #[derive(Debug, Default, Clone, PartialEq)] @@ -19,7 +21,7 @@ impl InMemoryStorage { pub fn with_system_contracts_and_chain_id( chain_id: L2ChainId, bytecode_hasher: impl Fn(&[u8]) -> H256, - system_contracts_options: &crate::system_contracts::Options, + system_contracts_options: &SystemContractsOptions, use_evm_emulator: bool, ) -> Self { let contracts = diff --git a/src/deps/storage_view.rs b/crates/core/src/deps/storage_view.rs similarity index 100% rename from src/deps/storage_view.rs rename to crates/core/src/deps/storage_view.rs diff --git a/src/deps/system_contracts.rs b/crates/core/src/deps/system_contracts.rs similarity index 95% rename from src/deps/system_contracts.rs rename to crates/core/src/deps/system_contracts.rs index 65d883f7..d0d01681 100644 --- a/src/deps/system_contracts.rs +++ b/crates/core/src/deps/system_contracts.rs @@ -1,4 +1,4 @@ -use crate::system_contracts::Options; +use anvil_zksync_config::types::SystemContractsOptions; use once_cell::sync::Lazy; use serde_json::Value; use zksync_types::system_contracts::get_system_smart_contracts; @@ -194,11 +194,13 @@ pub static COMPILED_IN_SYSTEM_CONTRACTS: Lazy> = Lazy::new }); pub fn get_deployed_contracts( - options: &Options, + options: &SystemContractsOptions, use_evm_emulator: bool, ) -> Vec { match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => COMPILED_IN_SYSTEM_CONTRACTS.clone(), - Options::Local => get_system_smart_contracts(use_evm_emulator), + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { + COMPILED_IN_SYSTEM_CONTRACTS.clone() + } + SystemContractsOptions::Local => get_system_smart_contracts(use_evm_emulator), } } diff --git a/src/deps/test-contracts/Primary.json b/crates/core/src/deps/test-contracts/Primary.json similarity index 100% rename from src/deps/test-contracts/Primary.json rename to crates/core/src/deps/test-contracts/Primary.json diff --git a/src/deps/test-contracts/Secondary.json b/crates/core/src/deps/test-contracts/Secondary.json similarity index 100% rename from src/deps/test-contracts/Secondary.json rename to crates/core/src/deps/test-contracts/Secondary.json diff --git a/src/filters.rs b/crates/core/src/filters.rs similarity index 100% rename from src/filters.rs rename to crates/core/src/filters.rs diff --git a/src/fork.rs b/crates/core/src/fork.rs similarity index 98% rename from src/fork.rs rename to crates/core/src/fork.rs index 8e3bcf0d..1d3bb6e1 100644 --- a/src/fork.rs +++ b/crates/core/src/fork.rs @@ -3,15 +3,12 @@ //! There is ForkStorage (that is a wrapper over InMemoryStorage) //! And ForkDetails - that parses network address and fork height from arguments. -use crate::config::{ - cache::CacheConfig, - constants::{ - DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, - DEFAULT_FAIR_PUBDATA_PRICE, TEST_NODE_NETWORK_ID, - }, -}; -use crate::system_contracts; use crate::{deps::InMemoryStorage, http_fork_source::HttpForkSource}; +use anvil_zksync_config::constants::{ + DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, + DEFAULT_FAIR_PUBDATA_PRICE, TEST_NODE_NETWORK_ID, +}; +use anvil_zksync_config::types::{CacheConfig, SystemContractsOptions}; use eyre::eyre; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -124,7 +121,7 @@ pub struct ForkStorageInner { impl ForkStorage { pub fn new( fork: Option, - system_contracts_options: &system_contracts::Options, + system_contracts_options: &SystemContractsOptions, use_evm_emulator: bool, override_chain_id: Option, ) -> Self { @@ -872,21 +869,17 @@ mod serde_from { #[cfg(test)] mod tests { + use super::{ForkDetails, ForkStorage}; + use crate::{deps::InMemoryStorage, testing}; + use anvil_zksync_config::constants::{ + DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, + DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L2_GAS_PRICE, TEST_NODE_NETWORK_ID, + }; + use anvil_zksync_config::types::{CacheConfig, SystemContractsOptions}; use zksync_multivm::interface::storage::ReadStorage; use zksync_types::{api::TransactionVariant, StorageKey}; use zksync_types::{AccountTreeId, L1BatchNumber, L2ChainId, H256}; - use crate::config::{ - cache::CacheConfig, - constants::{ - DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, - DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L2_GAS_PRICE, TEST_NODE_NETWORK_ID, - }, - }; - use crate::{deps::InMemoryStorage, system_contracts, testing}; - - use super::{ForkDetails, ForkStorage}; - #[test] fn test_initial_writes() { let account = AccountTreeId::default(); @@ -901,7 +894,7 @@ mod tests { raw_storage: in_memory_storage, }; - let options = system_contracts::Options::default(); + let options = SystemContractsOptions::default(); let fork_details = ForkDetails { fork_source: Box::new(external_storage), diff --git a/src/formatter.rs b/crates/core/src/formatter.rs similarity index 99% rename from src/formatter.rs rename to crates/core/src/formatter.rs index b76bdb65..f63798a1 100644 --- a/src/formatter.rs +++ b/crates/core/src/formatter.rs @@ -1,9 +1,10 @@ //! Helper methods to display transaction data in more human readable way. use crate::bootloader_debug::BootloaderDebug; use crate::fork::block_on; -use crate::utils::{calculate_eth_cost, format_gwei, to_human_size}; -use crate::{config::show_details::ShowCalls, resolver}; - +use crate::resolver; +use crate::utils::{calculate_eth_cost, to_human_size}; +use anvil_zksync_config::types::ShowCalls; +use anvil_zksync_config::utils::format_gwei; use colored::Colorize; use futures::future::join_all; use lazy_static::lazy_static; diff --git a/src/http_fork_source.rs b/crates/core/src/http_fork_source.rs similarity index 99% rename from src/http_fork_source.rs rename to crates/core/src/http_fork_source.rs index 1df25c5f..b98be508 100644 --- a/src/http_fork_source.rs +++ b/crates/core/src/http_fork_source.rs @@ -5,9 +5,9 @@ use std::{ use crate::{ cache::Cache, - config::cache::CacheConfig, fork::{block_on, ForkSource}, }; +use anvil_zksync_config::types::CacheConfig; use eyre::Context; use zksync_types::{ api::{BridgeAddresses, Transaction}, diff --git a/src/lib.rs b/crates/core/src/lib.rs similarity index 99% rename from src/lib.rs rename to crates/core/src/lib.rs index 591af031..83084595 100644 --- a/src/lib.rs +++ b/crates/core/src/lib.rs @@ -42,7 +42,6 @@ //! Contributions to improve `anvil-zksync` are welcome. Please refer to the [contribution guidelines](https://github.com/matter-labs/anvil-zksync/blob/main/.github/CONTRIBUTING.md) for more details. pub mod bootloader_debug; -pub mod config; pub mod console_log; pub mod deps; pub mod filters; diff --git a/src/namespaces/anvil.rs b/crates/core/src/namespaces/anvil.rs similarity index 100% rename from src/namespaces/anvil.rs rename to crates/core/src/namespaces/anvil.rs diff --git a/src/namespaces/config.rs b/crates/core/src/namespaces/config.rs similarity index 99% rename from src/namespaces/config.rs rename to crates/core/src/namespaces/config.rs index bfb4b922..25ac87b5 100644 --- a/src/namespaces/config.rs +++ b/crates/core/src/namespaces/config.rs @@ -1,5 +1,5 @@ use crate::namespaces::Result; -use crate::observability::LogLevel; +use anvil_zksync_config::types::LogLevel; use jsonrpc_derive::rpc; #[rpc] diff --git a/src/namespaces/debug.rs b/crates/core/src/namespaces/debug.rs similarity index 100% rename from src/namespaces/debug.rs rename to crates/core/src/namespaces/debug.rs diff --git a/src/namespaces/eth.rs b/crates/core/src/namespaces/eth.rs similarity index 100% rename from src/namespaces/eth.rs rename to crates/core/src/namespaces/eth.rs diff --git a/src/namespaces/eth_test.rs b/crates/core/src/namespaces/eth_test.rs similarity index 100% rename from src/namespaces/eth_test.rs rename to crates/core/src/namespaces/eth_test.rs diff --git a/src/namespaces/evm.rs b/crates/core/src/namespaces/evm.rs similarity index 100% rename from src/namespaces/evm.rs rename to crates/core/src/namespaces/evm.rs diff --git a/src/namespaces/hardhat.rs b/crates/core/src/namespaces/hardhat.rs similarity index 100% rename from src/namespaces/hardhat.rs rename to crates/core/src/namespaces/hardhat.rs diff --git a/src/namespaces/mod.rs b/crates/core/src/namespaces/mod.rs similarity index 100% rename from src/namespaces/mod.rs rename to crates/core/src/namespaces/mod.rs diff --git a/src/namespaces/net.rs b/crates/core/src/namespaces/net.rs similarity index 100% rename from src/namespaces/net.rs rename to crates/core/src/namespaces/net.rs diff --git a/src/namespaces/web3.rs b/crates/core/src/namespaces/web3.rs similarity index 100% rename from src/namespaces/web3.rs rename to crates/core/src/namespaces/web3.rs diff --git a/src/namespaces/zks.rs b/crates/core/src/namespaces/zks.rs similarity index 100% rename from src/namespaces/zks.rs rename to crates/core/src/namespaces/zks.rs diff --git a/src/node/anvil.rs b/crates/core/src/node/anvil.rs similarity index 100% rename from src/node/anvil.rs rename to crates/core/src/node/anvil.rs diff --git a/src/node/block_producer.rs b/crates/core/src/node/block_producer.rs similarity index 65% rename from src/node/block_producer.rs rename to crates/core/src/node/block_producer.rs index 4302eb07..f97523f3 100644 --- a/src/node/block_producer.rs +++ b/crates/core/src/node/block_producer.rs @@ -37,18 +37,19 @@ impl Future for BlockProducer { fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let pin = self.get_mut(); - loop { - if let Poll::Ready(tx_batch) = pin.block_sealer.poll(&pin.pool, cx) { - let TxBatch { impersonating, txs } = tx_batch; - let base_system_contracts = pin - .system_contracts - .contracts(TxExecutionMode::VerifyExecute, impersonating) - .clone(); - pin.node - .seal_block(&mut pin.node.time.lock(), txs, base_system_contracts) - .expect("block sealing failed"); - } + while let Poll::Ready(tx_batch) = pin.block_sealer.poll(&pin.pool, cx) { + let TxBatch { impersonating, txs } = tx_batch; + + let base_system_contracts = pin + .system_contracts + .contracts(TxExecutionMode::VerifyExecute, impersonating) + .clone(); + pin.node + .seal_block(&mut pin.node.time.lock(), txs, base_system_contracts) + .expect("block sealing failed"); } + + Poll::Pending } } diff --git a/src/node/call_error_tracer.rs b/crates/core/src/node/call_error_tracer.rs similarity index 100% rename from src/node/call_error_tracer.rs rename to crates/core/src/node/call_error_tracer.rs diff --git a/src/node/config_api.rs b/crates/core/src/node/config_api.rs similarity index 98% rename from src/node/config_api.rs rename to crates/core/src/node/config_api.rs index fd4afc4e..c2ac5b2a 100644 --- a/src/node/config_api.rs +++ b/crates/core/src/node/config_api.rs @@ -1,14 +1,14 @@ -use zksync_web3_decl::error::Web3Error; - use crate::node::time::ReadTime; use crate::{ - config::show_details::{ShowCalls, ShowGasDetails, ShowStorageLogs, ShowVMDetails}, fork::ForkSource, namespaces::{ConfigurationApiNamespaceT, Result}, node::InMemoryNode, - observability::LogLevel, utils::into_jsrpc_error, }; +use anvil_zksync_config::types::{ + LogLevel, ShowCalls, ShowGasDetails, ShowStorageLogs, ShowVMDetails, +}; +use zksync_web3_decl::error::Web3Error; impl ConfigurationApiNamespaceT for InMemoryNode diff --git a/src/node/debug.rs b/crates/core/src/node/debug.rs similarity index 99% rename from src/node/debug.rs rename to crates/core/src/node/debug.rs index 3cd7ca9b..c2ee6017 100644 --- a/src/node/debug.rs +++ b/crates/core/src/node/debug.rs @@ -235,6 +235,7 @@ impl DebugNames #[cfg(test)] mod tests { + use anvil_zksync_config::constants::DEFAULT_ACCOUNT_BALANCE; use ethers::abi::{short_signature, AbiEncode, HumanReadableParser, ParamType, Token}; use zksync_types::{ api::{Block, CallTracerConfig, SupportedTracers, TransactionReceipt}, @@ -245,7 +246,6 @@ mod tests { use super::*; use crate::{ - config::constants::DEFAULT_ACCOUNT_BALANCE, deps::system_contracts::bytecode_from_slice, http_fork_source::HttpForkSource, node::{InMemoryNode, TransactionResult}, diff --git a/src/node/error.rs b/crates/core/src/node/error.rs similarity index 100% rename from src/node/error.rs rename to crates/core/src/node/error.rs diff --git a/src/node/eth.rs b/crates/core/src/node/eth.rs similarity index 99% rename from src/node/eth.rs rename to crates/core/src/node/eth.rs index 58fd7a84..2b11a643 100644 --- a/src/node/eth.rs +++ b/crates/core/src/node/eth.rs @@ -1462,12 +1462,6 @@ impl EthTestNod mod tests { use super::*; use crate::{ - config::{ - cache::CacheConfig, - constants::{ - DEFAULT_ACCOUNT_BALANCE, DEFAULT_L2_GAS_PRICE, NON_FORK_FIRST_BLOCK_TIMESTAMP, - }, - }, fork::ForkDetails, http_fork_source::HttpForkSource, node::{compute_hash, InMemoryNode, Snapshot}, @@ -1476,6 +1470,10 @@ mod tests { TransactionResponseBuilder, }, }; + use anvil_zksync_config::constants::{ + DEFAULT_ACCOUNT_BALANCE, DEFAULT_L2_GAS_PRICE, NON_FORK_FIRST_BLOCK_TIMESTAMP, + }; + use anvil_zksync_config::types::CacheConfig; use maplit::hashmap; use zksync_multivm::utils::get_max_batch_gas_limit; use zksync_types::l2::TransactionType; diff --git a/src/node/evm.rs b/crates/core/src/node/evm.rs similarity index 100% rename from src/node/evm.rs rename to crates/core/src/node/evm.rs diff --git a/src/node/fee_model.rs b/crates/core/src/node/fee_model.rs similarity index 99% rename from src/node/fee_model.rs rename to crates/core/src/node/fee_model.rs index 20ca202e..33b7fcd5 100644 --- a/src/node/fee_model.rs +++ b/crates/core/src/node/fee_model.rs @@ -4,7 +4,7 @@ use zksync_types::fee_model::{ BaseTokenConversionRatio, BatchFeeInput, FeeModelConfigV2, FeeParams, FeeParamsV2, }; -use crate::config::constants::{ +use anvil_zksync_config::constants::{ DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L1_GAS_PRICE, DEFAULT_L2_GAS_PRICE, }; diff --git a/src/node/hardhat.rs b/crates/core/src/node/hardhat.rs similarity index 100% rename from src/node/hardhat.rs rename to crates/core/src/node/hardhat.rs diff --git a/src/node/impersonate.rs b/crates/core/src/node/impersonate.rs similarity index 100% rename from src/node/impersonate.rs rename to crates/core/src/node/impersonate.rs diff --git a/src/node/in_memory.rs b/crates/core/src/node/in_memory.rs similarity index 97% rename from src/node/in_memory.rs rename to crates/core/src/node/in_memory.rs index 8b15321a..422dee58 100644 --- a/src/node/in_memory.rs +++ b/crates/core/src/node/in_memory.rs @@ -1,4 +1,33 @@ //! In-memory node, that supports forking other networks. +use crate::fork::SerializableStorage; +use crate::node::error::LoadStateError; +use crate::node::impersonate::{ImpersonationManager, ImpersonationState}; +use crate::node::state::{StateV1, VersionedState}; +use crate::node::time::{AdvanceTime, ReadTime, TimestampManager}; +use crate::node::{BlockSealer, BlockSealerMode, TxPool}; +use crate::{ + bootloader_debug::{BootloaderDebug, BootloaderDebugTracer}, + console_log::ConsoleLogHandler, + deps::{storage_view::StorageView, InMemoryStorage}, + filters::EthFilters, + fork::{ForkDetails, ForkSource, ForkStorage}, + formatter, + node::{ + call_error_tracer::CallErrorTracer, fee_model::TestNodeFeeInputProvider, + storage_logs::print_storage_logs_details, + }, + observability::Observability, + system_contracts::SystemContracts, + utils::{bytecode_to_factory_dep, create_debug_output, into_jsrpc_error}, +}; +use anvil_zksync_config::constants::{ + LEGACY_RICH_WALLETS, NON_FORK_FIRST_BLOCK_TIMESTAMP, RICH_WALLETS, +}; +use anvil_zksync_config::types::{ + CacheConfig, Genesis, ShowCalls, ShowGasDetails, ShowStorageLogs, ShowVMDetails, + SystemContractsOptions, +}; +use anvil_zksync_config::TestNodeConfig; use colored::Colorize; use flate2::read::GzDecoder; use flate2::write::GzEncoder; @@ -52,34 +81,6 @@ use zksync_types::{ use zksync_utils::{bytecode::hash_bytecode, h256_to_account_address, h256_to_u256, u256_to_h256}; use zksync_web3_decl::error::Web3Error; -use crate::fork::SerializableStorage; -use crate::node::error::LoadStateError; -use crate::node::impersonate::{ImpersonationManager, ImpersonationState}; -use crate::node::state::{StateV1, VersionedState}; -use crate::node::time::{AdvanceTime, ReadTime, TimestampManager}; -use crate::node::{BlockSealer, TxPool}; -use crate::{ - bootloader_debug::{BootloaderDebug, BootloaderDebugTracer}, - config::{ - cache::CacheConfig, - constants::{LEGACY_RICH_WALLETS, NON_FORK_FIRST_BLOCK_TIMESTAMP, RICH_WALLETS}, - show_details::{ShowCalls, ShowGasDetails, ShowStorageLogs, ShowVMDetails}, - Genesis, TestNodeConfig, - }, - console_log::ConsoleLogHandler, - deps::{storage_view::StorageView, InMemoryStorage}, - filters::EthFilters, - fork::{ForkDetails, ForkSource, ForkStorage}, - formatter, - node::{ - call_error_tracer::CallErrorTracer, fee_model::TestNodeFeeInputProvider, - storage_logs::print_storage_logs_details, - }, - observability::Observability, - system_contracts::{self, SystemContracts}, - utils::{bytecode_to_factory_dep, create_debug_output, into_jsrpc_error}, -}; - /// Max possible size of an ABI encoded tx (in bytes). pub const MAX_TX_SIZE: usize = 1_000_000; /// Acceptable gas overestimation limit. @@ -1086,7 +1087,7 @@ pub struct InMemoryNode { pub(crate) snapshots: Arc>>, /// Configuration option that survives reset. #[allow(dead_code)] - pub(crate) system_contracts_options: system_contracts::Options, + pub(crate) system_contracts_options: SystemContractsOptions, pub(crate) time: TimestampManager, pub(crate) impersonation: ImpersonationManager, /// An optional handle to the observability stack @@ -1108,14 +1109,16 @@ fn contract_address_from_tx_result(execution_result: &VmExecutionResultAndLogs) impl Default for InMemoryNode { fn default() -> Self { let impersonation = ImpersonationManager::default(); + let pool = TxPool::new(impersonation.clone()); + let tx_listener = pool.add_tx_listener(); InMemoryNode::new( None, None, &TestNodeConfig::default(), TimestampManager::default(), - impersonation.clone(), - TxPool::new(impersonation), - BlockSealer::default(), + impersonation, + pool, + BlockSealer::new(BlockSealerMode::immediate(1000, tx_listener)), ) } } @@ -1159,14 +1162,16 @@ impl InMemoryNode { // TODO: Refactor InMemoryNode with a builder pattern pub fn default_fork(fork: Option) -> Self { let impersonation = ImpersonationManager::default(); + let pool = TxPool::new(impersonation.clone()); + let tx_listener = pool.add_tx_listener(); Self::new( fork, None, &Default::default(), TimestampManager::default(), - impersonation.clone(), - TxPool::new(impersonation), - BlockSealer::default(), + impersonation, + pool, + BlockSealer::new(BlockSealerMode::immediate(1000, tx_listener)), ) } @@ -2023,25 +2028,19 @@ pub fn load_last_l1_batch(storage: StoragePtr) -> Option<(u64 #[cfg(test)] mod tests { + use anvil_zksync_config::constants::{ + DEFAULT_ACCOUNT_BALANCE, DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, + DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, DEFAULT_FAIR_PUBDATA_PRICE, DEFAULT_L2_GAS_PRICE, + TEST_NODE_NETWORK_ID, + }; + use anvil_zksync_config::types::SystemContractsOptions; + use anvil_zksync_config::TestNodeConfig; use ethabi::{Token, Uint}; use std::fmt::Debug; use zksync_types::{utils::deployed_address_create, K256PrivateKey, Nonce}; use super::*; - use crate::{ - config::{ - constants::{ - DEFAULT_ACCOUNT_BALANCE, DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR, - DEFAULT_ESTIMATE_GAS_SCALE_FACTOR, DEFAULT_FAIR_PUBDATA_PRICE, - DEFAULT_L2_GAS_PRICE, TEST_NODE_NETWORK_ID, - }, - TestNodeConfig, - }, - http_fork_source::HttpForkSource, - node::InMemoryNode, - system_contracts::Options, - testing, - }; + use crate::{http_fork_source::HttpForkSource, node::InMemoryNode, testing}; fn test_vm( node: &InMemoryNode, @@ -2160,6 +2159,8 @@ mod tests { raw_storage: external_storage.inner.read().unwrap().raw_storage.clone(), }; let impersonation = ImpersonationManager::default(); + let pool = TxPool::new(impersonation.clone()); + let sealer = BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let node: InMemoryNode = InMemoryNode::new( Some(ForkDetails { fork_source: Box::new(mock_db), @@ -2181,9 +2182,9 @@ mod tests { None, &Default::default(), TimestampManager::default(), - impersonation.clone(), - TxPool::new(impersonation), - BlockSealer::default(), + impersonation, + pool, + sealer, ); let tx = testing::TransactionBuilder::new().build(); @@ -2198,17 +2199,19 @@ mod tests { #[tokio::test] async fn test_transact_returns_data_in_built_in_without_security_mode() { let impersonation = ImpersonationManager::default(); + let pool = TxPool::new(impersonation.clone()); + let sealer = BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let node = InMemoryNode::::new( None, None, &TestNodeConfig { - system_contracts_options: Options::BuiltInWithoutSecurity, + system_contracts_options: SystemContractsOptions::BuiltInWithoutSecurity, ..Default::default() }, TimestampManager::default(), - impersonation.clone(), - TxPool::new(impersonation), - BlockSealer::default(), + impersonation, + pool, + sealer, ); let private_key = K256PrivateKey::from_bytes(H256::repeat_byte(0xef)).unwrap(); diff --git a/src/node/in_memory_ext.rs b/crates/core/src/node/in_memory_ext.rs similarity index 99% rename from src/node/in_memory_ext.rs rename to crates/core/src/node/in_memory_ext.rs index fd489799..9bd9183a 100644 --- a/src/node/in_memory_ext.rs +++ b/crates/core/src/node/in_memory_ext.rs @@ -400,12 +400,14 @@ impl InMemoryNo pub fn set_immediate_sealing(&self, enable: bool) -> Result<()> { if enable { + let listener = self.pool.add_tx_listener(); self.sealer.set_mode(BlockSealerMode::immediate( self.inner .read() .map_err(|err| anyhow!("failed acquiring lock: {:?}", err))? .config .max_transactions, + listener, )) } else { self.sealer.set_mode(BlockSealerMode::Noop) @@ -627,6 +629,7 @@ mod tests { previous_states: Default::default(), }; let pool = TxPool::new(impersonation.clone()); + let sealer = BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let node = InMemoryNode:: { inner: Arc::new(RwLock::new(old_inner)), @@ -636,7 +639,7 @@ mod tests { impersonation, observability: None, pool, - sealer: BlockSealer::default(), + sealer, system_contracts: Default::default(), }; diff --git a/src/node/mod.rs b/crates/core/src/node/mod.rs similarity index 100% rename from src/node/mod.rs rename to crates/core/src/node/mod.rs diff --git a/src/node/net.rs b/crates/core/src/node/net.rs similarity index 92% rename from src/node/net.rs rename to crates/core/src/node/net.rs index db297ebb..ea7b7a03 100644 --- a/src/node/net.rs +++ b/crates/core/src/node/net.rs @@ -1,11 +1,10 @@ -use zksync_types::U256; - use crate::{ - config::constants::TEST_NODE_NETWORK_ID, fork::ForkSource, namespaces::{NetNamespaceT, Result}, node::InMemoryNode, }; +use anvil_zksync_config::constants::TEST_NODE_NETWORK_ID; +use zksync_types::U256; impl NetNamespaceT for InMemoryNode diff --git a/src/node/pool.rs b/crates/core/src/node/pool.rs similarity index 89% rename from src/node/pool.rs rename to crates/core/src/node/pool.rs index f8504e80..074adef1 100644 --- a/src/node/pool.rs +++ b/crates/core/src/node/pool.rs @@ -1,12 +1,15 @@ use crate::node::impersonate::ImpersonationManager; +use futures::channel::mpsc::{channel, Receiver, Sender}; use itertools::Itertools; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; use zksync_types::l2::L2Tx; use zksync_types::{Address, H256}; #[derive(Clone)] pub struct TxPool { inner: Arc>>, + /// Listeners for new transactions' hashes + tx_listeners: Arc>>>, pub(crate) impersonation: ImpersonationManager, } @@ -14,18 +17,25 @@ impl TxPool { pub fn new(impersonation: ImpersonationManager) -> Self { Self { inner: Arc::new(RwLock::new(Vec::new())), + tx_listeners: Arc::new(Mutex::new(Vec::new())), impersonation, } } pub fn add_tx(&self, tx: L2Tx) { let mut guard = self.inner.write().expect("TxPool lock is poisoned"); + let hash = tx.hash(); guard.push(tx); + self.notify_listeners(hash); } pub fn add_txs(&self, txs: impl IntoIterator) { let mut guard = self.inner.write().expect("TxPool lock is poisoned"); - guard.extend(txs); + for tx in txs { + let hash = tx.hash(); + guard.push(tx); + self.notify_listeners(hash); + } } /// Removes a single transaction from the pool @@ -82,6 +92,36 @@ impl TxPool { let txs = guard.drain(0..tx_count).collect(); Some(TxBatch { impersonating, txs }) } + + /// Adds a new transaction listener to the pool that gets notified about every new transaction. + pub fn add_tx_listener(&self) -> Receiver { + const TX_LISTENER_BUFFER_SIZE: usize = 2048; + let (tx, rx) = channel(TX_LISTENER_BUFFER_SIZE); + self.tx_listeners + .lock() + .expect("TxPool lock is poisoned") + .push(tx); + rx + } + + /// Notifies all listeners about the transaction. + fn notify_listeners(&self, tx_hash: H256) { + let mut tx_listeners = self.tx_listeners.lock().expect("TxPool lock is poisoned"); + tx_listeners.retain_mut(|listener| match listener.try_send(tx_hash) { + Ok(()) => true, + Err(e) => { + if e.is_full() { + tracing::warn!( + %tx_hash, + "Failed to send transaction notification because channel is full", + ); + true + } else { + false + } + } + }); + } } // Test utilities diff --git a/src/node/sealer.rs b/crates/core/src/node/sealer.rs similarity index 86% rename from src/node/sealer.rs rename to crates/core/src/node/sealer.rs index 0d536087..9d3e379f 100644 --- a/src/node/sealer.rs +++ b/crates/core/src/node/sealer.rs @@ -1,9 +1,14 @@ use crate::node::pool::{TxBatch, TxPool}; +use futures::channel::mpsc::Receiver; +use futures::stream::{Fuse, StreamExt}; use futures::task::AtomicWaker; +use futures::Stream; +use std::pin::Pin; use std::sync::{Arc, RwLock}; use std::task::{Context, Poll}; use std::time::Duration; use tokio::time::{Interval, MissedTickBehavior}; +use zksync_types::H256; #[derive(Clone, Debug)] pub struct BlockSealer { @@ -13,12 +18,6 @@ pub struct BlockSealer { waker: Arc, } -impl Default for BlockSealer { - fn default() -> Self { - BlockSealer::new(BlockSealerMode::immediate(1000)) - } -} - impl BlockSealer { pub fn new(mode: BlockSealerMode) -> Self { Self { @@ -45,7 +44,7 @@ impl BlockSealer { let mut mode = self.mode.write().expect("BlockSealer lock is poisoned"); match &mut *mode { BlockSealerMode::Noop => Poll::Pending, - BlockSealerMode::Immediate(immediate) => immediate.poll(pool), + BlockSealerMode::Immediate(immediate) => immediate.poll(pool, cx), BlockSealerMode::FixedTime(fixed) => fixed.poll(pool, cx), } } @@ -67,8 +66,11 @@ impl BlockSealerMode { Self::Noop } - pub fn immediate(max_transactions: usize) -> Self { - Self::Immediate(ImmediateBlockSealer { max_transactions }) + pub fn immediate(max_transactions: usize, listener: Receiver) -> Self { + Self::Immediate(ImmediateBlockSealer { + max_transactions, + rx: listener.fuse(), + }) } pub fn fixed_time(max_transactions: usize, block_time: Duration) -> Self { @@ -78,7 +80,7 @@ impl BlockSealerMode { pub fn poll(&mut self, pool: &TxPool, cx: &mut Context<'_>) -> Poll { match self { BlockSealerMode::Noop => Poll::Pending, - BlockSealerMode::Immediate(immediate) => immediate.poll(pool), + BlockSealerMode::Immediate(immediate) => immediate.poll(pool, cx), BlockSealerMode::FixedTime(fixed) => fixed.poll(pool, cx), } } @@ -88,15 +90,28 @@ impl BlockSealerMode { pub struct ImmediateBlockSealer { /// Maximum number of transactions to include in a block. max_transactions: usize, + /// Receives hashes of new transactions. + rx: Fuse>, } impl ImmediateBlockSealer { - pub fn poll(&mut self, pool: &TxPool) -> Poll { - let Some(tx_batch) = pool.take_uniform(self.max_transactions) else { - return Poll::Pending; - }; - - Poll::Ready(tx_batch) + pub fn poll(&mut self, pool: &TxPool, cx: &mut Context<'_>) -> Poll { + match pool.take_uniform(self.max_transactions) { + Some(tx_batch) => Poll::Ready(tx_batch), + None => { + let mut has_new_txs = false; + // Yield until new transactions are available in the pool + while let Poll::Ready(Some(_hash)) = Pin::new(&mut self.rx).poll_next(cx) { + has_new_txs = true; + } + + if has_new_txs { + self.poll(pool, cx) + } else { + Poll::Pending + } + } + } } } @@ -161,7 +176,8 @@ mod tests { #[test] fn immediate_empty() { let pool = TxPool::new(ImpersonationManager::default()); - let mut block_sealer = BlockSealer::new(BlockSealerMode::immediate(1000)); + let mut block_sealer = + BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let waker = &WAKER_NOOP; let mut cx = Context::from_waker(waker); @@ -171,7 +187,8 @@ mod tests { #[test] fn immediate_one_tx() { let pool = TxPool::new(ImpersonationManager::default()); - let mut block_sealer = BlockSealer::new(BlockSealerMode::immediate(1000)); + let mut block_sealer = + BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let waker = &WAKER_NOOP; let mut cx = Context::from_waker(waker); @@ -190,7 +207,8 @@ mod tests { #[test] fn immediate_several_txs() { let pool = TxPool::new(ImpersonationManager::default()); - let mut block_sealer = BlockSealer::new(BlockSealerMode::immediate(1000)); + let mut block_sealer = + BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let waker = &WAKER_NOOP; let mut cx = Context::from_waker(waker); @@ -209,7 +227,8 @@ mod tests { #[test] fn immediate_respect_max_txs() { let pool = TxPool::new(ImpersonationManager::default()); - let mut block_sealer = BlockSealer::new(BlockSealerMode::immediate(3)); + let mut block_sealer = + BlockSealer::new(BlockSealerMode::immediate(3, pool.add_tx_listener())); let waker = &WAKER_NOOP; let mut cx = Context::from_waker(waker); @@ -229,7 +248,8 @@ mod tests { #[test] fn immediate_gradual_txs() { let pool = TxPool::new(ImpersonationManager::default()); - let mut block_sealer = BlockSealer::new(BlockSealerMode::immediate(1000)); + let mut block_sealer = + BlockSealer::new(BlockSealerMode::immediate(1000, pool.add_tx_listener())); let waker = &WAKER_NOOP; let mut cx = Context::from_waker(waker); diff --git a/src/node/state.rs b/crates/core/src/node/state.rs similarity index 100% rename from src/node/state.rs rename to crates/core/src/node/state.rs diff --git a/src/node/storage_logs.rs b/crates/core/src/node/storage_logs.rs similarity index 98% rename from src/node/storage_logs.rs rename to crates/core/src/node/storage_logs.rs index cda90032..6b80aed6 100644 --- a/src/node/storage_logs.rs +++ b/crates/core/src/node/storage_logs.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::formatter::{self, PubdataBytesInfo}; -use crate::config::show_details::ShowStorageLogs; +use anvil_zksync_config::types::ShowStorageLogs; use zksync_multivm::interface::VmExecutionResultAndLogs; use zksync_types::{ utils::storage_key_for_eth_balance, diff --git a/src/node/time.rs b/crates/core/src/node/time.rs similarity index 100% rename from src/node/time.rs rename to crates/core/src/node/time.rs diff --git a/src/node/web3.rs b/crates/core/src/node/web3.rs similarity index 100% rename from src/node/web3.rs rename to crates/core/src/node/web3.rs diff --git a/src/node/zks.rs b/crates/core/src/node/zks.rs similarity index 99% rename from src/node/zks.rs rename to crates/core/src/node/zks.rs index 11b0de22..281cf1d2 100644 --- a/src/node/zks.rs +++ b/crates/core/src/node/zks.rs @@ -576,6 +576,8 @@ impl ZksNamespa mod tests { use std::str::FromStr; + use anvil_zksync_config::constants::TEST_NODE_NETWORK_ID; + use anvil_zksync_config::types::CacheConfig; use zksync_types::{ api::{self, Block, TransactionReceipt, TransactionVariant}, transaction_request::CallRequest, @@ -585,7 +587,6 @@ mod tests { use super::*; use crate::{ - config::{cache::CacheConfig, constants::TEST_NODE_NETWORK_ID}, fork::ForkDetails, http_fork_source::HttpForkSource, node::InMemoryNode, diff --git a/src/observability.rs b/crates/core/src/observability.rs similarity index 81% rename from src/observability.rs rename to crates/core/src/observability.rs index bd7d4f87..6b0d2c64 100644 --- a/src/observability.rs +++ b/crates/core/src/observability.rs @@ -1,48 +1,10 @@ -use clap::ValueEnum; -use core::fmt; -use serde::{Deserialize, Serialize}; +use anvil_zksync_config::types::LogLevel; use std::sync::{Arc, RwLock}; use std::{fs::File, sync::Mutex}; use tracing_subscriber::{ filter::LevelFilter, layer::SubscriberExt, reload, util::SubscriberInitExt, EnvFilter, Registry, }; -/// Log filter level for the node. -#[derive(Default, Debug, Copy, Clone, ValueEnum, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum LogLevel { - Trace, - Debug, - #[default] - Info, - Warn, - Error, -} - -impl fmt::Display for LogLevel { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - LogLevel::Trace => f.pad("TRACE"), - LogLevel::Debug => f.pad("DEBUG"), - LogLevel::Info => f.pad("INFO"), - LogLevel::Warn => f.pad("WARN"), - LogLevel::Error => f.pad("ERROR"), - } - } -} - -impl From for LevelFilter { - fn from(value: LogLevel) -> Self { - match value { - LogLevel::Trace => LevelFilter::TRACE, - LogLevel::Debug => LevelFilter::DEBUG, - LogLevel::Info => LevelFilter::INFO, - LogLevel::Warn => LevelFilter::WARN, - LogLevel::Error => LevelFilter::ERROR, - } - } -} - /// A sharable reference to the observability stack. #[derive(Debug, Clone)] pub struct Observability { diff --git a/src/resolver.rs b/crates/core/src/resolver.rs similarity index 99% rename from src/resolver.rs rename to crates/core/src/resolver.rs index fc98c634..6b2d7ebd 100644 --- a/src/resolver.rs +++ b/crates/core/src/resolver.rs @@ -1,4 +1,6 @@ //! Resolving the selectors (both method & event) with external database. +use crate::cache::Cache; +use anvil_zksync_config::types::CacheConfig; use lazy_static::lazy_static; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use serde::Deserialize; @@ -14,8 +16,6 @@ use std::{ use tokio::sync::RwLock; use tracing::warn; -use crate::{cache::Cache, config::cache::CacheConfig}; - static SELECTOR_DATABASE_URL: &str = "https://api.openchain.xyz/signature-database/v1/lookup"; /// The standard request timeout for API requests diff --git a/src/system_contracts.rs b/crates/core/src/system_contracts.rs similarity index 75% rename from src/system_contracts.rs rename to crates/core/src/system_contracts.rs index 8d7264d2..d7c9b0cb 100644 --- a/src/system_contracts.rs +++ b/crates/core/src/system_contracts.rs @@ -1,5 +1,5 @@ -use clap::ValueEnum; -use serde::Deserialize; +use crate::deps::system_contracts::bytecode_from_slice; +use anvil_zksync_config::types::SystemContractsOptions; use zksync_contracts::{ read_bootloader_code, read_sys_contract_bytecode, BaseSystemContracts, BaseSystemContractsHashes, ContractLanguage, SystemContractCode, @@ -7,19 +7,6 @@ use zksync_contracts::{ use zksync_multivm::interface::TxExecutionMode; use zksync_utils::{bytecode::hash_bytecode, bytes_to_be_words}; -use crate::deps::system_contracts::bytecode_from_slice; - -#[derive(Deserialize, Default, Debug, Copy, Clone, PartialEq, ValueEnum)] -pub enum Options { - // Use the compiled-in contracts - #[default] - BuiltIn, - // Load the contracts bytecode at runtime from ZKSYNC_HOME - Local, - // Don't verify the signatures and return transaction result on calls (used only for testing - for example Forge). - BuiltInWithoutSecurity, -} - /// Holds the system contracts (and bootloader) that are used by the in-memory node. #[derive(Debug, Clone)] pub struct SystemContracts { @@ -33,14 +20,14 @@ pub struct SystemContracts { impl Default for SystemContracts { /// Creates SystemContracts that use compiled-in contracts. fn default() -> Self { - SystemContracts::from_options(&Options::BuiltIn, false) + SystemContracts::from_options(&SystemContractsOptions::BuiltIn, false) } } impl SystemContracts { /// Creates the SystemContracts that use the complied contracts from ZKSYNC_HOME path. /// These are loaded at binary runtime. - pub fn from_options(options: &Options, use_evm_emulator: bool) -> Self { + pub fn from_options(options: &SystemContractsOptions, use_evm_emulator: bool) -> Self { Self { baseline_contracts: baseline_contracts(options, use_evm_emulator), playground_contracts: playground(options, use_evm_emulator), @@ -94,7 +81,7 @@ impl SystemContracts { /// Creates BaseSystemContracts object with a specific bootloader. fn bsc_load_with_bootloader( bootloader_bytecode: Vec, - options: &Options, + options: &SystemContractsOptions, use_evm_emulator: bool, ) -> BaseSystemContracts { let hash = hash_bytecode(&bootloader_bytecode); @@ -105,12 +92,14 @@ fn bsc_load_with_bootloader( }; let aa_bytecode = match options { - Options::BuiltIn => bytecode_from_slice( + SystemContractsOptions::BuiltIn => bytecode_from_slice( "DefaultAccount", include_bytes!("deps/contracts/DefaultAccount.json"), ), - Options::Local => read_sys_contract_bytecode("", "DefaultAccount", ContractLanguage::Sol), - Options::BuiltInWithoutSecurity => bytecode_from_slice( + SystemContractsOptions::Local => { + read_sys_contract_bytecode("", "DefaultAccount", ContractLanguage::Sol) + } + SystemContractsOptions::BuiltInWithoutSecurity => bytecode_from_slice( "DefaultAccountNoSecurity", include_bytes!("deps/contracts/DefaultAccountNoSecurity.json"), ), @@ -124,8 +113,10 @@ fn bsc_load_with_bootloader( let evm_emulator = if use_evm_emulator { let evm_emulator_bytecode = match options { - Options::Local => read_sys_contract_bytecode("", "EvmEmulator", ContractLanguage::Yul), - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::Local => { + read_sys_contract_bytecode("", "EvmEmulator", ContractLanguage::Yul) + } + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { panic!("no built-in EVM emulator yet") } }; @@ -146,12 +137,12 @@ fn bsc_load_with_bootloader( } /// BaseSystemContracts with playground bootloader - used for handling 'eth_calls'. -fn playground(options: &Options, use_evm_emulator: bool) -> BaseSystemContracts { +fn playground(options: &SystemContractsOptions, use_evm_emulator: bool) -> BaseSystemContracts { let bootloader_bytecode = match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { include_bytes!("deps/contracts/playground_batch.yul.zbin").to_vec() } - Options::Local => read_bootloader_code("playground_batch"), + SystemContractsOptions::Local => read_bootloader_code("playground_batch"), }; bsc_load_with_bootloader(bootloader_bytecode, options, use_evm_emulator) @@ -163,52 +154,58 @@ fn playground(options: &Options, use_evm_emulator: bool) -> BaseSystemContracts /// /// A `BaseSystemContracts` struct containing the system contracts used for handling 'eth_estimateGas'. /// It sets ENSURE_RETURNED_MAGIC to 0 and BOOTLOADER_TYPE to 'playground_block' -fn fee_estimate_contracts(options: &Options, use_evm_emulator: bool) -> BaseSystemContracts { +fn fee_estimate_contracts( + options: &SystemContractsOptions, + use_evm_emulator: bool, +) -> BaseSystemContracts { let bootloader_bytecode = match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { include_bytes!("deps/contracts/fee_estimate.yul.zbin").to_vec() } - Options::Local => read_bootloader_code("fee_estimate"), + SystemContractsOptions::Local => read_bootloader_code("fee_estimate"), }; bsc_load_with_bootloader(bootloader_bytecode, options, use_evm_emulator) } fn fee_estimate_impersonating_contracts( - options: &Options, + options: &SystemContractsOptions, use_evm_emulator: bool, ) -> BaseSystemContracts { let bootloader_bytecode = match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { include_bytes!("deps/contracts/fee_estimate_impersonating.yul.zbin").to_vec() } // Account impersonating is not supported with the local contracts - Options::Local => read_bootloader_code("fee_estimate"), + SystemContractsOptions::Local => read_bootloader_code("fee_estimate"), }; bsc_load_with_bootloader(bootloader_bytecode, options, use_evm_emulator) } -fn baseline_contracts(options: &Options, use_evm_emulator: bool) -> BaseSystemContracts { +fn baseline_contracts( + options: &SystemContractsOptions, + use_evm_emulator: bool, +) -> BaseSystemContracts { let bootloader_bytecode = match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { include_bytes!("deps/contracts/proved_batch.yul.zbin").to_vec() } - Options::Local => read_bootloader_code("proved_batch"), + SystemContractsOptions::Local => read_bootloader_code("proved_batch"), }; bsc_load_with_bootloader(bootloader_bytecode, options, use_evm_emulator) } fn baseline_impersonating_contracts( - options: &Options, + options: &SystemContractsOptions, use_evm_emulator: bool, ) -> BaseSystemContracts { let bootloader_bytecode = match options { - Options::BuiltIn | Options::BuiltInWithoutSecurity => { + SystemContractsOptions::BuiltIn | SystemContractsOptions::BuiltInWithoutSecurity => { include_bytes!("deps/contracts/proved_batch_impersonating.yul.zbin").to_vec() } // Account impersonating is not supported with the local contracts - Options::Local => read_bootloader_code("proved_batch"), + SystemContractsOptions::Local => read_bootloader_code("proved_batch"), }; bsc_load_with_bootloader(bootloader_bytecode, options, use_evm_emulator) } diff --git a/src/testing.rs b/crates/core/src/testing.rs similarity index 100% rename from src/testing.rs rename to crates/core/src/testing.rs diff --git a/src/utils.rs b/crates/core/src/utils.rs similarity index 90% rename from src/utils.rs rename to crates/core/src/utils.rs index 9592ef10..23b7438e 100644 --- a/src/utils.rs +++ b/crates/core/src/utils.rs @@ -1,11 +1,9 @@ -use crate::config::Genesis; use anyhow::Context; use chrono::{DateTime, Utc}; use futures::Future; use jsonrpc_core::{Error, ErrorCode}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; -use std::fs; use std::{convert::TryInto, fmt, pin::Pin}; use zksync_multivm::interface::{Call, CallType, ExecutionResult, VmExecutionResultAndLogs}; use zksync_types::{ @@ -30,13 +28,6 @@ where { } -/// Parses the genesis file from the given path. -pub fn parse_genesis_file(path: &str) -> Result { - let file_content = - fs::read_to_string(path).map_err(|err| format!("Failed to read file: {err}"))?; - serde_json::from_str(&file_content).map_err(|err| format!("Failed to parse JSON: {err}")) -} - /// Takes long integers and returns them in human friendly format with "_". /// For example: 12_334_093 pub fn to_human_size(input: U256) -> String { @@ -268,28 +259,6 @@ pub fn h256_to_u64(value: H256) -> u64 { u64::from_be_bytes(be_u64_bytes) } -// TODO: look to remove in favour of alloy-primitives utils -/// Formats a `U256` value as Ether without capping decimal points. -pub fn format_eth(value: U256) -> String { - let wei_per_eth = U256::from(10).pow(U256::from(18)); - let whole_eth = value / wei_per_eth; - let remainder_wei = value % wei_per_eth; - let fractional_eth = remainder_wei.as_u128() as f64 / 1e18; - - format!("{} ETH", whole_eth.as_u128() as f64 + fractional_eth) -} -// TODO: look to remove in favour of alloy-primitives utils -/// Formats a `U256` value as Gwei without capping decimal points. -pub fn format_gwei(value: U256) -> String { - let gwei_value = value / U256::exp10(9); - let fractional = value % U256::exp10(9); - - let fractional_part = fractional.as_u128() as f64 / 1e9; - let full_gwei = gwei_value.as_u128() as f64 + fractional_part; - - format!("{:.8} gwei", full_gwei) -} - /// Helper type to be able to parse both `u64` and `U256` depending on the user input #[derive(Copy, Clone, Serialize, Deserialize)] #[serde(untagged)]