@nomicfoundation/edr 0.12.0-next.31 → 0.12.0-next.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/coverage.sol +38 -0
  2. package/dist/src/ts/coverage.d.ts +6 -0
  3. package/dist/src/ts/coverage.d.ts.map +1 -0
  4. package/dist/src/ts/coverage.js +51 -0
  5. package/dist/src/ts/coverage.js.map +1 -0
  6. package/index.d.ts +82 -14
  7. package/index.js +2 -1
  8. package/package.json +11 -10
  9. package/src/account.rs +0 -124
  10. package/src/block.rs +0 -28
  11. package/src/call_override.rs +0 -116
  12. package/src/cast.rs +0 -165
  13. package/src/chains/generic.rs +0 -59
  14. package/src/chains/l1.rs +0 -275
  15. package/src/chains/op.rs +0 -451
  16. package/src/chains.rs +0 -7
  17. package/src/config.rs +0 -722
  18. package/src/context.rs +0 -447
  19. package/src/contract_decoder.rs +0 -60
  20. package/src/debug_trace.rs +0 -40
  21. package/src/gas_report.rs +0 -100
  22. package/src/instrument.rs +0 -115
  23. package/src/lib.rs +0 -50
  24. package/src/log.rs +0 -28
  25. package/src/logger.rs +0 -120
  26. package/src/mock/time.rs +0 -134
  27. package/src/mock.rs +0 -65
  28. package/src/precompile.rs +0 -50
  29. package/src/provider/factory.rs +0 -22
  30. package/src/provider/response.rs +0 -75
  31. package/src/provider.rs +0 -162
  32. package/src/result.rs +0 -216
  33. package/src/scenarios.rs +0 -53
  34. package/src/serde.rs +0 -57
  35. package/src/solidity_tests/artifact.rs +0 -184
  36. package/src/solidity_tests/cheatcode_errors.rs +0 -37
  37. package/src/solidity_tests/config.rs +0 -1009
  38. package/src/solidity_tests/factory.rs +0 -22
  39. package/src/solidity_tests/l1.rs +0 -72
  40. package/src/solidity_tests/op.rs +0 -72
  41. package/src/solidity_tests/runner.rs +0 -54
  42. package/src/solidity_tests/test_results.rs +0 -799
  43. package/src/solidity_tests.rs +0 -57
  44. package/src/subscription.rs +0 -32
  45. package/src/trace/debug.rs +0 -61
  46. package/src/trace/exit.rs +0 -89
  47. package/src/trace/library_utils.rs +0 -11
  48. package/src/trace/model.rs +0 -59
  49. package/src/trace/return_data.rs +0 -96
  50. package/src/trace/solidity_stack_trace.rs +0 -913
  51. package/src/trace.rs +0 -192
  52. package/src/ts/solidity_tests.ts +0 -46
  53. package/src/withdrawal.rs +0 -49
package/coverage.sol ADDED
@@ -0,0 +1,38 @@
1
+ // SPDX-License-Identifier: MIT
2
+ pragma solidity >=0.4.22 <0.9.0;
3
+
4
+ library __NomicFoundationCoverage {
5
+ address constant COVERAGE_ADDRESS =
6
+ 0xc0bEc0BEc0BeC0bEC0beC0bEC0bEC0beC0beC0BE;
7
+
8
+ function _sendHitImplementation(uint256 coverageId) private view {
9
+ address coverageAddress = COVERAGE_ADDRESS;
10
+ /// @solidity memory-safe-assembly
11
+ assembly {
12
+ let ptr := mload(0x40) // Get free memory pointer
13
+ mstore(ptr, coverageId) // Store coverageId at free memory
14
+ pop(
15
+ staticcall(
16
+ gas(),
17
+ coverageAddress,
18
+ ptr,
19
+ 32, // Size of uint256 is 32 bytes
20
+ 0,
21
+ 0
22
+ )
23
+ )
24
+ }
25
+ }
26
+
27
+ function _castToPure(
28
+ function(uint256) internal view fnIn
29
+ ) private pure returns (function(uint256) pure fnOut) {
30
+ assembly {
31
+ fnOut := fnIn
32
+ }
33
+ }
34
+
35
+ function sendHit(uint256 coverageId) internal pure {
36
+ _castToPure(_sendHitImplementation)(coverageId);
37
+ }
38
+ }
@@ -0,0 +1,6 @@
1
+ export interface CoverageLib {
2
+ content: string;
3
+ filename: string;
4
+ }
5
+ export declare function getCoverageLibrary(): CoverageLib;
6
+ //# sourceMappingURL=coverage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coverage.d.ts","sourceRoot":"","sources":["../../../src/ts/coverage.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,kBAAkB,IAAI,WAAW,CAYhD"}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.getCoverageLibrary = getCoverageLibrary;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ const edr_1 = require("@nomicfoundation/edr");
40
+ function getCoverageLibrary() {
41
+ const packageRoot = path.dirname(require.resolve("@nomicfoundation/edr"));
42
+ const sourcePath = path.join(packageRoot, "coverage.sol");
43
+ if (!fs.existsSync(sourcePath)) {
44
+ throw new Error(`Coverage library file not found at ${sourcePath}. It should be bundled with @nomicfoundation/edr.`);
45
+ }
46
+ return {
47
+ content: fs.readFileSync(sourcePath, "utf-8"),
48
+ filename: edr_1.COVERAGE_LIBRARY_FILE_NAME,
49
+ };
50
+ }
51
+ //# sourceMappingURL=coverage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coverage.js","sourceRoot":"","sources":["../../../src/ts/coverage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,gDAYC;AAtBD,uCAAyB;AACzB,2CAA6B;AAE7B,8CAAkE;AAOlE,SAAgB,kBAAkB;IAChC,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,sBAAsB,CAAC,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;IAC1D,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CACb,sCAAsC,UAAU,mDAAmD,CACpG,CAAC;IACJ,CAAC;IACD,OAAO;QACL,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC;QAC7C,QAAQ,EAAE,gCAA0B;KACrC,CAAC;AACJ,CAAC"}
package/index.d.ts CHANGED
@@ -264,9 +264,29 @@ export interface IntervalRange {
264
264
  /** Configuration for the provider's miner. */
265
265
  export interface MiningConfig {
266
266
  autoMine: boolean
267
+ /**
268
+ * The block gas limit to use for mining a block.
269
+ *
270
+ * When not set, enforcement of the block gas limit is disabled in the mem
271
+ * pool, miner, and REVM.
272
+ */
273
+ blockGasLimit?: bigint
267
274
  interval?: bigint | IntervalRange
268
275
  memPool: MemPoolConfig
269
276
  }
277
+ /** Configuration for a locally mined blockchain. */
278
+ export interface LocalConfig {
279
+ /**
280
+ * The blob gas used for the genesis block, introduced in [EIP-4844].
281
+ *
282
+ * [EIP-4844]: https://eips.ethereum.org/EIPS/eip-4844
283
+ */
284
+ genesisBlobGas?: BlobGas
285
+ /** The block gas limit of the genesis block. */
286
+ genesisBlockGasLimit: bigint
287
+ /** The date, in seconds since the Unix epoch, of the genesis block. */
288
+ genesisBlockTime?: bigint
289
+ }
270
290
  /** Configuration for runtime observability. */
271
291
  export interface ObservabilityConfig {
272
292
  /** If present, configures runtime observability to collect code coverage. */
@@ -302,17 +322,15 @@ export interface ProviderConfig {
302
322
  * will be used.
303
323
  */
304
324
  baseFeeConfig?: Array<BaseFeeParamActivation>
305
- /** The gas limit of each block */
306
- blockGasLimit: bigint
307
325
  /** The chain ID of the blockchain */
308
326
  chainId: bigint
309
327
  /** The address of the coinbase */
310
328
  coinbase: Uint8Array
311
329
  /**
312
- * The configuration for forking a blockchain. If not provided, a local
313
- * blockchain will be created
330
+ * The default transaction gas limit to use for RPC call and transaction
331
+ * requests that do not specify a `gas` value.
314
332
  */
315
- fork?: ForkConfig
333
+ defaultTransactionGasLimit: bigint
316
334
  /** The genesis state of the blockchain */
317
335
  genesisState: Array<AccountOverride>
318
336
  /** The hardfork of the blockchain */
@@ -322,10 +340,6 @@ export interface ProviderConfig {
322
340
  * transactions and later
323
341
  */
324
342
  initialBaseFeePerGas?: bigint
325
- /** The initial blob gas of the blockchain. Required for EIP-4844 */
326
- initialBlobGas?: BlobGas
327
- /** The initial date of the blockchain, in seconds since the Unix epoch */
328
- initialDate?: bigint
329
343
  /**
330
344
  * The initial parent beacon block root of the blockchain. Required for
331
345
  * EIP-4788
@@ -335,6 +349,8 @@ export interface ProviderConfig {
335
349
  minGasPrice: bigint
336
350
  /** The configuration for the miner */
337
351
  mining: MiningConfig
352
+ /** The network configuration for the provider. */
353
+ network: ForkConfig | LocalConfig
338
354
  /** The network ID of the blockchain */
339
355
  networkId: bigint
340
356
  /** The configuration for the provider's observability */
@@ -346,11 +362,17 @@ export interface ProviderConfig {
346
362
  /**
347
363
  * Transaction gas cap, introduced in [EIP-7825].
348
364
  *
349
- * When not set, will default to value defined by the used hardfork
365
+ * Integer values should be larger than zero.
366
+ *
367
+ * When `false`, enforcement of the transaction gas cap is disabled and
368
+ * transactions with any `gas` value are accepted by the mempool and
369
+ * executed without REVM's transaction gas cap check.
370
+ *
371
+ * When not set, a hardfork-specific default value will be used.
350
372
  *
351
373
  * [EIP-7825]: https://eips.ethereum.org/EIPS/eip-7825
352
374
  */
353
- transactionGasCap?: bigint
375
+ transactionGasCap?: bigint | false
354
376
  }
355
377
  /** Tracing config for Solidity stack trace generation. */
356
378
  export interface TracingConfigWithBuffers {
@@ -460,11 +482,13 @@ export interface InstrumentationMetadata {
460
482
  */
461
483
  readonly endUtf16: number
462
484
  }
485
+ /** The instrumentation coverage library file name. */
486
+ export const COVERAGE_LIBRARY_FILE_NAME: string
463
487
  /**
464
488
  * Adds per-statement coverage instrumentation to the given Solidity source
465
489
  * code.
466
490
  */
467
- export declare function addStatementCoverageInstrumentation(sourceCode: string, sourceId: string, solidityVersion: string, coverageLibraryPath: string): InstrumentationResult
491
+ export declare function addStatementCoverageInstrumentation(sourceCode: string, sourceId: string, solidityVersion: string): InstrumentationResult
468
492
  /** Retrieves the latest version of `Solidity` supported for instrumentation. */
469
493
  export declare function latestSupportedSolidityVersion(): string
470
494
  /** Ethereum execution log. */
@@ -718,10 +742,20 @@ export interface SolidityTestRunnerConfigArgs {
718
742
  */
719
743
  disableBlockGasLimit?: boolean
720
744
  /**
721
- * Whether to enable the EIP-7825 (Osaka) transaction gas limit cap.
745
+ * Transaction gas cap, introduced in [EIP-7825].
746
+ *
747
+ * When not set, defaults to the value defined by the used hardfork.
748
+ *
749
+ * [EIP-7825]: https://eips.ethereum.org/EIPS/eip-7825
750
+ */
751
+ transactionGasCap?: bigint
752
+ /**
753
+ * Whether to disable the [EIP-7825] transaction gas cap.
722
754
  * Defaults to false.
755
+ *
756
+ * [EIP-7825]: https://eips.ethereum.org/EIPS/eip-7825
723
757
  */
724
- enableTxGasLimitCap?: boolean
758
+ disableTransactionGasCap?: boolean
725
759
  /**
726
760
  * The memory limit of the EVM in bytes.
727
761
  * Defaults to `33_554_432` (2^25 = 32MiB).
@@ -795,6 +829,40 @@ export interface SolidityTestRunnerConfigArgs {
795
829
  * Defaults to none.
796
830
  */
797
831
  testFunctionOverrides?: Array<TestFunctionOverride>
832
+ /**
833
+ * A list of EIP-712 canonical type definitions that can be referenced by
834
+ * type name in the `eip712HashType` and `eip712HashStruct` cheatcodes.
835
+ *
836
+ * Each entry is an independent, self-contained type definition. A
837
+ * definition that references nested struct types must inline those
838
+ * struct definitions, per the EIP-712 `encodeType` spec.
839
+ *
840
+ * Only the primary (leftmost) type of each entry is registered by name.
841
+ * Nested struct types referenced inside an entry are *not* registered
842
+ * under their own names. To look up a nested struct by name from a
843
+ * cheatcode, add it as a separate top-level entry whose primary type
844
+ * is the nested struct.
845
+ *
846
+ * The type of a struct is encoded as:
847
+ *
848
+ * `name ‖ "(" ‖ member₁ ‖ "," ‖ member₂ ‖ "," ‖ … ‖ memberₙ ")"`
849
+ *
850
+ * where each member is written as `type ‖ " " ‖ name`.
851
+ *
852
+ * Entries that fail to parse cause a startup error listing every bad
853
+ * entry.
854
+ *
855
+ * Example — to make both `Mail` and `Person` reachable by name:
856
+ *
857
+ * ```text
858
+ * "Mail(Person from,Person to,string contents)Person(address wallet,string name)"
859
+ * "Person(address wallet,string name)"
860
+ * ```
861
+ *
862
+ * With *only* the first entry, `vm.eip712HashType("Mail")` works but
863
+ * `vm.eip712HashType("Person")` fails with an unknown-type error.
864
+ */
865
+ eip712CanonicalTypes?: Array<string>
798
866
  }
799
867
  /** Fuzz testing configuration */
800
868
  export interface FuzzConfigArgs {
package/index.js CHANGED
@@ -310,7 +310,7 @@ if (!nativeBinding) {
310
310
  throw new Error(`Failed to load native binding`)
311
311
  }
312
312
 
313
- const { GENERIC_CHAIN_TYPE, genericChainProviderFactory, L1_CHAIN_TYPE, l1GenesisState, l1ProviderFactory, SpecId, l1HardforkFromString, l1HardforkToString, l1HardforkLatest, FRONTIER, FRONTIER_THAWING, HOMESTEAD, DAO_FORK, TANGERINE, SPURIOUS_DRAGON, BYZANTIUM, CONSTANTINOPLE, PETERSBURG, ISTANBUL, MUIR_GLACIER, BERLIN, LONDON, ARROW_GLACIER, GRAY_GLACIER, MERGE, SHANGHAI, CANCUN, PRAGUE, OSAKA, OpHardfork, opHardforkFromString, opHardforkToString, opLatestHardfork, OP_CHAIN_TYPE, opGenesisState, opProviderFactory, BEDROCK, REGOLITH, CANYON, ECOTONE, FJORD, GRANITE, HOLOCENE, ISTHMUS, MineOrdering, EdrContext, ContractDecoder, GasReportExecutionStatus, addStatementCoverageInstrumentation, latestSupportedSolidityVersion, Precompile, precompileP256Verify, ProviderFactory, Response, Provider, SuccessReason, ExceptionalHalt, CheatcodeErrorCode, CachedChains, CachedEndpoints, FsAccessPermission, CollectStackTraces, IncludeTraces, SolidityTestRunnerFactory, l1SolidityTestRunnerFactory, opSolidityTestRunnerFactory, SuiteResult, TestResult, TestStatus, CallKind, LogKind, linkHexStringBytecode, printStackTrace, Exit, ExitCode, BytecodeWrapper, ContractFunctionType, ReturnData, StackTraceEntryType, stackTraceEntryTypeToString, FALLBACK_FUNCTION_NAME, RECEIVE_FUNCTION_NAME, CONSTRUCTOR_FUNCTION_NAME, UNRECOGNIZED_FUNCTION_NAME, UNKNOWN_FUNCTION_NAME, PRECOMPILE_FUNCTION_NAME, UNRECOGNIZED_CONTRACT_NAME, RawTrace } = nativeBinding
313
+ const { GENERIC_CHAIN_TYPE, genericChainProviderFactory, L1_CHAIN_TYPE, l1GenesisState, l1ProviderFactory, SpecId, l1HardforkFromString, l1HardforkToString, l1HardforkLatest, FRONTIER, FRONTIER_THAWING, HOMESTEAD, DAO_FORK, TANGERINE, SPURIOUS_DRAGON, BYZANTIUM, CONSTANTINOPLE, PETERSBURG, ISTANBUL, MUIR_GLACIER, BERLIN, LONDON, ARROW_GLACIER, GRAY_GLACIER, MERGE, SHANGHAI, CANCUN, PRAGUE, OSAKA, OpHardfork, opHardforkFromString, opHardforkToString, opLatestHardfork, OP_CHAIN_TYPE, opGenesisState, opProviderFactory, BEDROCK, REGOLITH, CANYON, ECOTONE, FJORD, GRANITE, HOLOCENE, ISTHMUS, MineOrdering, EdrContext, ContractDecoder, GasReportExecutionStatus, COVERAGE_LIBRARY_FILE_NAME, addStatementCoverageInstrumentation, latestSupportedSolidityVersion, Precompile, precompileP256Verify, ProviderFactory, Response, Provider, SuccessReason, ExceptionalHalt, CheatcodeErrorCode, CachedChains, CachedEndpoints, FsAccessPermission, CollectStackTraces, IncludeTraces, SolidityTestRunnerFactory, l1SolidityTestRunnerFactory, opSolidityTestRunnerFactory, SuiteResult, TestResult, TestStatus, CallKind, LogKind, linkHexStringBytecode, printStackTrace, Exit, ExitCode, BytecodeWrapper, ContractFunctionType, ReturnData, StackTraceEntryType, stackTraceEntryTypeToString, FALLBACK_FUNCTION_NAME, RECEIVE_FUNCTION_NAME, CONSTRUCTOR_FUNCTION_NAME, UNRECOGNIZED_FUNCTION_NAME, UNKNOWN_FUNCTION_NAME, PRECOMPILE_FUNCTION_NAME, UNRECOGNIZED_CONTRACT_NAME, RawTrace } = nativeBinding
314
314
 
315
315
  module.exports.GENERIC_CHAIN_TYPE = GENERIC_CHAIN_TYPE
316
316
  module.exports.genericChainProviderFactory = genericChainProviderFactory
@@ -360,6 +360,7 @@ module.exports.MineOrdering = MineOrdering
360
360
  module.exports.EdrContext = EdrContext
361
361
  module.exports.ContractDecoder = ContractDecoder
362
362
  module.exports.GasReportExecutionStatus = GasReportExecutionStatus
363
+ module.exports.COVERAGE_LIBRARY_FILE_NAME = COVERAGE_LIBRARY_FILE_NAME
363
364
  module.exports.addStatementCoverageInstrumentation = addStatementCoverageInstrumentation
364
365
  module.exports.latestSupportedSolidityVersion = latestSupportedSolidityVersion
365
366
  module.exports.Precompile = Precompile
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nomicfoundation/edr",
3
- "version": "0.12.0-next.31",
3
+ "version": "0.12.0-next.33",
4
4
  "devDependencies": {
5
5
  "@napi-rs/cli": "^2.18.4",
6
6
  "@nomicfoundation/ethereumjs-util": "^9.0.4",
@@ -31,12 +31,13 @@
31
31
  },
32
32
  "exports": {
33
33
  ".": "./index.js",
34
- "./solidity-tests": "./dist/src/ts/solidity_tests.js"
34
+ "./coverage": "./dist/src/ts/coverage.js"
35
35
  },
36
36
  "files": [
37
37
  "index.js",
38
38
  "index.d.ts",
39
- "src/"
39
+ "dist/src/",
40
+ "coverage.sol"
40
41
  ],
41
42
  "license": "MIT",
42
43
  "main": "index.js",
@@ -58,13 +59,13 @@
58
59
  "repository": "NomicFoundation/edr.git",
59
60
  "types": "index.d.ts",
60
61
  "dependencies": {
61
- "@nomicfoundation/edr-darwin-arm64": "0.12.0-next.31",
62
- "@nomicfoundation/edr-darwin-x64": "0.12.0-next.31",
63
- "@nomicfoundation/edr-linux-arm64-gnu": "0.12.0-next.31",
64
- "@nomicfoundation/edr-linux-arm64-musl": "0.12.0-next.31",
65
- "@nomicfoundation/edr-linux-x64-gnu": "0.12.0-next.31",
66
- "@nomicfoundation/edr-linux-x64-musl": "0.12.0-next.31",
67
- "@nomicfoundation/edr-win32-x64-msvc": "0.12.0-next.31"
62
+ "@nomicfoundation/edr-darwin-arm64": "0.12.0-next.33",
63
+ "@nomicfoundation/edr-darwin-x64": "0.12.0-next.33",
64
+ "@nomicfoundation/edr-linux-arm64-gnu": "0.12.0-next.33",
65
+ "@nomicfoundation/edr-linux-arm64-musl": "0.12.0-next.33",
66
+ "@nomicfoundation/edr-linux-x64-gnu": "0.12.0-next.33",
67
+ "@nomicfoundation/edr-linux-x64-musl": "0.12.0-next.33",
68
+ "@nomicfoundation/edr-win32-x64-msvc": "0.12.0-next.33"
68
69
  },
69
70
  "scripts": {
70
71
  "artifacts": "napi artifacts",
package/src/account.rs DELETED
@@ -1,124 +0,0 @@
1
- use derive_more::Debug;
2
- use edr_primitives::{hex, Address, HashMap, U256};
3
- use edr_solidity_tests::{backend::Predeploy, revm::state::AccountInfo};
4
- use edr_state_api::EvmStorageSlot;
5
- use napi::bindgen_prelude::{BigInt, Uint8Array};
6
- use napi_derive::napi;
7
-
8
- use crate::{
9
- cast::TryCast,
10
- serde::{
11
- serialize_bigint_as_struct, serialize_optional_bigint_as_struct,
12
- serialize_optional_uint8array_as_hex, serialize_uint8array_as_hex,
13
- },
14
- };
15
-
16
- /// Specification of overrides for an account and its storage.
17
- #[napi(object)]
18
- #[derive(Clone, Debug, serde::Serialize)]
19
- pub struct AccountOverride {
20
- /// The account's address
21
- #[debug("{}", hex::encode(address))]
22
- #[serde(serialize_with = "serialize_uint8array_as_hex")]
23
- pub address: Uint8Array,
24
- /// If present, the overwriting balance.
25
- #[serde(serialize_with = "serialize_optional_bigint_as_struct")]
26
- pub balance: Option<BigInt>,
27
- /// If present, the overwriting nonce.
28
- #[serde(serialize_with = "serialize_optional_bigint_as_struct")]
29
- pub nonce: Option<BigInt>,
30
- /// If present, the overwriting code.
31
- #[debug("{:?}", code.as_ref().map(hex::encode))]
32
- #[serde(serialize_with = "serialize_optional_uint8array_as_hex")]
33
- pub code: Option<Uint8Array>,
34
- /// BEWARE: This field is not supported yet. See <https://github.com/NomicFoundation/edr/issues/911>
35
- ///
36
- /// If present, the overwriting storage.
37
- pub storage: Option<Vec<StorageSlot>>,
38
- }
39
-
40
- impl TryFrom<AccountOverride> for (Address, edr_provider::AccountOverride) {
41
- type Error = napi::Error;
42
-
43
- fn try_from(value: AccountOverride) -> Result<Self, Self::Error> {
44
- let AccountOverride {
45
- address,
46
- balance,
47
- nonce,
48
- code,
49
- storage,
50
- } = value;
51
- let storage = storage
52
- .map(|storage| {
53
- storage
54
- .into_iter()
55
- .map(|StorageSlot { index, value }| {
56
- let value = value.try_cast()?;
57
- let slot = EvmStorageSlot::new(value, 0);
58
-
59
- let index: U256 = index.try_cast()?;
60
- Ok((index, slot))
61
- })
62
- .collect::<napi::Result<_>>()
63
- })
64
- .transpose()?;
65
-
66
- let account_override = edr_provider::AccountOverride {
67
- balance: balance.map(TryCast::try_cast).transpose()?,
68
- nonce: nonce.map(TryCast::try_cast).transpose()?,
69
- code: code.map(TryCast::try_cast).transpose()?,
70
- storage,
71
- };
72
-
73
- let address: Address = address.try_cast()?;
74
-
75
- Ok((address, account_override))
76
- }
77
- }
78
-
79
- impl TryFrom<AccountOverride> for Predeploy {
80
- type Error = napi::Error;
81
-
82
- fn try_from(value: AccountOverride) -> Result<Self, Self::Error> {
83
- let (address, account_override) = value.try_into()?;
84
-
85
- let storage = account_override.storage.unwrap_or_else(HashMap::default);
86
- let balance = account_override.balance.unwrap_or(U256::ZERO);
87
- let nonce = account_override.nonce.unwrap_or(0);
88
- let code = account_override.code.ok_or_else(|| {
89
- napi::Error::from_reason(format!("Predeploy with address '{address}' must have code"))
90
- })?;
91
-
92
- if code.is_empty() {
93
- return Err(napi::Error::from_reason(
94
- "Predeploy with address '{address}' must have non-empty code",
95
- ));
96
- }
97
- let code_hash = code.hash_slow();
98
-
99
- let account_info = AccountInfo {
100
- balance,
101
- nonce,
102
- code_hash,
103
- code: Some(code),
104
- };
105
-
106
- Ok(Self {
107
- address,
108
- account_info,
109
- storage,
110
- })
111
- }
112
- }
113
-
114
- /// A description of a storage slot's state.
115
- #[napi(object)]
116
- #[derive(Clone, Debug, serde::Serialize)]
117
- pub struct StorageSlot {
118
- /// The storage slot's index
119
- #[serde(serialize_with = "serialize_bigint_as_struct")]
120
- pub index: BigInt,
121
- /// The storage slot's value
122
- #[serde(serialize_with = "serialize_bigint_as_struct")]
123
- pub value: BigInt,
124
- }
package/src/block.rs DELETED
@@ -1,28 +0,0 @@
1
- use napi::bindgen_prelude::BigInt;
2
- use napi_derive::napi;
3
-
4
- use crate::cast::TryCast;
5
-
6
- /// Information about the blob gas used in a block.
7
- #[napi(object)]
8
- pub struct BlobGas {
9
- /// The total amount of blob gas consumed by the transactions within the
10
- /// block.
11
- pub gas_used: BigInt,
12
- /// The running total of blob gas consumed in excess of the target, prior to
13
- /// the block. Blocks with above-target blob gas consumption increase this
14
- /// value, blocks with below-target blob gas consumption decrease it
15
- /// (bounded at 0).
16
- pub excess_gas: BigInt,
17
- }
18
-
19
- impl TryFrom<BlobGas> for edr_block_header::BlobGas {
20
- type Error = napi::Error;
21
-
22
- fn try_from(value: BlobGas) -> Result<Self, Self::Error> {
23
- Ok(Self {
24
- gas_used: BigInt::try_cast(value.gas_used)?,
25
- excess_gas: BigInt::try_cast(value.excess_gas)?,
26
- })
27
- }
28
- }
@@ -1,116 +0,0 @@
1
- use std::sync::mpsc::channel;
2
-
3
- use edr_primitives::{Address, Bytes};
4
- use napi::{
5
- bindgen_prelude::{Promise, Uint8Array},
6
- threadsafe_function::{
7
- ErrorStrategy, ThreadSafeCallContext, ThreadsafeFunction, ThreadsafeFunctionCallMode,
8
- },
9
- tokio::runtime,
10
- Env, JsFunction, Status,
11
- };
12
- use napi_derive::napi;
13
-
14
- use crate::cast::TryCast;
15
-
16
- /// The result of executing a call override.
17
- #[napi(object)]
18
- pub struct CallOverrideResult {
19
- pub result: Uint8Array,
20
- pub should_revert: bool,
21
- }
22
-
23
- impl TryCast<Option<edr_provider::CallOverrideResult>> for Option<CallOverrideResult> {
24
- type Error = napi::Error;
25
-
26
- fn try_cast(self) -> Result<Option<edr_provider::CallOverrideResult>, Self::Error> {
27
- match self {
28
- None => Ok(None),
29
- Some(result) => Ok(Some(edr_provider::CallOverrideResult {
30
- output: Bytes::copy_from_slice(&result.result),
31
- should_revert: result.should_revert,
32
- })),
33
- }
34
- }
35
- }
36
-
37
- struct CallOverrideCall {
38
- contract_address: Address,
39
- data: Bytes,
40
- }
41
-
42
- #[derive(Clone)]
43
- pub struct CallOverrideCallback {
44
- call_override_callback_fn: ThreadsafeFunction<CallOverrideCall, ErrorStrategy::Fatal>,
45
- runtime: runtime::Handle,
46
- }
47
-
48
- impl CallOverrideCallback {
49
- pub fn new(
50
- env: &Env,
51
- call_override_callback: JsFunction,
52
- runtime: runtime::Handle,
53
- ) -> napi::Result<Self> {
54
- let mut call_override_callback_fn = call_override_callback.create_threadsafe_function(
55
- 0,
56
- |ctx: ThreadSafeCallContext<CallOverrideCall>| {
57
- let address = ctx
58
- .env
59
- .create_arraybuffer_with_data(ctx.value.contract_address.to_vec())?
60
- .into_raw();
61
-
62
- let data = ctx
63
- .env
64
- .create_arraybuffer_with_data(ctx.value.data.to_vec())?
65
- .into_raw();
66
-
67
- Ok(vec![address, data])
68
- },
69
- )?;
70
-
71
- // Maintain a weak reference to the function to avoid blocking the event loop
72
- // from exiting.
73
- call_override_callback_fn.unref(env)?;
74
-
75
- Ok(Self {
76
- call_override_callback_fn,
77
- runtime,
78
- })
79
- }
80
-
81
- pub fn call_override(
82
- &self,
83
- contract_address: Address,
84
- data: Bytes,
85
- ) -> Option<edr_provider::CallOverrideResult> {
86
- let (sender, receiver) = channel();
87
-
88
- let runtime = self.runtime.clone();
89
- let status = self.call_override_callback_fn.call_with_return_value(
90
- CallOverrideCall {
91
- contract_address,
92
- data,
93
- },
94
- ThreadsafeFunctionCallMode::Blocking,
95
- move |result: Promise<Option<CallOverrideResult>>| {
96
- runtime.spawn(async move {
97
- let result = result.await?.try_cast();
98
- sender.send(result).map_err(|_error| {
99
- napi::Error::new(
100
- Status::GenericFailure,
101
- "Failed to send result from call_override_callback",
102
- )
103
- })
104
- });
105
- Ok(())
106
- },
107
- );
108
-
109
- assert_eq!(status, Status::Ok, "Call override callback failed");
110
-
111
- receiver
112
- .recv()
113
- .unwrap()
114
- .expect("Failed call to call_override_callback")
115
- }
116
- }