diff --git a/.github/workflows/publish-check-crates.yml b/.github/workflows/publish-check-crates.yml index 116a4b2212cfc..4a6e776415330 100644 --- a/.github/workflows/publish-check-crates.yml +++ b/.github/workflows/publish-check-crates.yml @@ -21,6 +21,12 @@ jobs: steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + - name: Install Rust + run: | + RUST_VERSION=$(cat .github/env | sed -E 's/.*ci-unified:[^-]+-([^-]+).*/\1/') + rustup install $RUST_VERSION + rustup default $RUST_VERSION + - name: Rust Cache uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2 with: diff --git a/.github/workflows/publish-claim-crates.yml b/.github/workflows/publish-claim-crates.yml index 98b99f2c34f8f..0ab2ae44c8e3b 100644 --- a/.github/workflows/publish-claim-crates.yml +++ b/.github/workflows/publish-claim-crates.yml @@ -18,7 +18,7 @@ jobs: save-if: ${{ github.ref == 'refs/heads/master' }} - name: install parity-publish - run: cargo install parity-publish@0.10.4 --locked -q + run: cargo install parity-publish@0.10.6 --locked -q - name: parity-publish claim env: diff --git a/.github/workflows/release-80_publish-crates.yml b/.github/workflows/release-80_publish-crates.yml index 372a7e6dee545..85dd6d7332bd7 100644 --- a/.github/workflows/release-80_publish-crates.yml +++ b/.github/workflows/release-80_publish-crates.yml @@ -131,7 +131,7 @@ jobs: cache-on-failure: true - name: Install parity-publish - run: cargo install parity-publish@0.10.9 --locked -q + run: cargo install parity-publish@0.10.6 --locked -q - name: Run parity-publish plan run: | diff --git a/prdoc/pr_11054.prdoc b/prdoc/pr_11054.prdoc new file mode 100644 index 0000000000000..5b4143004bc8a --- /dev/null +++ b/prdoc/pr_11054.prdoc @@ -0,0 +1,22 @@ +title: 'pallet-revive: minor cleanups and fixes' +doc: +- audience: Runtime Dev + description: |- + ## Summary + + Preparatory cleanup PR extracted from the EIP-7702 branch to simplify review. + + - **Counter.sol uint64**: Change `uint256` to `uint64` in Counter/NestedCounter fixtures, to avoid U256 conversion in tests. + - **Remove k256 dependency**: Replace `k256::ecdsa::SigningKey` with `sp_core::ecdsa::Pair` in benchmark signing helpers + - **Debug log**: Add debug log for `eth_transact` substrate tx hash + - **Formatting**: Fix indentation in call.rs closure body, remove stray blank line in lib.rs + - **RLP fix**: Fix `Transaction7702Signed` decoder field order (removed incorrect `gas_price` field at index 4, aligned with encoder) +crates: +- name: pallet-revive-fixtures + bump: patch +- name: pallet-revive + bump: patch + validate: false +- name: pallet-revive-eth-rpc + bump: patch + validate: false diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index 8696ad71f0a1b..513184b79d339 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -1,8 +1,10 @@ +cargo-features = ["edition2024"] + [package] name = "pallet-revive" version = "0.1.0" authors.workspace = true -edition.workspace = true +edition = "2024" license = "Apache-2.0" homepage.workspace = true repository.workspace = true diff --git a/substrate/frame/revive/fixtures/contracts/Counter.sol b/substrate/frame/revive/fixtures/contracts/Counter.sol index e4bde49eaab0f..5df2f12cb6b0e 100644 --- a/substrate/frame/revive/fixtures/contracts/Counter.sol +++ b/substrate/frame/revive/fixtures/contracts/Counter.sol @@ -1,13 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract Counter { - uint256 public number; + uint64 public number; constructor() { number = 3; } - function setNumber(uint256 newNumber) public returns (uint256) { + function setNumber(uint64 newNumber) public returns (uint64) { number = newNumber; } @@ -18,7 +18,7 @@ contract Counter { contract NestedCounter { Counter public counter; - uint256 public number; + uint64 public number; constructor() { @@ -27,8 +27,8 @@ contract NestedCounter { number = 7; } - function nestedNumber() public returns (uint256) { - uint256 currentNumber = counter.setNumber(number); + function nestedNumber() public returns (uint64) { + uint64 currentNumber = counter.setNumber(number); number++; return currentNumber; } diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index cb9f124e96930..38afd7d5ce203 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -1,8 +1,10 @@ +cargo-features = ["edition2024"] + [package] name = "pallet-revive-eth-rpc" version = "0.1.0" authors.workspace = true -edition.workspace = true +edition = "2024" license = "Apache-2.0" homepage.workspace = true repository.workspace = true diff --git a/substrate/frame/revive/rpc/examples/deploy.rs b/substrate/frame/revive/rpc/examples/deploy.rs index bcea0fc280c1e..ac3a8ce07d7fb 100644 --- a/substrate/frame/revive/rpc/examples/deploy.rs +++ b/substrate/frame/revive/rpc/examples/deploy.rs @@ -19,7 +19,7 @@ use pallet_revive::{ create1, evm::{Account, BlockTag, ReceiptInfo, U256}, }; -use pallet_revive_eth_rpc::{example::TransactionBuilder, EthRpcClient}; +use pallet_revive_eth_rpc::{EthRpcClient, example::TransactionBuilder}; use std::sync::Arc; #[tokio::main] diff --git a/substrate/frame/revive/rpc/examples/eth-rpc-tester.rs b/substrate/frame/revive/rpc/examples/eth-rpc-tester.rs index 1fa03ffbe7dbb..eecc281954db2 100644 --- a/substrate/frame/revive/rpc/examples/eth-rpc-tester.rs +++ b/substrate/frame/revive/rpc/examples/eth-rpc-tester.rs @@ -17,12 +17,12 @@ use clap::Parser; use jsonrpsee::http_client::HttpClientBuilder; use pallet_revive::evm::{Account, BlockTag, ReceiptInfo}; -use pallet_revive_eth_rpc::{example::TransactionBuilder, EthRpcClient}; +use pallet_revive_eth_rpc::{EthRpcClient, example::TransactionBuilder}; use std::sync::Arc; use tokio::{ io::{AsyncBufReadExt, BufReader}, process::{Child, ChildStderr, Command}, - signal::unix::{signal, SignalKind}, + signal::unix::{SignalKind, signal}, }; const DOCKER_CONTAINER_NAME: &str = "eth-rpc-test"; diff --git a/substrate/frame/revive/rpc/examples/extrinsic.rs b/substrate/frame/revive/rpc/examples/extrinsic.rs index 2d207d2eed9ae..132a026da60cf 100644 --- a/substrate/frame/revive/rpc/examples/extrinsic.rs +++ b/substrate/frame/revive/rpc/examples/extrinsic.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. use pallet_revive_eth_rpc::subxt_client::{ - self, revive::calls::types::InstantiateWithCode, SrcChainConfig, + self, SrcChainConfig, revive::calls::types::InstantiateWithCode, }; use sp_weights::Weight; use subxt::OnlineClient; diff --git a/substrate/frame/revive/rpc/examples/remark-extrinsic.rs b/substrate/frame/revive/rpc/examples/remark-extrinsic.rs index b106d27c218a1..570e2ded46e0d 100644 --- a/substrate/frame/revive/rpc/examples/remark-extrinsic.rs +++ b/substrate/frame/revive/rpc/examples/remark-extrinsic.rs @@ -14,7 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use pallet_revive_eth_rpc::subxt_client::{self, system::calls::types::Remark, SrcChainConfig}; +use pallet_revive_eth_rpc::subxt_client::{self, SrcChainConfig, system::calls::types::Remark}; use subxt::OnlineClient; use subxt_signer::sr25519::dev; diff --git a/substrate/frame/revive/rpc/examples/transfer.rs b/substrate/frame/revive/rpc/examples/transfer.rs index 12823d4a34827..e9881220d3733 100644 --- a/substrate/frame/revive/rpc/examples/transfer.rs +++ b/substrate/frame/revive/rpc/examples/transfer.rs @@ -16,7 +16,7 @@ // limitations under the License. use jsonrpsee::http_client::HttpClientBuilder; use pallet_revive::evm::{Account, BlockTag, ReceiptInfo}; -use pallet_revive_eth_rpc::{example::TransactionBuilder, EthRpcClient}; +use pallet_revive_eth_rpc::{EthRpcClient, example::TransactionBuilder}; use std::sync::Arc; #[tokio::main] diff --git a/substrate/frame/revive/rpc/src/apis/execution_apis.rs b/substrate/frame/revive/rpc/src/apis/execution_apis.rs index 9ef03a8334698..350b661d00312 100644 --- a/substrate/frame/revive/rpc/src/apis/execution_apis.rs +++ b/substrate/frame/revive/rpc/src/apis/execution_apis.rs @@ -59,7 +59,7 @@ pub trait EthRpc { /// Returns the balance of the account of given address. #[method(name = "eth_getBalance")] async fn get_balance(&self, address: Address, block: BlockNumberOrTagOrHash) - -> RpcResult; + -> RpcResult; /// Returns information about a block by hash. #[method(name = "eth_getBlockByHash")] diff --git a/substrate/frame/revive/rpc/src/block_info_provider.rs b/substrate/frame/revive/rpc/src/block_info_provider.rs index 1755ce58a5829..7f56acfa575fc 100644 --- a/substrate/frame/revive/rpc/src/block_info_provider.rs +++ b/substrate/frame/revive/rpc/src/block_info_provider.rs @@ -16,14 +16,14 @@ // limitations under the License. use crate::{ + ClientError, client::{SubscriptionType, SubstrateBlock, SubstrateBlockNumber}, subxt_client::SrcChainConfig, - ClientError, }; use jsonrpsee::core::async_trait; use sp_core::H256; use std::sync::Arc; -use subxt::{backend::legacy::LegacyRpcMethods, OnlineClient}; +use subxt::{OnlineClient, backend::legacy::LegacyRpcMethods}; use tokio::sync::RwLock; /// BlockInfoProvider cache and retrieves information about blocks. diff --git a/substrate/frame/revive/rpc/src/cli.rs b/substrate/frame/revive/rpc/src/cli.rs index 87793e78be59b..049512a440dc2 100644 --- a/substrate/frame/revive/rpc/src/cli.rs +++ b/substrate/frame/revive/rpc/src/cli.rs @@ -16,18 +16,19 @@ // limitations under the License. //! The Ethereum JSON-RPC server. use crate::{ - client::{connect, Client, SubscriptionType, SubstrateBlockNumber}, - DebugRpcServer, DebugRpcServerImpl, EthRpcServer, EthRpcServerImpl, PolkadotRpcServer, - PolkadotRpcServerImpl, ReceiptExtractor, ReceiptProvider, SubxtBlockInfoProvider, - SystemHealthRpcServer, SystemHealthRpcServerImpl, LOG_TARGET, + DebugRpcServer, DebugRpcServerImpl, EthRpcServer, EthRpcServerImpl, LOG_TARGET, + PolkadotRpcServer, PolkadotRpcServerImpl, ReceiptExtractor, ReceiptProvider, + SubxtBlockInfoProvider, SystemHealthRpcServer, SystemHealthRpcServerImpl, + client::{Client, SubscriptionType, SubstrateBlockNumber, connect}, }; use clap::Parser; -use futures::{future::BoxFuture, pin_mut, FutureExt}; +use futures::{FutureExt, future::BoxFuture, pin_mut}; use jsonrpsee::server::RpcModule; use sc_cli::{PrometheusParams, RpcParams, SharedParams, Signals}; use sc_service::{ + TaskManager, config::{PrometheusConfig, RpcConfiguration}, - start_rpc_servers, TaskManager, + start_rpc_servers, }; use sqlx::sqlite::SqlitePoolOptions; diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index 283458d9bbd87..1118033f018b7 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -21,18 +21,18 @@ pub(crate) mod runtime_api; pub(crate) mod storage_api; use crate::{ - subxt_client::{self, revive::calls::types::EthTransact, SrcChainConfig}, BlockInfoProvider, BlockTag, FeeHistoryProvider, ReceiptProvider, SubxtBlockInfoProvider, TracerType, TransactionInfo, + subxt_client::{self, SrcChainConfig, revive::calls::types::EthTransact}, }; -use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObjectOwned}; +use jsonrpsee::types::{ErrorObjectOwned, error::CALL_EXECUTION_FAILED_CODE}; use pallet_revive::{ + EthTransactError, evm::{ - decode_revert_reason, Block, BlockNumberOrTag, BlockNumberOrTagOrHash, FeeHistoryResult, - Filter, GenericTransaction, HashesOrTransactionInfos, Log, ReceiptInfo, SyncingProgress, - SyncingStatus, Trace, TransactionSigned, TransactionTrace, H256, + Block, BlockNumberOrTag, BlockNumberOrTagOrHash, FeeHistoryResult, Filter, + GenericTransaction, H256, HashesOrTransactionInfos, Log, ReceiptInfo, SyncingProgress, + SyncingStatus, Trace, TransactionSigned, TransactionTrace, decode_revert_reason, }, - EthTransactError, }; use runtime_api::RuntimeApi; use sp_runtime::traits::Block as BlockT; @@ -40,16 +40,16 @@ use sp_weights::Weight; use std::{ops::Range, sync::Arc, time::Duration}; use storage_api::StorageApi; use subxt::{ + Config, OnlineClient, backend::{ - legacy::{rpc_methods::SystemHealth, LegacyRpcMethods}, + legacy::{LegacyRpcMethods, rpc_methods::SystemHealth}, rpc::{ - reconnecting_rpc_client::{ExponentialBackoff, RpcClient as ReconnectingRpcClient}, RpcClient, + reconnecting_rpc_client::{ExponentialBackoff, RpcClient as ReconnectingRpcClient}, }, }, config::{HashFor, Header}, ext::subxt_rpcs::rpc_params, - Config, OnlineClient, }; use thiserror::Error; use tokio::sync::Mutex; diff --git a/substrate/frame/revive/rpc/src/client/runtime_api.rs b/substrate/frame/revive/rpc/src/client/runtime_api.rs index e90cbc524c321..78548f374480f 100644 --- a/substrate/frame/revive/rpc/src/client/runtime_api.rs +++ b/substrate/frame/revive/rpc/src/client/runtime_api.rs @@ -16,21 +16,21 @@ // limitations under the License. use crate::{ + ClientError, client::Balance, subxt_client::{self, SrcChainConfig}, - ClientError, }; use futures::TryFutureExt; use pallet_revive::{ + DryRunConfig, EthTransactInfo, evm::{ - Block as EthBlock, BlockNumberOrTagOrHash, BlockTag, GenericTransaction, ReceiptGasInfo, - Trace, H160, U256, + Block as EthBlock, BlockNumberOrTagOrHash, BlockTag, GenericTransaction, H160, + ReceiptGasInfo, Trace, U256, }, - DryRunConfig, EthTransactInfo, }; use sp_core::H256; use sp_timestamp::Timestamp; -use subxt::{error::MetadataError, ext::subxt_rpcs::UserError, Error::Metadata, OnlineClient}; +use subxt::{Error::Metadata, OnlineClient, error::MetadataError, ext::subxt_rpcs::UserError}; const LOG_TARGET: &str = "eth-rpc::runtime_api"; diff --git a/substrate/frame/revive/rpc/src/client/storage_api.rs b/substrate/frame/revive/rpc/src/client/storage_api.rs index d4b27d7162552..e9e3a8d2b7073 100644 --- a/substrate/frame/revive/rpc/src/client/storage_api.rs +++ b/substrate/frame/revive/rpc/src/client/storage_api.rs @@ -16,14 +16,13 @@ // limitations under the License. use crate::{ + ClientError, H160, subxt_client::{ - self, + self, SrcChainConfig, runtime_types::pallet_revive::storage::{AccountType, ContractInfo}, - SrcChainConfig, }, - ClientError, H160, }; -use subxt::{storage::Storage, OnlineClient}; +use subxt::{OnlineClient, storage::Storage}; /// A wrapper around the Substrate Storage API. #[derive(Clone)] diff --git a/substrate/frame/revive/rpc/src/fee_history_provider.rs b/substrate/frame/revive/rpc/src/fee_history_provider.rs index b12f8e1e7df65..c727b5f6735f7 100644 --- a/substrate/frame/revive/rpc/src/fee_history_provider.rs +++ b/substrate/frame/revive/rpc/src/fee_history_provider.rs @@ -14,7 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use crate::{client::SubstrateBlockNumber, ClientError}; +use crate::{ClientError, client::SubstrateBlockNumber}; use pallet_revive::evm::{Block, FeeHistoryResult, ReceiptInfo}; use sp_core::U256; use std::{collections::BTreeMap, sync::Arc}; diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index b59c24484aece..d1fa7fb9ba3c3 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -19,11 +19,11 @@ use client::ClientError; use jsonrpsee::{ - core::{async_trait, RpcResult}, + core::{RpcResult, async_trait}, types::{ErrorCode, ErrorObjectOwned}, }; use pallet_revive::evm::*; -use sp_core::{keccak_256, H160, H256, U256}; +use sp_core::{H160, H256, U256, keccak_256}; use thiserror::Error; use tokio::time::Duration; diff --git a/substrate/frame/revive/rpc/src/receipt_extractor.rs b/substrate/frame/revive/rpc/src/receipt_extractor.rs index 7bece956c7f2e..a404231849e6f 100644 --- a/substrate/frame/revive/rpc/src/receipt_extractor.rs +++ b/substrate/frame/revive/rpc/src/receipt_extractor.rs @@ -15,25 +15,25 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ - client::{runtime_api::RuntimeApi, SubstrateBlock, SubstrateBlockNumber}, + ClientError, H160, LOG_TARGET, + client::{SubstrateBlock, SubstrateBlockNumber, runtime_api::RuntimeApi}, subxt_client::{ + SrcChainConfig, revive::{ calls::types::EthTransact, events::{ContractEmitted, EthExtrinsicRevert}, }, - SrcChainConfig, }, - ClientError, H160, LOG_TARGET, }; -use futures::{stream, StreamExt}; +use futures::{StreamExt, stream}; use pallet_revive::{ create1, - evm::{GenericTransaction, Log, ReceiptGasInfo, ReceiptInfo, TransactionSigned, H256, U256}, + evm::{GenericTransaction, H256, Log, ReceiptGasInfo, ReceiptInfo, TransactionSigned, U256}, }; use sp_core::keccak_256; use std::{future::Future, pin::Pin, sync::Arc}; -use subxt::{blocks::ExtrinsicDetails, OnlineClient}; +use subxt::{OnlineClient, blocks::ExtrinsicDetails}; type FetchReceiptDataFn = Arc< dyn Fn(H256) -> Pin>> + Send>> + Send + Sync, diff --git a/substrate/frame/revive/rpc/src/receipt_provider.rs b/substrate/frame/revive/rpc/src/receipt_provider.rs index ff55adb05b619..026bb3430b761 100644 --- a/substrate/frame/revive/rpc/src/receipt_provider.rs +++ b/substrate/frame/revive/rpc/src/receipt_provider.rs @@ -15,13 +15,13 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ - client::{SubstrateBlock, SubstrateBlockNumber}, Address, AddressOrAddresses, BlockInfoProvider, BlockNumberOrTag, BlockTag, Bytes, ClientError, FilterTopic, ReceiptExtractor, SubxtBlockInfoProvider, + client::{SubstrateBlock, SubstrateBlockNumber}, }; use pallet_revive::evm::{Filter, Log, ReceiptInfo, TransactionSigned}; use sp_core::{H256, U256}; -use sqlx::{query, QueryBuilder, Row, Sqlite, SqlitePool}; +use sqlx::{QueryBuilder, Row, Sqlite, SqlitePool, query}; use std::{ collections::{BTreeMap, HashMap}, sync::Arc, diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index c684eb7eb8e44..912c12e0387c9 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -19,12 +19,12 @@ //! [evm-test-suite](https://github.com/paritytech/evm-test-suite) repository. use crate::{ + EthRpcClient, cli::{self, CliCommand}, example::TransactionBuilder, subxt_client::{ - self, src_chain::runtime_types::pallet_revive::primitives::Code, SrcChainConfig, + self, SrcChainConfig, src_chain::runtime_types::pallet_revive::primitives::Code, }, - EthRpcClient, }; use anyhow::anyhow; use clap::Parser; @@ -32,16 +32,16 @@ use jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use pallet_revive::{ create1, evm::{ - Account, Block, BlockNumberOrTag, BlockNumberOrTagOrHash, BlockTag, - HashesOrTransactionInfos, TransactionInfo, TransactionUnsigned, H256, U256, + Account, Block, BlockNumberOrTag, BlockNumberOrTagOrHash, BlockTag, H256, + HashesOrTransactionInfos, TransactionInfo, TransactionUnsigned, U256, }, }; use std::{sync::Arc, thread}; use subxt::{ + OnlineClient, backend::rpc::RpcClient, ext::subxt_rpcs::rpc_params, tx::{SubmittableTransaction, TxStatus}, - OnlineClient, }; const LOG_TARGET: &str = "eth-rpc-tests"; @@ -422,7 +422,11 @@ async fn test_deploy_and_call() -> anyhow::Result<()> { ); let balance = client.get_balance(contract_address, BlockTag::Latest.into()).await?; - assert_eq!(Some(value), balance.checked_sub(initial_balance), "Contract {contract_address:?} Balance {balance} should have increased from {initial_balance} by {value}."); + assert_eq!( + Some(value), + balance.checked_sub(initial_balance), + "Contract {contract_address:?} Balance {balance} should have increased from {initial_balance} by {value}." + ); // Balance transfer to contract let initial_balance = client.get_balance(contract_address, BlockTag::Latest.into()).await?; diff --git a/substrate/frame/revive/src/address.rs b/substrate/frame/revive/src/address.rs index fa238165f9f41..e7a344d55558f 100644 --- a/substrate/frame/revive/src/address.rs +++ b/substrate/frame/revive/src/address.rs @@ -17,7 +17,7 @@ //! Functions that deal contract addresses. -use crate::{ensure, Config, Error, HoldReason, OriginalAccount}; +use crate::{Config, Error, HoldReason, OriginalAccount, ensure}; use alloc::vec::Vec; use core::marker::PhantomData; use frame_support::traits::{fungible::MutateHold, tokens::Precision}; @@ -270,16 +270,16 @@ pub fn create2(deployer: &H160, code: &[u8], input_data: &[u8], salt: &[u8; 32]) mod test { use super::*; use crate::{ + AddressMapper, Error, test_utils::*, tests::{ExtBuilder, Test}, - AddressMapper, Error, }; use frame_support::{ assert_err, traits::fungible::{InspectHold, Mutate}, }; use pretty_assertions::assert_eq; - use sp_core::{hex2array, H160}; + use sp_core::{H160, hex2array}; #[test] fn create1_works() { diff --git a/substrate/frame/revive/src/benchmarking.rs b/substrate/frame/revive/src/benchmarking.rs index e89e95bb097fa..913737921adc8 100644 --- a/substrate/frame/revive/src/benchmarking.rs +++ b/substrate/frame/revive/src/benchmarking.rs @@ -19,29 +19,29 @@ #![cfg(feature = "runtime-benchmarks")] use crate::{ - call_builder::{caller_funding, default_deposit_limit, CallSetup, Contract, VmBinaryModule}, + Pallet as Contracts, + call_builder::{CallSetup, Contract, VmBinaryModule, caller_funding, default_deposit_limit}, evm::{ - block_hash::EthereumBlockBuilder, block_storage, TransactionLegacyUnsigned, - TransactionSigned, TransactionUnsigned, + TransactionLegacyUnsigned, TransactionSigned, TransactionUnsigned, + block_hash::EthereumBlockBuilder, block_storage, }, exec::{Key, Origin as ExecOrigin, PrecompileExt}, limits, precompiles::{ - self, + self, BenchmarkStorage, BenchmarkSystem, BuiltinPrecompile, alloy::sol_types::{ - sol_data::{Bool, Bytes, FixedBytes, Uint}, SolType, + sol_data::{Bool, Bytes, FixedBytes, Uint}, }, run::builtin as run_builtin_precompile, - BenchmarkStorage, BenchmarkSystem, BuiltinPrecompile, }, storage::WriteOutcome, vm::{ evm, - evm::{instructions, instructions::utility::IntoAddress, Interpreter}, + evm::{Interpreter, instructions, instructions::utility::IntoAddress}, pvm, }, - Pallet as Contracts, *, + *, }; use alloc::{vec, vec::Vec}; use alloy_core::sol_types::{SolInterface, SolValue}; @@ -51,21 +51,20 @@ use frame_support::{ self, assert_ok, migrations::SteppedMigration, storage::child, - traits::{fungible::InspectHold, Hooks}, + traits::{Hooks, fungible::InspectHold}, weights::{Weight, WeightMeter}, }; use frame_system::RawOrigin; use k256::ecdsa::SigningKey; use pallet_revive_uapi::{ - pack_hi_lo, + CallFlags, ReturnErrorCode, StorageFlags, pack_hi_lo, precompiles::{storage::IStorage, system::ISystem}, - CallFlags, ReturnErrorCode, StorageFlags, }; use revm::bytecode::Bytecode; use sp_consensus_aura::AURA_ENGINE_ID; use sp_consensus_babe::{ - digests::{PreDigest, PrimaryPreDigest}, BABE_ENGINE_ID, + digests::{PreDigest, PrimaryPreDigest}, }; use sp_consensus_slots::Slot; use sp_runtime::{generic::DigestItem, traits::Zero}; @@ -2400,7 +2399,7 @@ mod benchmarks { #[benchmark(pov_mode = Measured)] fn bn128_pairing(n: Linear<0, { 20 }>) { fn generate_random_ecpairs(n: usize) -> Vec { - use bn::{AffineG1, AffineG2, Fr, Group, G1, G2}; + use bn::{AffineG1, AffineG2, Fr, G1, G2, Group}; use rand::SeedableRng; use rand_pcg::Pcg64; let mut rng = Pcg64::seed_from_u64(1); @@ -2514,7 +2513,7 @@ mod benchmarks { // and then accessing it so that each instruction generates two cache misses. #[benchmark(pov_mode = Ignored)] fn instr(r: Linear<0, 10_000>) { - use rand::{seq::SliceRandom, SeedableRng}; + use rand::{SeedableRng, seq::SliceRandom}; use rand_pcg::Pcg64; // Ideally, this needs to be bigger than the cache. @@ -2715,8 +2714,8 @@ mod benchmarks { } /// Helper function to generate common finalize_block benchmark setup - fn setup_finalize_block_benchmark( - ) -> Result<(Contract, BalanceOf, U256, SigningKey, BlockNumberFor), BenchmarkError> + fn setup_finalize_block_benchmark() + -> Result<(Contract, BalanceOf, U256, SigningKey, BlockNumberFor), BenchmarkError> where BalanceOf: Into + TryFrom, T: Config, diff --git a/substrate/frame/revive/src/call_builder.rs b/substrate/frame/revive/src/call_builder.rs index cafe8382ae10a..40c230f05ec90 100644 --- a/substrate/frame/revive/src/call_builder.rs +++ b/substrate/frame/revive/src/call_builder.rs @@ -26,14 +26,14 @@ #![cfg_attr(test, allow(dead_code))] use crate::{ + AccountInfo, BalanceOf, BalanceWithDust, Code, CodeInfoOf, Config, ContractBlob, ContractInfo, + Error, ExecConfig, ExecOrigin as Origin, OriginFor, Pallet as Contracts, PristineCode, Weight, address::AddressMapper, exec::{ExportedFunction, Key, PrecompileExt, Stack}, limits, metering::{TransactionLimits, TransactionMeter}, transient_storage::MeterEntry, vm::pvm::{PreparedCall, Runtime}, - AccountInfo, BalanceOf, BalanceWithDust, Code, CodeInfoOf, Config, ContractBlob, ContractInfo, - Error, ExecConfig, ExecOrigin as Origin, OriginFor, Pallet as Contracts, PristineCode, Weight, }; use alloc::{vec, vec::Vec}; use frame_support::{storage::child, traits::fungible::Mutate}; diff --git a/substrate/frame/revive/src/debug.rs b/substrate/frame/revive/src/debug.rs index ba73798859528..c1c8b8c52a891 100644 --- a/substrate/frame/revive/src/debug.rs +++ b/substrate/frame/revive/src/debug.rs @@ -16,11 +16,11 @@ // limitations under the License. use crate::{Config, DebugSettingsOf}; +use Debug; use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_core::Get; -use Debug; /// Debugging settings that can be configured when DebugEnabled config is true. #[derive( diff --git a/substrate/frame/revive/src/evm/api/account.rs b/substrate/frame/revive/src/evm/api/account.rs index 931a2060c6fde..1c3b589c920b3 100644 --- a/substrate/frame/revive/src/evm/api/account.rs +++ b/substrate/frame/revive/src/evm/api/account.rs @@ -16,8 +16,8 @@ // limitations under the License. //! Utilities for working with Ethereum accounts. use crate::{ - evm::{TransactionSigned, TransactionUnsigned}, H160, + evm::{TransactionSigned, TransactionUnsigned}, }; use sp_runtime::AccountId32; diff --git a/substrate/frame/revive/src/evm/api/debug_rpc_types.rs b/substrate/frame/revive/src/evm/api/debug_rpc_types.rs index 9cc1da82e1a54..6bbfa13f93fae 100644 --- a/substrate/frame/revive/src/evm/api/debug_rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/debug_rpc_types.rs @@ -15,15 +15,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{evm::Bytes, Weight}; +use crate::{Weight, evm::Bytes}; use alloc::{collections::BTreeMap, string::String, vec::Vec}; use codec::{Decode, Encode}; use derive_more::From; use scale_info::TypeInfo; use serde::{ + Deserialize, Serialize, de::{Deserializer, Error, MapAccess, Visitor}, ser::{SerializeMap, Serializer}, - Deserialize, Serialize, }; use sp_core::{H160, H256, U256}; diff --git a/substrate/frame/revive/src/evm/api/rlp_codec.rs b/substrate/frame/revive/src/evm/api/rlp_codec.rs index 483314c946656..89c7ecd055bc4 100644 --- a/substrate/frame/revive/src/evm/api/rlp_codec.rs +++ b/substrate/frame/revive/src/evm/api/rlp_codec.rs @@ -27,23 +27,23 @@ impl TransactionUnsigned { use TransactionUnsigned::*; let mut s = rlp::RlpStream::new(); match self { - Transaction7702Unsigned(ref tx) => { + Transaction7702Unsigned(tx) => { s.append(&tx.r#type.value()); s.append(tx); }, - Transaction2930Unsigned(ref tx) => { + Transaction2930Unsigned(tx) => { s.append(&tx.r#type.value()); s.append(tx); }, - Transaction1559Unsigned(ref tx) => { + Transaction1559Unsigned(tx) => { s.append(&tx.r#type.value()); s.append(tx); }, - Transaction4844Unsigned(ref tx) => { + Transaction4844Unsigned(tx) => { s.append(&tx.r#type.value()); s.append(tx); }, - TransactionLegacyUnsigned(ref tx) => { + TransactionLegacyUnsigned(tx) => { s.append(tx); }, } @@ -73,23 +73,23 @@ impl TransactionSigned { use TransactionSigned::*; let mut s = rlp::RlpStream::new(); match self { - Transaction7702Signed(ref tx) => { + Transaction7702Signed(tx) => { s.append(&tx.transaction_7702_unsigned.r#type.value()); s.append(tx); }, - Transaction2930Signed(ref tx) => { + Transaction2930Signed(tx) => { s.append(&tx.transaction_2930_unsigned.r#type.value()); s.append(tx); }, - Transaction1559Signed(ref tx) => { + Transaction1559Signed(tx) => { s.append(&tx.transaction_1559_unsigned.r#type.value()); s.append(tx); }, - Transaction4844Signed(ref tx) => { + Transaction4844Signed(tx) => { s.append(&tx.transaction_4844_unsigned.r#type.value()); s.append(tx); }, - TransactionLegacySigned(ref tx) => { + TransactionLegacySigned(tx) => { s.append(tx); }, } @@ -167,11 +167,7 @@ impl Decodable for TransactionLegacyUnsigned { gas: rlp.val_at(2)?, to: { let to = rlp.at(3)?; - if to.is_empty() { - None - } else { - Some(to.as_val()?) - } + if to.is_empty() { None } else { Some(to.as_val()?) } }, value: rlp.val_at(4)?, input: Bytes(rlp.val_at(5)?), @@ -296,11 +292,7 @@ impl Decodable for Transaction1559Signed { gas: rlp.val_at(4)?, to: { let to = rlp.at(5)?; - if to.is_empty() { - None - } else { - Some(to.as_val()?) - } + if to.is_empty() { None } else { Some(to.as_val()?) } }, value: rlp.val_at(6)?, input: Bytes(rlp.val_at(7)?), @@ -367,11 +359,7 @@ impl Decodable for Transaction2930Signed { gas: rlp.val_at(3)?, to: { let to = rlp.at(4)?; - if to.is_empty() { - None - } else { - Some(to.as_val()?) - } + if to.is_empty() { None } else { Some(to.as_val()?) } }, value: rlp.val_at(5)?, input: Bytes(rlp.val_at(6)?), @@ -413,19 +401,18 @@ impl Decodable for Transaction7702Signed { nonce: rlp.val_at(1)?, max_priority_fee_per_gas: rlp.val_at(2)?, max_fee_per_gas: rlp.val_at(3)?, - gas_price: rlp.val_at(4)?, - gas: rlp.val_at(5)?, - to: rlp.val_at(6)?, - value: rlp.val_at(7)?, - input: Bytes(rlp.val_at(8)?), - access_list: rlp.list_at(9)?, - authorization_list: rlp.list_at(10)?, + gas: rlp.val_at(4)?, + to: rlp.val_at(5)?, + value: rlp.val_at(6)?, + input: Bytes(rlp.val_at(7)?), + access_list: rlp.list_at(8)?, + authorization_list: rlp.list_at(9)?, r#type: Default::default(), } }, - y_parity: rlp.val_at(11)?, - r: rlp.val_at(12)?, - s: rlp.val_at(13)?, + y_parity: rlp.val_at(10)?, + r: rlp.val_at(11)?, + s: rlp.val_at(12)?, v: None, }) } @@ -523,11 +510,7 @@ impl Decodable for TransactionLegacySigned { let v: U256 = rlp.val_at(6)?; let extract_chain_id = |v: U256| { - if v.ge(&35u32.into()) { - Some((v - 35) / 2) - } else { - None - } + if v.ge(&35u32.into()) { Some((v - 35) / 2) } else { None } }; Ok(TransactionLegacySigned { @@ -538,11 +521,7 @@ impl Decodable for TransactionLegacySigned { gas: rlp.val_at(2)?, to: { let to = rlp.at(3)?; - if to.is_empty() { - None - } else { - Some(to.as_val()?) - } + if to.is_empty() { None } else { Some(to.as_val()?) } }, value: rlp.val_at(4)?, input: Bytes(rlp.val_at(5)?), @@ -581,7 +560,7 @@ mod test { "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", "v": "0x25" } - "# + "#, ), // type 1: EIP2930 ( @@ -606,7 +585,7 @@ mod test { "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", "yParity": "0x0" } - "# + "#, ), // type 2: EIP1559 ( @@ -634,7 +613,7 @@ mod test { "yParity": "0x0" } - "# + "#, ), // type 3: EIP4844 ( @@ -663,7 +642,7 @@ mod test { "yParity": "0x0" } "#, - ) + ), ]; for (tx, json) in txs { @@ -675,6 +654,43 @@ mod test { } } + #[test] + fn encode_decode_7702_tx_works() { + let tx = TransactionSigned::Transaction7702Signed(Transaction7702Signed { + transaction_7702_unsigned: Transaction7702Unsigned { + chain_id: U256::from(1), + nonce: U256::zero(), + max_priority_fee_per_gas: U256::zero(), + max_fee_per_gas: U256::from(1), + gas: U256::from(0x1e241), + to: "0x095e7baea6a6c7c4c2dfeb977efac326af552d87".parse().unwrap(), + value: U256::zero(), + input: Bytes(vec![]), + access_list: vec![AccessListEntry { + address: H160::from_low_u64_be(1), + storage_keys: vec![H256::zero()], + }], + authorization_list: vec![AuthorizationListEntry { + chain_id: U256::from(1), + address: H160::from_low_u64_be(42), + nonce: U256::zero(), + y_parity: U256::zero(), + r: U256::from(1), + s: U256::from(2), + }], + r#type: TypeEip7702 {}, + }, + y_parity: U256::zero(), + r: U256::from(1), + s: U256::from(2), + v: None, + }); + + let encoded = tx.signed_payload(); + let decoded = TransactionSigned::decode(&encoded).unwrap(); + assert_eq!(tx, decoded); + } + #[test] fn dummy_signed_payload_works() { let tx: TransactionUnsigned = TransactionLegacyUnsigned { @@ -705,7 +721,7 @@ mod test { // EIP-1559 "02f89c018080018301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", // EIP4844 - "03f89783aa36a701832dc6c083fc546c8261a8947f8b1ca29f95274e06367b60fc4a539e4910fd0c865af3107a400080c0831e8480e1a0018fd423d1ad106395f04abac797217d4dece29da3ba649d9aa4da70e98fa6ff80a028d2350a1bfa5043de1533911143eb5c43815a58039121a0ccf124870620fca6a0157eca4963615cd3926538af88e529cfa3baf6c55787a33f79c25babe9f5db2b", + "03f89783aa36a701832dc6c083fc546c8261a8947f8b1ca29f95274e06367b60fc4a539e4910fd0c865af3107a400080c0831e8480e1a0018fd423d1ad106395f04abac797217d4dece29da3ba649d9aa4da70e98fa6ff80a028d2350a1bfa5043de1533911143eb5c43815a58039121a0ccf124870620fca6a0157eca4963615cd3926538af88e529cfa3baf6c55787a33f79c25babe9f5db2b", ]; for hex_tx in test_cases { diff --git a/substrate/frame/revive/src/evm/api/rpc_types.rs b/substrate/frame/revive/src/evm/api/rpc_types.rs index aa2dd04defcdf..589fdba78200b 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types.rs @@ -390,7 +390,6 @@ impl GenericTransaction { value: self.value.unwrap_or_default(), to: self.to.unwrap_or_default(), gas: self.gas.unwrap_or_default(), - gas_price: self.max_fee_per_gas.unwrap_or_default(), max_fee_per_gas: self.max_fee_per_gas.unwrap_or_default(), max_priority_fee_per_gas: self.max_priority_fee_per_gas.unwrap_or_default(), access_list: self.access_list.unwrap_or_default(), @@ -456,7 +455,6 @@ fn from_unsigned_works_for_7702() { value: U256::from(1), to: H160::zero(), gas: U256::from(1), - gas_price: U256::from(20), max_fee_per_gas: U256::from(20), max_priority_fee_per_gas: U256::from(1), authorization_list: vec![AuthorizationListEntry { diff --git a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs index 2411c12c3dbba..fcd1be75c8930 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs @@ -17,13 +17,13 @@ //! Generated JSON-RPC types. #![allow(missing_docs)] -use super::{byte::*, TypeEip1559, TypeEip2930, TypeEip4844, TypeEip7702, TypeLegacy}; +use super::{TypeEip1559, TypeEip2930, TypeEip4844, TypeEip7702, TypeLegacy, byte::*}; use alloc::vec::Vec; use codec::{Decode, DecodeWithMemTracking, Encode}; use derive_more::{From, TryInto}; pub use ethereum_types::*; use scale_info::TypeInfo; -use serde::{de::Error, Deserialize, Deserializer, Serialize}; +use serde::{Deserialize, Deserializer, Serialize, de::Error}; /// Input of a `GenericTransaction` #[derive( @@ -67,10 +67,13 @@ impl InputOrData { fn deserialize_input_or_data<'d, D: Deserializer<'d>>(d: D) -> Result { let value = InputOrData::deserialize(d)?; match &value { - InputOrData { input: Some(input), data: Some(data) } if input != data => - Err(serde::de::Error::custom("Both \"data\" and \"input\" are set and not equal. Please use \"input\" to pass transaction call data")), - _ => Ok(value), - } + InputOrData { input: Some(input), data: Some(data) } if input != data => { + Err(serde::de::Error::custom( + "Both \"data\" and \"input\" are set and not equal. Please use \"input\" to pass transaction call data", + )) + }, + _ => Ok(value), + } } /// Block object @@ -796,11 +799,6 @@ pub struct Transaction7702Unsigned { pub chain_id: U256, /// gas limit pub gas: U256, - /// gas price - /// The effective gas price paid by the sender in wei. For transactions not yet included in a - /// block, this value should be set equal to the max fee per gas. This field is DEPRECATED, - /// please transition to using effectiveGasPrice in the receipt object going forward. - pub gas_price: U256, /// input data pub input: Bytes, /// max fee per gas diff --git a/substrate/frame/revive/src/evm/api/type_id.rs b/substrate/frame/revive/src/evm/api/type_id.rs index b055cb59dbe1b..01e0948b3badb 100644 --- a/substrate/frame/revive/src/evm/api/type_id.rs +++ b/substrate/frame/revive/src/evm/api/type_id.rs @@ -49,11 +49,7 @@ macro_rules! transaction_type { /// Try to convert from Byte pub fn try_from_byte(byte: Byte) -> Result { - if byte.0 == $value { - Ok(Self {}) - } else { - Err(byte) - } + if byte.0 == $value { Ok(Self {}) } else { Err(byte) } } } diff --git a/substrate/frame/revive/src/evm/block_hash.rs b/substrate/frame/revive/src/evm/block_hash.rs index 85278fa388159..1ec1602ceefee 100644 --- a/substrate/frame/revive/src/evm/block_hash.rs +++ b/substrate/frame/revive/src/evm/block_hash.rs @@ -30,7 +30,7 @@ pub use block_builder::{EthereumBlockBuilder, EthereumBlockBuilderIR}; use crate::evm::Block; use alloc::vec::Vec; -use alloy_core::primitives::{bytes::BufMut, B256}; +use alloy_core::primitives::{B256, bytes::BufMut}; use codec::{Decode, Encode}; use scale_info::TypeInfo; diff --git a/substrate/frame/revive/src/evm/block_hash/block_builder.rs b/substrate/frame/revive/src/evm/block_hash/block_builder.rs index 680c9bf749fe5..b90f850cd27c1 100644 --- a/substrate/frame/revive/src/evm/block_hash/block_builder.rs +++ b/substrate/frame/revive/src/evm/block_hash/block_builder.rs @@ -18,14 +18,14 @@ //! Ethereum block builder. use crate::{ + Config, Pallet, ReceiptGasInfo, evm::{ + Block, HashesOrTransactionInfos, TYPE_EIP1559, TYPE_EIP2930, TYPE_EIP4844, TYPE_EIP7702, block_hash::{ - receipt::BLOOM_SIZE_BYTES, AccumulateReceipt, BuilderPhase, IncrementalHashBuilder, - IncrementalHashBuilderIR, LogsBloom, + AccumulateReceipt, BuilderPhase, IncrementalHashBuilder, IncrementalHashBuilderIR, + LogsBloom, receipt::BLOOM_SIZE_BYTES, }, - Block, HashesOrTransactionInfos, TYPE_EIP1559, TYPE_EIP2930, TYPE_EIP4844, TYPE_EIP7702, }, - Config, Pallet, ReceiptGasInfo, }; use alloc::{vec, vec::Vec}; @@ -34,7 +34,7 @@ use codec::{Decode, Encode}; use frame_support::traits::Time; use scale_info::TypeInfo; use sp_arithmetic::traits::Saturating; -use sp_core::{keccak_256, H160, H256, U256}; +use sp_core::{H160, H256, U256, keccak_256}; use sp_runtime::traits::{One, Zero}; const LOG_TARGET: &str = "runtime::revive::block_builder"; diff --git a/substrate/frame/revive/src/evm/block_hash/hash_builder.rs b/substrate/frame/revive/src/evm/block_hash/hash_builder.rs index ae3c9b82f26ae..169e367ac2343 100644 --- a/substrate/frame/revive/src/evm/block_hash/hash_builder.rs +++ b/substrate/frame/revive/src/evm/block_hash/hash_builder.rs @@ -20,9 +20,9 @@ use alloc::vec::Vec; use alloy_core::rlp; use alloy_trie::{ + HashBuilder, Nibbles, TrieMask, hash_builder::{HashBuilderValue, HashBuilderValueRef}, nodes::RlpNode, - HashBuilder, Nibbles, TrieMask, }; use codec::{Decode, Encode}; use sp_core::H256; diff --git a/substrate/frame/revive/src/evm/block_hash/receipt.rs b/substrate/frame/revive/src/evm/block_hash/receipt.rs index 29812cc5c0573..c690112c08a5d 100644 --- a/substrate/frame/revive/src/evm/block_hash/receipt.rs +++ b/substrate/frame/revive/src/evm/block_hash/receipt.rs @@ -19,7 +19,7 @@ use alloc::vec::Vec; use alloy_core::rlp; -use sp_core::{keccak_256, H160, H256}; +use sp_core::{H160, H256, keccak_256}; /// Number of bytes that a bloom stores. pub const BLOOM_SIZE_BYTES: usize = 256; diff --git a/substrate/frame/revive/src/evm/block_storage.rs b/substrate/frame/revive/src/evm/block_storage.rs index e4b5360c1fede..270dd95f41912 100644 --- a/substrate/frame/revive/src/evm/block_storage.rs +++ b/substrate/frame/revive/src/evm/block_storage.rs @@ -15,7 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ - dispatch_result, + AccountIdOf, BalanceOf, BalanceWithDust, BlockHash, BlockNumberFor, Config, ContractResult, + Error, EthBlockBuilderIR, EthereumBlock, Event, ExecReturnValue, H160, H256, LOG_TARGET, + Pallet, ReceiptGasInfo, ReceiptInfoData, StorageDeposit, Weight, dispatch_result, evm::{ block_hash::{AccumulateReceipt, EthereumBlockBuilder, LogsBloom}, burn_with_dust, @@ -24,9 +26,6 @@ use crate::{ limits, sp_runtime::traits::{One, Zero}, weights::WeightInfo, - AccountIdOf, BalanceOf, BalanceWithDust, BlockHash, BlockNumberFor, Config, ContractResult, - Error, EthBlockBuilderIR, EthereumBlock, Event, ExecReturnValue, Pallet, ReceiptGasInfo, - ReceiptInfoData, StorageDeposit, Weight, H160, H256, LOG_TARGET, }; use alloc::vec::Vec; use environmental::environmental; @@ -77,10 +76,10 @@ impl EthereumCallResult { ) -> Self { let effective_gas_price = effective_gas_price.max(Pallet::::evm_base_fee()); - if let Ok(retval) = &output.result { - if retval.did_revert() { - output.result = Err(>::ContractReverted.into()); - } + if let Ok(retval) = &output.result && + retval.did_revert() + { + output.result = Err(>::ContractReverted.into()); } // Refund pre-charged revert event weight if the call succeeds. diff --git a/substrate/frame/revive/src/evm/call.rs b/substrate/frame/revive/src/evm/call.rs index 6e381dbf530ea..0a3db8a366737 100644 --- a/substrate/frame/revive/src/evm/call.rs +++ b/substrate/frame/revive/src/evm/call.rs @@ -18,19 +18,20 @@ //! Functionality to decode an eth transaction into an dispatchable call. use crate::{ + BalanceOf, CallOf, Config, GenericTransaction, LOG_TARGET, Pallet, RUNTIME_PALLETS_ADDR, + Weight, Zero, evm::{ - fees::{compute_max_integer_quotient, InfoT}, - runtime::SetWeightLimit, TYPE_LEGACY, + fees::{InfoT, compute_max_integer_quotient}, + runtime::SetWeightLimit, }, - extract_code_and_data, BalanceOf, CallOf, Config, GenericTransaction, Pallet, Weight, Zero, - LOG_TARGET, RUNTIME_PALLETS_ADDR, + extract_code_and_data, }; use alloc::{boxed::Box, vec::Vec}; use codec::DecodeLimit; use frame_support::MAX_EXTRINSIC_DEPTH; use sp_core::{Get, U256}; -use sp_runtime::{transaction_validity::InvalidTransaction, SaturatedConversion}; +use sp_runtime::{SaturatedConversion, transaction_validity::InvalidTransaction}; /// Result of decoding an eth transaction into a dispatchable call. pub struct CallInfo { @@ -242,9 +243,9 @@ impl GenericTransaction { // the leftover we make available to the deposit collection system let storage_deposit = eth_fee.checked_sub(tx_fee.into()).ok_or_else(|| { - log::error!(target: LOG_TARGET, "The eth_fee={eth_fee:?} is smaller than the tx_fee={tx_fee:?}. This is a bug."); - InvalidTransaction::Payment - })?.saturated_into(); + log::error!(target: LOG_TARGET, "The eth_fee={eth_fee:?} is smaller than the tx_fee={tx_fee:?}. This is a bug."); + InvalidTransaction::Payment + })?.saturated_into(); Ok(CallInfo { call, diff --git a/substrate/frame/revive/src/evm/fees.rs b/substrate/frame/revive/src/evm/fees.rs index b4d20b047caa9..8d586d226eeb1 100644 --- a/substrate/frame/revive/src/evm/fees.rs +++ b/substrate/frame/revive/src/evm/fees.rs @@ -18,19 +18,19 @@ //! Contains the fee types that need to be configured for `pallet-transaction-payment`. use crate::{ + BalanceOf, CallOf, Config, DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Error, + LOG_TARGET, PostDispatchInfo, evm::{ - runtime::{EthExtra, SetWeightLimit}, OnChargeTransactionBalanceOf, + runtime::{EthExtra, SetWeightLimit}, }, - BalanceOf, CallOf, Config, DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Error, - PostDispatchInfo, LOG_TARGET, }; use codec::Encode; use core::marker::PhantomData; use frame_support::{ dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo}, pallet_prelude::Weight, - traits::{fungible::Credit, tokens::Balance, Get, SuppressedDrop}, + traits::{Get, SuppressedDrop, fungible::Credit, tokens::Balance}, weights::WeightToFee, }; use frame_system::Config as SysConfig; @@ -40,11 +40,11 @@ use pallet_transaction_payment::{ }; use sp_arithmetic::{FixedPointOperand, SignedRounding}; use sp_runtime::{ + FixedPointNumber, FixedU128, SaturatedConversion, Saturating, generic::UncheckedExtrinsic, traits::{ Block as BlockT, Dispatchable, ExtensionPostDispatchWeightHandler, TransactionExtension, }, - FixedPointNumber, FixedU128, SaturatedConversion, Saturating, }; type CreditOf = Credit<::AccountId, ::Currency>; diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index a5a962588eb87..630cc492df727 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -16,33 +16,33 @@ // limitations under the License. //! Runtime types for integrating `pallet-revive` with the EVM. use crate::{ + AccountIdOf, AddressMapper, BalanceOf, CallOf, Config, LOG_TARGET, Pallet, Zero, evm::{ + CreateCallMode, api::{GenericTransaction, TransactionSigned}, fees::InfoT, - CreateCallMode, }, - AccountIdOf, AddressMapper, BalanceOf, CallOf, Config, Pallet, Zero, LOG_TARGET, }; use codec::{Decode, DecodeWithMemTracking, Encode}; use frame_support::{ dispatch::{DispatchInfo, GetDispatchInfo}, traits::{ + InherentBuilder, IsSubType, SignedTransactionBuilder, fungible::Balanced, tokens::{Fortitude, Precision, Preservation}, - InherentBuilder, IsSubType, SignedTransactionBuilder, }, }; use pallet_transaction_payment::Config as TxConfig; use scale_info::{StaticTypeInfo, TypeInfo}; use sp_core::U256; use sp_runtime::{ + Debug, OpaqueExtrinsic, Weight, generic::{self, CheckedExtrinsic, ExtrinsicFormat}, traits::{ Checkable, ExtrinsicCall, ExtrinsicLike, ExtrinsicMetadata, LazyExtrinsic, TransactionExtension, }, transaction_validity::{InvalidTransaction, TransactionValidityError}, - Debug, OpaqueExtrinsic, Weight, }; /// Used to set the weight limit argument of a `eth_call` or `eth_instantiate_with_code` call. @@ -128,15 +128,20 @@ where // required by Checkable for `generic::UncheckedExtrinsic` generic::UncheckedExtrinsic, Signature, E::Extension>: Checkable< - Lookup, - Checked = CheckedExtrinsic, CallOf, E::Extension>, - >, + Lookup, + Checked = CheckedExtrinsic, CallOf, E::Extension>, + >, { type Checked = CheckedExtrinsic, CallOf, E::Extension>; fn check(self, lookup: &Lookup) -> Result { if !self.0.is_signed() { if let Some(crate::Call::eth_transact { payload }) = self.0.function.is_sub_type() { + log::trace!( + target: LOG_TARGET, + "eth_transact substrate tx hash: 0x{}", + sp_core::hexdisplay::HexDisplay::from(&sp_core::hashing::blake2_256(&self.encode())), + ); let checked = E::try_into_checked_extrinsic(payload, self.encoded_size())?; return Ok(checked); }; @@ -367,12 +372,12 @@ pub trait EthExtra { mod test { use super::*; use crate::{ + EthTransactInfo, RUNTIME_PALLETS_ADDR, Weight, evm::*, test_utils::*, tests::{ Address, ExtBuilder, RuntimeCall, RuntimeOrigin, SignedExtra, Test, UncheckedExtrinsic, }, - EthTransactInfo, Weight, RUNTIME_PALLETS_ADDR, }; use frame_support::{error::LookupError, traits::fungible::Mutate}; use pallet_revive_fixtures::compile_module; @@ -722,7 +727,9 @@ mod test { #[test] fn contract_deployment_with_nick_method_works() { // Arrange - let raw_transaction_bytes = alloy_core::hex!("0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470"); + let raw_transaction_bytes = alloy_core::hex!( + "0xf9016c8085174876e8008303c4d88080b90154608060405234801561001057600080fd5b50610134806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80634af63f0214602d575b600080fd5b60cf60048036036040811015604157600080fd5b810190602081018135640100000000811115605b57600080fd5b820183602082011115606c57600080fd5b80359060200191846001830284011164010000000083111715608d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925060eb915050565b604080516001600160a01b039092168252519081900360200190f35b6000818351602085016000f5939250505056fea26469706673582212206b44f8a82cb6b156bfcc3dc6aadd6df4eefd204bc928a4397fd15dacf6d5320564736f6c634300060200331b83247000822470" + ); let mut signed_transaction = TransactionSigned::decode(raw_transaction_bytes.as_slice()) .expect("Invalid raw transaction bytes"); diff --git a/substrate/frame/revive/src/evm/tracing.rs b/substrate/frame/revive/src/evm/tracing.rs index eafecf1b34692..7da6b6d43255c 100644 --- a/substrate/frame/revive/src/evm/tracing.rs +++ b/substrate/frame/revive/src/evm/tracing.rs @@ -15,9 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ + Config, evm::{CallTrace, ExecutionTrace, Trace}, tracing::Tracing, - Config, }; mod call_tracing; diff --git a/substrate/frame/revive/src/evm/tracing/call_tracing.rs b/substrate/frame/revive/src/evm/tracing/call_tracing.rs index 06e529c68abc9..66c4b1a307671 100644 --- a/substrate/frame/revive/src/evm/tracing/call_tracing.rs +++ b/substrate/frame/revive/src/evm/tracing/call_tracing.rs @@ -15,10 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ - evm::{decode_revert_reason, CallLog, CallTrace, CallTracerConfig, CallType}, + Code, DispatchError, Weight, + evm::{CallLog, CallTrace, CallTracerConfig, CallType, decode_revert_reason}, primitives::ExecReturnValue, tracing::Tracing, - Code, DispatchError, Weight, }; use alloc::{format, string::ToString, vec::Vec}; use sp_core::{H160, H256, U256}; @@ -81,10 +81,10 @@ impl Tracing for CallTracer { gas_limit: u64, ) { // Increment parent's child call count. - if let Some(&index) = self.current_stack.last() { - if let Some(trace) = self.traces.get_mut(index) { - trace.child_call_count += 1; - } + if let Some(&index) = self.current_stack.last() && + let Some(trace) = self.traces.get_mut(index) + { + trace.child_call_count += 1; } if self.traces.is_empty() || !self.config.only_top_call { diff --git a/substrate/frame/revive/src/evm/tracing/execution_tracing.rs b/substrate/frame/revive/src/evm/tracing/execution_tracing.rs index 9be5b09ede1c0..fb1858b839337 100644 --- a/substrate/frame/revive/src/evm/tracing/execution_tracing.rs +++ b/substrate/frame/revive/src/evm/tracing/execution_tracing.rs @@ -15,13 +15,13 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ + DispatchError, ExecReturnValue, Key, Weight, evm::{ - tracing::Tracing, Bytes, ExecutionStep, ExecutionStepKind, ExecutionTrace, - ExecutionTracerConfig, + Bytes, ExecutionStep, ExecutionStepKind, ExecutionTrace, ExecutionTracerConfig, + tracing::Tracing, }, tracing::{EVMFrameTraceInfo, FrameTraceInfo}, vm::pvm::env::lookup_syscall_index, - DispatchError, ExecReturnValue, Key, Weight, }; use alloc::{ collections::BTreeMap, @@ -229,10 +229,10 @@ impl Tracing for ExecutionTracer { let total_weight = trace_info.weight_consumed().saturating_sub(step.weight_cost); step.weight_cost = total_weight.saturating_sub(pending.child_weight); - if !self.config.disable_syscall_details { - if let ExecutionStepKind::PVMSyscall { returned: ref mut ret, .. } = step.kind { - *ret = returned; - } + if !self.config.disable_syscall_details && + let ExecutionStepKind::PVMSyscall { returned: ref mut ret, .. } = step.kind + { + *ret = returned; } } diff --git a/substrate/frame/revive/src/evm/tracing/prestate_tracing.rs b/substrate/frame/revive/src/evm/tracing/prestate_tracing.rs index c69c7def13e9d..824c92bea932d 100644 --- a/substrate/frame/revive/src/evm/tracing/prestate_tracing.rs +++ b/substrate/frame/revive/src/evm/tracing/prestate_tracing.rs @@ -15,9 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ + AccountInfo, Code, Config, ExecReturnValue, Key, Pallet, PristineCode, Weight, evm::{Bytes, PrestateTrace, PrestateTraceInfo, PrestateTracerConfig}, tracing::Tracing, - AccountInfo, Code, Config, ExecReturnValue, Key, Pallet, PristineCode, Weight, }; use alloc::{ collections::{BTreeMap, BTreeSet}, diff --git a/substrate/frame/revive/src/evm/transfer_with_dust.rs b/substrate/frame/revive/src/evm/transfer_with_dust.rs index 3275b0902d5fb..a30449a51139f 100644 --- a/substrate/frame/revive/src/evm/transfer_with_dust.rs +++ b/substrate/frame/revive/src/evm/transfer_with_dust.rs @@ -18,15 +18,15 @@ //! Transfer with dust functionality for pallet-revive. use crate::{ - address::AddressMapper, exec::AccountIdOf, primitives::BalanceWithDust, storage::AccountInfo, - AccountInfoOf, BalanceOf, Config, Error, LOG_TARGET, + AccountInfoOf, BalanceOf, Config, Error, LOG_TARGET, address::AddressMapper, exec::AccountIdOf, + primitives::BalanceWithDust, storage::AccountInfo, }; use frame_support::{ dispatch::DispatchResult, traits::{ + Get, fungible::Mutate, tokens::{Fortitude, Precision, Preservation}, - Get, }, }; @@ -184,12 +184,12 @@ pub(crate) fn burn_with_dust( mod tests { use super::*; use crate::{ + Config, Error, H160, Pallet, test_utils::{ALICE_ADDR, BOB_ADDR}, - tests::{builder, test_utils::set_balance_with_dust, ExtBuilder, Test}, - Config, Error, Pallet, H160, + tests::{ExtBuilder, Test, builder, test_utils::set_balance_with_dust}, }; use frame_support::{assert_err, traits::Get}; - use sp_runtime::{traits::Zero, DispatchError}; + use sp_runtime::{DispatchError, traits::Zero}; #[test] fn transfer_with_dust_works() { diff --git a/substrate/frame/revive/src/evm/tx_extension.rs b/substrate/frame/revive/src/evm/tx_extension.rs index 607d8a76c10e5..f04a5cbc717be 100644 --- a/substrate/frame/revive/src/evm/tx_extension.rs +++ b/substrate/frame/revive/src/evm/tx_extension.rs @@ -20,14 +20,13 @@ use crate::{CallOf, Config, Origin, OriginFor}; use codec::{Decode, DecodeWithMemTracking, Encode}; use frame_support::{ - pallet_prelude::{InvalidTransaction, TransactionSource}, DebugNoBound, DefaultNoBound, + pallet_prelude::{InvalidTransaction, TransactionSource}, }; use scale_info::TypeInfo; use sp_runtime::{ - impl_tx_ext_default, + Weight, impl_tx_ext_default, traits::{DispatchInfoOf, TransactionExtension, ValidateResult}, - Weight, }; /// An extension that sets the origin to [`Origin::EthTransaction`] in case it originated from an diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 7a2cf628ffede..b67269ebec183 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -16,6 +16,9 @@ // limitations under the License. use crate::{ + AccountInfo, AccountInfoOf, BalanceOf, BalanceWithDust, Code, CodeInfo, CodeInfoOf, + CodeRemoved, Config, ContractInfo, Error, Event, HoldReason, ImmutableData, ImmutableDataOf, + LOG_TARGET, Pallet as Contracts, RuntimeCosts, TrieId, address::{self, AddressMapper}, evm::{block_storage, transfer_with_dust}, limits, @@ -26,9 +29,6 @@ use crate::{ storage::{AccountIdOrAddress, WriteOutcome}, tracing::if_tracing, transient_storage::TransientStorage, - AccountInfo, AccountInfoOf, BalanceOf, BalanceWithDust, Code, CodeInfo, CodeInfoOf, - CodeRemoved, Config, ContractInfo, Error, Event, HoldReason, ImmutableData, ImmutableDataOf, - Pallet as Contracts, RuntimeCosts, TrieId, LOG_TARGET, }; use alloc::{ collections::{BTreeMap, BTreeSet}, @@ -36,31 +36,31 @@ use alloc::{ }; use core::{cmp, fmt::Debug, marker::PhantomData, mem, ops::ControlFlow}; use frame_support::{ + Blake2_128Concat, BoundedVec, DebugNoBound, StorageHasher, crypto::ecdsa::ECDSAExt, dispatch::DispatchResult, ensure, - storage::{with_transaction, TransactionOutcome}, + storage::{TransactionOutcome, with_transaction}, traits::{ + Time, fungible::{Inspect, Mutate}, tokens::Preservation, - Time, }, weights::Weight, - Blake2_128Concat, BoundedVec, DebugNoBound, StorageHasher, }; use frame_system::{ - pallet_prelude::{BlockNumberFor, OriginFor}, Pallet as System, RawOrigin, + pallet_prelude::{BlockNumberFor, OriginFor}, }; use sp_core::{ + ConstU32, Get, H160, H256, U256, ecdsa::Public as ECDSAPublic, sr25519::{Public as SR25519Public, Signature as SR25519Signature}, - ConstU32, Get, H160, H256, U256, }; use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; use sp_runtime::{ - traits::{BadOrigin, Saturating, TrailingZeroInput}, DispatchError, SaturatedConversion, + traits::{BadOrigin, Saturating, TrailingZeroInput}, }; #[cfg(test)] @@ -692,11 +692,7 @@ enum ExecutableOrPrecompile, Env> { impl, Env> ExecutableOrPrecompile { fn as_executable(&self) -> Option<&E> { - if let Self::Executable(executable) = self { - Some(executable) - } else { - None - } + if let Self::Executable(executable) = self { Some(executable) } else { None } } fn is_pvm(&self) -> bool { @@ -707,20 +703,12 @@ impl, Env> ExecutableOrPrecompile { } fn as_precompile(&self) -> Option<&PrecompileInstance> { - if let Self::Precompile { instance, .. } = self { - Some(instance) - } else { - None - } + if let Self::Precompile { instance, .. } = self { Some(instance) } else { None } } #[cfg(any(feature = "runtime-benchmarks", test))] fn into_executable(self) -> Option { - if let Self::Executable(executable) = self { - Some(executable) - } else { - None - } + if let Self::Executable(executable) = self { Some(executable) } else { None } } } @@ -811,30 +799,21 @@ macro_rules! top_frame_mut { impl CachedContract { /// Return `Some(ContractInfo)` if the contract is in cached state. `None` otherwise. fn into_contract(self) -> Option> { - if let CachedContract::Cached(contract) = self { - Some(contract) - } else { - None - } + if let CachedContract::Cached(contract) = self { Some(contract) } else { None } } /// Return `Some(&mut ContractInfo)` if the contract is in cached state. `None` otherwise. fn as_contract(&mut self) -> Option<&mut ContractInfo> { - if let CachedContract::Cached(contract) = self { - Some(contract) - } else { - None - } + if let CachedContract::Cached(contract) = self { Some(contract) } else { None } } /// Load the `contract_info` from storage if necessary. fn load(&mut self, account_id: &T::AccountId) { - if let CachedContract::Invalidated = self { - if let Some(contract) = + if let CachedContract::Invalidated = self && + let Some(contract) = AccountInfo::::load_contract(&T::AddressMapper::to_address(account_id)) - { - *self = CachedContract::Cached(contract); - } + { + *self = CachedContract::Cached(contract); } } @@ -959,10 +938,10 @@ where let result = stack .run(executable, input_data) .map(|_| (address, stack.first_frame.last_frame_output)); - if let Ok((contract, ref output)) = result { - if !output.did_revert() { - Contracts::::deposit_event(Event::Instantiated { deployer, contract }); - } + if let Ok((contract, output)) = &result && + !output.did_revert() + { + Contracts::::deposit_event(Event::Instantiated { deployer, contract: *contract }); } log::trace!(target: LOG_TARGET, "instantiate finished with: {result:?}"); result @@ -1361,17 +1340,16 @@ where // account. // - Only when not delegate calling we are executing in the context of the pre-compile. // Pre-compiles itself cannot delegate call. - if let Some(precompile) = executable.as_precompile() { - if precompile.has_contract_info() && - frame.delegate.is_none() && - !>::account_exists(account_id) - { - // prefix matching pre-compiles cannot have a contract info - // hence we only mint once per pre-compile - T::Currency::mint_into(account_id, T::Currency::minimum_balance())?; - // make sure the pre-compile does not destroy its account by accident - >::inc_consumers(account_id)?; - } + if let Some(precompile) = executable.as_precompile() && + precompile.has_contract_info() && + frame.delegate.is_none() && + !>::account_exists(account_id) + { + // prefix matching pre-compiles cannot have a contract info + // hence we only mint once per pre-compile + T::Currency::mint_into(account_id, T::Currency::minimum_balance())?; + // make sure the pre-compile does not destroy its account by accident + >::inc_consumers(account_id)?; } let mut code_deposit = executable diff --git a/substrate/frame/revive/src/exec/mock_ext.rs b/substrate/frame/revive/src/exec/mock_ext.rs index cd98ba4205f01..50544e08fc12f 100644 --- a/substrate/frame/revive/src/exec/mock_ext.rs +++ b/substrate/frame/revive/src/exec/mock_ext.rs @@ -17,6 +17,8 @@ #![cfg(test)] use crate::{ + BalanceOf, Code, CodeRemoved, Config, DispatchResult, ExecReturnValue, ImmutableData, + ReentrancyProtection, exec::{ AccountIdOf, CallResources, ExecError, Ext, Key, Origin, PrecompileExt, PrecompileWithInfoExt, @@ -25,8 +27,6 @@ use crate::{ precompiles::Diff, storage::{ContractInfo, WriteOutcome}, transient_storage::TransientStorage, - BalanceOf, Code, CodeRemoved, Config, DispatchResult, ExecReturnValue, ImmutableData, - ReentrancyProtection, }; use alloc::vec::Vec; use core::marker::PhantomData; diff --git a/substrate/frame/revive/src/exec/tests.rs b/substrate/frame/revive/src/exec/tests.rs index 90e2f6e7b0420..0855d144a6311 100644 --- a/substrate/frame/revive/src/exec/tests.rs +++ b/substrate/frame/revive/src/exec/tests.rs @@ -23,14 +23,14 @@ #[cfg(test)] use super::*; use crate::{ + AddressMapper, Error, Pallet, ReentrancyProtection, exec::ExportedFunction::*, metering::TransactionMeter, test_utils::*, tests::{ - test_utils::{get_balance, place_contract, set_balance}, ExtBuilder, RuntimeEvent as MetaEvent, Test, + test_utils::{get_balance, place_contract, set_balance}, }, - AddressMapper, Error, Pallet, ReentrancyProtection, }; use assert_matches::assert_matches; use frame_support::{assert_err, assert_ok, parameter_types}; @@ -1377,17 +1377,18 @@ fn in_memory_changes_not_discarded() { exec_success() }); let code_charlie = MockLoader::insert(Call, |ctx, _| { - assert!(ctx - .ext - .call( - &Default::default(), - &BOB_ADDR, - U256::zero(), - vec![99], - ReentrancyProtection::AllowReentry, - false - ) - .is_ok()); + assert!( + ctx.ext + .call( + &Default::default(), + &BOB_ADDR, + U256::zero(), + vec![99], + ReentrancyProtection::AllowReentry, + false + ) + .is_ok() + ); exec_trapped() }); @@ -2231,17 +2232,18 @@ fn get_transient_storage_works() { exec_success() }); let code_charlie = MockLoader::insert(Call, |ctx, _| { - assert!(ctx - .ext - .call( - &Default::default(), - &BOB_ADDR, - U256::zero(), - vec![99], - ReentrancyProtection::AllowReentry, - false - ) - .is_ok()); + assert!( + ctx.ext + .call( + &Default::default(), + &BOB_ADDR, + U256::zero(), + vec![99], + ReentrancyProtection::AllowReentry, + false + ) + .is_ok() + ); // CHARLIE can not read BOB`s storage. assert_eq!(ctx.ext.get_transient_storage(storage_key_1), None); exec_success() @@ -2337,17 +2339,18 @@ fn rollback_transient_storage_works() { exec_success() }); let code_charlie = MockLoader::insert(Call, |ctx, _| { - assert!(ctx - .ext - .call( - &Default::default(), - &BOB_ADDR, - U256::zero(), - vec![99], - ReentrancyProtection::AllowReentry, - false - ) - .is_ok()); + assert!( + ctx.ext + .call( + &Default::default(), + &BOB_ADDR, + U256::zero(), + vec![99], + ReentrancyProtection::AllowReentry, + false + ) + .is_ok() + ); exec_trapped() }); @@ -2518,17 +2521,18 @@ fn last_frame_output_works_on_nested_call() { &ExecReturnValue { flags: ReturnFlags::empty(), data: vec![] } ); - assert!(ctx - .ext - .call( - &Default::default(), - &BOB_ADDR, - U256::zero(), - vec![99], - ReentrancyProtection::AllowReentry, - false - ) - .is_ok()); + assert!( + ctx.ext + .call( + &Default::default(), + &BOB_ADDR, + U256::zero(), + vec![99], + ReentrancyProtection::AllowReentry, + false + ) + .is_ok() + ); assert_eq!( ctx.ext.last_frame_output(), &ExecReturnValue { flags: ReturnFlags::empty(), data: vec![127] } diff --git a/substrate/frame/revive/src/impl_fungibles.rs b/substrate/frame/revive/src/impl_fungibles.rs index b4dda778bb9e0..4665391d931e6 100644 --- a/substrate/frame/revive/src/impl_fungibles.rs +++ b/substrate/frame/revive/src/impl_fungibles.rs @@ -24,25 +24,25 @@ #![cfg(any(feature = "std", feature = "runtime-benchmarks", test))] -use crate::{metering::TransactionLimits, OriginFor}; +use crate::{OriginFor, metering::TransactionLimits}; use alloy_core::{ primitives::{Address, U256 as EU256}, sol_types::*, }; use frame_support::{ + PalletId, traits::{ + OriginTrait, tokens::{ - fungible, fungibles, DepositConsequence, Fortitude, Precision, Preservation, - Provenance, WithdrawConsequence, + DepositConsequence, Fortitude, Precision, Preservation, Provenance, + WithdrawConsequence, fungible, fungibles, }, - OriginTrait, }, - PalletId, }; use sp_core::{H160, U256}; -use sp_runtime::{traits::AccountIdConversion, DispatchError}; +use sp_runtime::{DispatchError, traits::AccountIdConversion}; -use super::{address::AddressMapper, pallet, Config, ContractResult, ExecConfig, Pallet, Weight}; +use super::{Config, ContractResult, ExecConfig, Pallet, Weight, address::AddressMapper, pallet}; use ethereum_standards::IERC20; const WEIGHT_LIMIT: Weight = Weight::from_parts(10_000_000_000, 1000_000); @@ -77,12 +77,10 @@ impl fungibles::Inspect<::AccountId> for P data, &ExecConfig::new_substrate_tx(), ); - if let Ok(return_value) = result { - if let Ok(eu256) = EU256::abi_decode_validate(&return_value.data) { - eu256.to::() - } else { - 0 - } + if let Ok(return_value) = result && + let Ok(eu256) = EU256::abi_decode_validate(&return_value.data) + { + eu256.to::() } else { 0 } @@ -115,12 +113,10 @@ impl fungibles::Inspect<::AccountId> for P data, &ExecConfig::new_substrate_tx(), ); - if let Ok(return_value) = result { - if let Ok(eu256) = EU256::abi_decode_validate(&return_value.data) { - eu256.to::() - } else { - 0 - } + if let Ok(return_value) = result && + let Ok(eu256) = EU256::abi_decode_validate(&return_value.data) + { + eu256.to::() } else { 0 } @@ -288,12 +284,12 @@ impl fungibles::Unbalanced<::AccountId> fo mod tests { use super::*; use crate::{ - test_utils::{builder::*, ALICE}, - tests::{Contracts, ExtBuilder, RuntimeOrigin, Test}, AccountInfoOf, Code, + test_utils::{ALICE, builder::*}, + tests::{Contracts, ExtBuilder, RuntimeOrigin, Test}, }; use frame_support::assert_ok; - use pallet_revive_fixtures::{compile_module_with_type, FixtureType}; + use pallet_revive_fixtures::{FixtureType, compile_module_with_type}; #[test] fn call_erc20_contract() { diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index d6348ee58f6f7..eebf86c56adc5 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -48,20 +48,21 @@ pub mod weights; use crate::{ evm::{ - block_hash::EthereumBlockBuilderIR, block_storage, fees::InfoT as FeeInfo, - runtime::SetWeightLimit, CallTracer, CreateCallMode, ExecutionTracer, GenericTransaction, - PrestateTracer, Trace, Tracer, TracerType, TYPE_EIP1559, + CallTracer, CreateCallMode, ExecutionTracer, GenericTransaction, PrestateTracer, + TYPE_EIP1559, Trace, Tracer, TracerType, block_hash::EthereumBlockBuilderIR, block_storage, + fees::InfoT as FeeInfo, runtime::SetWeightLimit, }, exec::{AccountIdOf, ExecError, ReentrancyProtection, Stack as ExecStack}, storage::{AccountType, DeletionQueueManager}, tracing::if_tracing, - vm::{pvm::extract_code_and_data, CodeInfo, RuntimeCosts}, + vm::{CodeInfo, RuntimeCosts, pvm::extract_code_and_data}, weightinfo_extension::OnFinalizeBlockParts, }; use alloc::{boxed::Box, format, vec}; use codec::{Codec, Decode, Encode}; use environmental::*; use frame_support::{ + BoundedVec, dispatch::{ DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, Pays, PostDispatchInfo, RawOrigin, @@ -69,35 +70,33 @@ use frame_support::{ ensure, pallet_prelude::DispatchClass, traits::{ + ConstU32, ConstU64, EnsureOrigin, Get, IsSubType, IsType, OriginTrait, fungible::{Balanced, Inspect, Mutate, MutateHold}, tokens::Balance, - ConstU32, ConstU64, EnsureOrigin, Get, IsSubType, IsType, OriginTrait, }, weights::WeightMeter, - BoundedVec, }; use frame_system::{ - ensure_signed, + Pallet as System, ensure_signed, pallet_prelude::{BlockNumberFor, OriginFor}, - Pallet as System, }; use scale_info::TypeInfo; use sp_runtime::{ + AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion, traits::{ BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom, UniqueSaturatedInto, Zero, }, - AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion, }; pub use crate::{ address::{ - create1, create2, is_eth_derived, AccountId32Mapper, AddressMapper, TestAccountMapper, + AccountId32Mapper, AddressMapper, TestAccountMapper, create1, create2, is_eth_derived, }, debug::DebugSettings, evm::{ - block_hash::ReceiptGasInfo, Address as EthAddress, Block as EthBlock, DryRunConfig, - ReceiptInfo, + Address as EthAddress, Block as EthBlock, DryRunConfig, ReceiptInfo, + block_hash::ReceiptGasInfo, }, exec::{CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin}, limits::TRANSIENT_STORAGE_BYTES as TRANSIENT_STORAGE_LIMIT, @@ -114,7 +113,7 @@ pub use codec; pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight}; pub use frame_system::{self, limits::BlockWeights}; pub use primitives::*; -pub use sp_core::{keccak_256, H160, H256, U256}; +pub use sp_core::{H160, H256, U256, keccak_256}; pub use sp_runtime; pub use weights::WeightInfo; @@ -1108,10 +1107,10 @@ pub mod pallet { &ExecConfig::new_substrate_tx(), ); - if let Ok(return_value) = &output.result { - if return_value.did_revert() { - output.result = Err(>::ContractReverted.into()); - } + if let Ok(return_value) = &output.result && + return_value.did_revert() + { + output.result = Err(>::ContractReverted.into()); } dispatch_result( output.result, @@ -1152,10 +1151,10 @@ pub mod pallet { salt, &ExecConfig::new_substrate_tx(), ); - if let Ok(retval) = &output.result { - if retval.result.did_revert() { - output.result = Err(>::ContractReverted.into()); - } + if let Ok(retval) = &output.result && + retval.result.did_revert() + { + output.result = Err(>::ContractReverted.into()); } dispatch_result( output.result.map(|result| result.result), @@ -1220,10 +1219,10 @@ pub mod pallet { salt, &ExecConfig::new_substrate_tx(), ); - if let Ok(retval) = &output.result { - if retval.result.did_revert() { - output.result = Err(>::ContractReverted.into()); - } + if let Ok(retval) = &output.result && + retval.result.did_revert() + { + output.result = Err(>::ContractReverted.into()); } dispatch_result( output.result.map(|result| result.result), @@ -1600,7 +1599,6 @@ impl Pallet { Ok(transaction_meter) => transaction_meter, Err(error) => return ContractResult { result: Err(error), ..Default::default() }, }; - let mut storage_deposit = Default::default(); let try_call = || { @@ -2040,11 +2038,7 @@ impl Pallet { pub fn eth_block_hash_from_number(number: U256) -> Option { let number = BlockNumberFor::::try_from(number).ok()?; let hash = >::get(number); - if hash == H256::zero() { - None - } else { - Some(hash) - } + if hash == H256::zero() { None } else { Some(hash) } } /// The details needed to reconstruct the receipt information offchain. diff --git a/substrate/frame/revive/src/metering/gas.rs b/substrate/frame/revive/src/metering/gas.rs index 34a811ac1e79c..7cee692c76940 100644 --- a/substrate/frame/revive/src/metering/gas.rs +++ b/substrate/frame/revive/src/metering/gas.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License -use crate::{evm::fees::InfoT, BalanceOf, Config, StorageDeposit}; +use crate::{BalanceOf, Config, StorageDeposit, evm::fees::InfoT}; use frame_support::DebugNoBound; use sp_core::Get; use sp_runtime::{FixedPointNumber, Saturating}; @@ -49,11 +49,7 @@ impl SignedGas { /// /// Ensures the invariant that `Negative` must not be used for zero pub fn safe_new_negative(amount: BalanceOf) -> Self { - if amount == Default::default() { - Positive(amount) - } else { - Negative(amount) - } + if amount == Default::default() { Positive(amount) } else { Negative(amount) } } /// Transform a weight fee into a gas amount. diff --git a/substrate/frame/revive/src/metering/mod.rs b/substrate/frame/revive/src/metering/mod.rs index 52d4deed9c7ff..d9137bdb8ad6b 100644 --- a/substrate/frame/revive/src/metering/mod.rs +++ b/substrate/frame/revive/src/metering/mod.rs @@ -24,8 +24,8 @@ mod weight; mod tests; use crate::{ - evm::fees::InfoT, exec::CallResources, storage::ContractInfo, vm::evm::Halt, BalanceOf, Config, - Error, ExecConfig, ExecOrigin as Origin, StorageDeposit, LOG_TARGET, + BalanceOf, Config, Error, ExecConfig, ExecOrigin as Origin, LOG_TARGET, StorageDeposit, + evm::fees::InfoT, exec::CallResources, storage::ContractInfo, vm::evm::Halt, }; pub use gas::SignedGas; diff --git a/substrate/frame/revive/src/metering/storage.rs b/substrate/frame/revive/src/metering/storage.rs index 66809bd57fed9..05c134c38bed4 100644 --- a/substrate/frame/revive/src/metering/storage.rs +++ b/substrate/frame/revive/src/metering/storage.rs @@ -22,15 +22,15 @@ mod tests; use super::{Nested, Root, State}; use crate::{ - storage::ContractInfo, BalanceOf, Config, ExecConfig, ExecOrigin as Origin, HoldReason, Pallet, - StorageDeposit as Deposit, + BalanceOf, Config, ExecConfig, ExecOrigin as Origin, HoldReason, Pallet, + StorageDeposit as Deposit, storage::ContractInfo, }; use alloc::vec::Vec; use core::{marker::PhantomData, mem}; -use frame_support::{traits::Get, DebugNoBound, DefaultNoBound}; +use frame_support::{DebugNoBound, DefaultNoBound, traits::Get}; use sp_runtime::{ - traits::{Saturating, Zero}, DispatchError, FixedPointNumber, FixedU128, + traits::{Saturating, Zero}, }; #[cfg(test)] diff --git a/substrate/frame/revive/src/metering/tests.rs b/substrate/frame/revive/src/metering/tests.rs index c246048a4fc19..712a337b87c89 100644 --- a/substrate/frame/revive/src/metering/tests.rs +++ b/substrate/frame/revive/src/metering/tests.rs @@ -16,16 +16,16 @@ // limitations under the License. use crate::{ - storage::AccountInfo, - test_utils::{builder::Contract, ALICE, ALICE_ADDR}, - tests::{builder, ExtBuilder, Test}, BalanceOf, CallResources, Code, Config, EthTxInfo, StorageDeposit, TransactionLimits, TransactionMeter, WeightToken, + storage::AccountInfo, + test_utils::{ALICE, ALICE_ADDR, builder::Contract}, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::SolCall; use frame_support::traits::fungible::Mutate; use pallet_revive_fixtures::{ - compile_module_with_type, CatchConstructorTest, DepositPrecompile, FixtureType, + CatchConstructorTest, DepositPrecompile, FixtureType, compile_module_with_type, }; use sp_runtime::{FixedU128, Weight}; use test_case::test_case; diff --git a/substrate/frame/revive/src/metering/weight.rs b/substrate/frame/revive/src/metering/weight.rs index ec094e69287c8..c31b1fae29351 100644 --- a/substrate/frame/revive/src/metering/weight.rs +++ b/substrate/frame/revive/src/metering/weight.rs @@ -18,9 +18,9 @@ #[cfg(test)] mod tests; -use crate::{vm::evm::Halt, weights::WeightInfo, Config, Error}; +use crate::{Config, Error, vm::evm::Halt, weights::WeightInfo}; use core::{marker::PhantomData, ops::ControlFlow}; -use frame_support::{weights::Weight, DefaultNoBound}; +use frame_support::{DefaultNoBound, weights::Weight}; use sp_runtime::DispatchError; #[cfg(test)] diff --git a/substrate/frame/revive/src/migrations/v1.rs b/substrate/frame/revive/src/migrations/v1.rs index e4afa98d99c86..aa02842c9f646 100644 --- a/substrate/frame/revive/src/migrations/v1.rs +++ b/substrate/frame/revive/src/migrations/v1.rs @@ -22,7 +22,7 @@ extern crate alloc; use super::PALLET_MIGRATIONS_ID; -use crate::{weights::WeightInfo, AccountInfo, AccountInfoOf, Config, H160}; +use crate::{AccountInfo, AccountInfoOf, Config, H160, weights::WeightInfo}; use frame_support::{ migrations::{MigrationId, SteppedMigration, SteppedMigrationError}, pallet_prelude::PhantomData, @@ -38,8 +38,8 @@ use alloc::vec::Vec; /// Module containing the old storage items. pub mod old { use super::Config; - use crate::{pallet::Pallet, ContractInfo, H160}; - use frame_support::{storage_alias, Identity}; + use crate::{ContractInfo, H160, pallet::Pallet}; + use frame_support::{Identity, storage_alias}; #[storage_alias] /// The storage item that is being migrated from. @@ -132,8 +132,8 @@ impl SteppedMigration for Migration { #[test] fn migrate_to_v1() { use crate::{ - tests::{ExtBuilder, Test}, ContractInfo, + tests::{ExtBuilder, Test}, }; ExtBuilder::default().build().execute_with(|| { for i in 0..10u8 { diff --git a/substrate/frame/revive/src/migrations/v2.rs b/substrate/frame/revive/src/migrations/v2.rs index bf193228a5c20..0fe678aec6d18 100644 --- a/substrate/frame/revive/src/migrations/v2.rs +++ b/substrate/frame/revive/src/migrations/v2.rs @@ -23,7 +23,7 @@ extern crate alloc; use super::PALLET_MIGRATIONS_ID; -use crate::{vm::BytecodeType, weights::WeightInfo, Config, Pallet, H256, LOG_TARGET}; +use crate::{Config, H256, LOG_TARGET, Pallet, vm::BytecodeType, weights::WeightInfo}; use frame_support::{ migrations::{MigrationId, SteppedMigration, SteppedMigrationError}, pallet_prelude::PhantomData, @@ -43,9 +43,9 @@ use frame_support::{sp_runtime::TryRuntimeError, traits::fungible::InspectHold}; /// Module containing the old storage items. mod old { use super::Config; - use crate::{pallet::Pallet, AccountIdOf, BalanceOf, H256}; + use crate::{AccountIdOf, BalanceOf, H256, pallet::Pallet}; use codec::{Decode, Encode}; - use frame_support::{storage_alias, Identity}; + use frame_support::{Identity, storage_alias}; #[derive(Clone, Encode, Decode)] pub struct CodeInfo { @@ -65,9 +65,9 @@ mod old { mod new { use super::{BytecodeType, Config}; - use crate::{pallet::Pallet, AccountIdOf, BalanceOf, H256}; + use crate::{AccountIdOf, BalanceOf, H256, pallet::Pallet}; use codec::{Decode, Encode}; - use frame_support::{storage_alias, DebugNoBound, Identity}; + use frame_support::{DebugNoBound, Identity, storage_alias}; #[derive(PartialEq, Eq, DebugNoBound, Encode, Decode)] pub struct CodeInfo { @@ -171,7 +171,7 @@ impl SteppedMigration for Migration { #[cfg(feature = "try-runtime")] fn post_upgrade(prev: Vec) -> Result<(), TryRuntimeError> { use codec::Decode; - use sp_runtime::{traits::Zero, Saturating}; + use sp_runtime::{Saturating, traits::Zero}; // Check the state of the storage after the migration. let prev_map = BTreeMap::>::decode(&mut &prev[..]) @@ -234,11 +234,13 @@ impl Migration { let migrated = new::CodeInfoOf::::get(code_hash).expect("Failed to get migrated CodeInfo"); - assert!(::Currency::balance_on_hold( - &crate::HoldReason::CodeUploadDepositReserve.into(), - &old_code_info.owner - ) - .is_zero()); + assert!( + ::Currency::balance_on_hold( + &crate::HoldReason::CodeUploadDepositReserve.into(), + &old_code_info.owner + ) + .is_zero() + ); assert_eq!( migrated, @@ -258,8 +260,8 @@ impl Migration { #[test] fn migrate_to_v2() { use crate::{ - tests::{ExtBuilder, Test}, AccountIdOf, + tests::{ExtBuilder, Test}, }; use alloc::collections::BTreeMap; diff --git a/substrate/frame/revive/src/mock.rs b/substrate/frame/revive/src/mock.rs index b2395c12326df..a7c7fb2a7cbfe 100644 --- a/substrate/frame/revive/src/mock.rs +++ b/substrate/frame/revive/src/mock.rs @@ -22,7 +22,7 @@ use frame_system::pallet_prelude::OriginFor; use sp_core::{H160, U256}; -use crate::{exec::Origin, pallet, DelegateInfo, ExecReturnValue}; +use crate::{DelegateInfo, ExecReturnValue, exec::Origin, pallet}; /// A trait that provides hooks for mocking EVM contract calls and callers. /// This is useful for testing and simulating contract interactions within foundry forge tests. diff --git a/substrate/frame/revive/src/precompiles.rs b/substrate/frame/revive/src/precompiles.rs index 2647a1ddf51ad..07a9d25088fd2 100644 --- a/substrate/frame/revive/src/precompiles.rs +++ b/substrate/frame/revive/src/precompiles.rs @@ -30,17 +30,17 @@ mod builtin; mod tests; pub use crate::{ + AddressMapper, TransactionLimits, exec::{ExecError, PrecompileExt as Ext, PrecompileWithInfoExt as ExtWithInfo}, metering::{Diff, Token}, vm::RuntimeCosts, - AddressMapper, TransactionLimits, }; pub use alloy_core as alloy; pub use sp_core::{H160, H256, U256}; use crate::{ - exec::ExecResult, precompiles::builtin::Builtin, primitives::ExecReturnValue, Config, - Error as CrateError, + Config, Error as CrateError, exec::ExecResult, precompiles::builtin::Builtin, + primitives::ExecReturnValue, }; use alloc::vec::Vec; use alloy::sol_types::{Panic, PanicKind, Revert, SolError, SolInterface}; @@ -604,8 +604,8 @@ impl BuiltinAddressMatcher { #[cfg(any(test, feature = "runtime-benchmarks"))] pub mod run { pub use crate::{ - call_builder::{CallSetup, Contract, VmBinaryModule}, BalanceOf, MomentOf, + call_builder::{CallSetup, Contract, VmBinaryModule}, }; pub use sp_core::{H256, U256}; diff --git a/substrate/frame/revive/src/precompiles/builtin.rs b/substrate/frame/revive/src/precompiles/builtin.rs index 1654302ed2efc..862ae10d6de86 100644 --- a/substrate/frame/revive/src/precompiles/builtin.rs +++ b/substrate/frame/revive/src/precompiles/builtin.rs @@ -32,8 +32,8 @@ mod benchmarking; #[cfg(feature = "runtime-benchmarks")] use crate::{ - precompiles::{ExtWithInfo, Instance, Precompiles}, Config, + precompiles::{ExtWithInfo, Instance, Precompiles}, }; #[cfg(feature = "runtime-benchmarks")] diff --git a/substrate/frame/revive/src/precompiles/builtin/benchmarking.rs b/substrate/frame/revive/src/precompiles/builtin/benchmarking.rs index f499d1a682bb0..40b1a137cad53 100644 --- a/substrate/frame/revive/src/precompiles/builtin/benchmarking.rs +++ b/substrate/frame/revive/src/precompiles/builtin/benchmarking.rs @@ -16,8 +16,8 @@ // limitations under the License. use crate::{ - precompiles::{BuiltinAddressMatcher, BuiltinPrecompile, Error, Ext, ExtWithInfo}, Config, + precompiles::{BuiltinAddressMatcher, BuiltinPrecompile, Error, Ext, ExtWithInfo}, }; use alloc::vec::Vec; use alloy_core::sol; diff --git a/substrate/frame/revive/src/precompiles/builtin/blake2f.rs b/substrate/frame/revive/src/precompiles/builtin/blake2f.rs index 9fd2d67b1581c..cdf9433942516 100644 --- a/substrate/frame/revive/src/precompiles/builtin/blake2f.rs +++ b/substrate/frame/revive/src/precompiles/builtin/blake2f.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/bn128.rs b/substrate/frame/revive/src/precompiles/builtin/bn128.rs index b091800c799da..3b0104603c962 100644 --- a/substrate/frame/revive/src/precompiles/builtin/bn128.rs +++ b/substrate/frame/revive/src/precompiles/builtin/bn128.rs @@ -16,12 +16,12 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; -use bn::{pairing_batch, AffineG1, AffineG2, Fq, Fq2, Group, Gt, G1, G2}; +use bn::{AffineG1, AffineG2, Fq, Fq2, G1, G2, Group, Gt, pairing_batch}; use core::{marker::PhantomData, num::NonZero}; use sp_core::U256; use sp_runtime::DispatchError; @@ -155,11 +155,7 @@ impl PrimitivePrecompile for Bn128Pairing { let mul = pairing_batch(&vals); - if mul == Gt::one() { - U256::one() - } else { - U256::zero() - } + if mul == Gt::one() { U256::one() } else { U256::zero() } }; let buf = ret_val.to_big_endian(); diff --git a/substrate/frame/revive/src/precompiles/builtin/ecrecover.rs b/substrate/frame/revive/src/precompiles/builtin/ecrecover.rs index 6d13b84d01f8d..25cae2fce202b 100644 --- a/substrate/frame/revive/src/precompiles/builtin/ecrecover.rs +++ b/substrate/frame/revive/src/precompiles/builtin/ecrecover.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/identity.rs b/substrate/frame/revive/src/precompiles/builtin/identity.rs index 899e8b200fcd4..91084e74943d3 100644 --- a/substrate/frame/revive/src/precompiles/builtin/identity.rs +++ b/substrate/frame/revive/src/precompiles/builtin/identity.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/modexp.rs b/substrate/frame/revive/src/precompiles/builtin/modexp.rs index 8e3911f0bf5a6..c0238840832b0 100644 --- a/substrate/frame/revive/src/precompiles/builtin/modexp.rs +++ b/substrate/frame/revive/src/precompiles/builtin/modexp.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::{vec, vec::Vec}; use core::{cmp::max, marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/p256_verify.rs b/substrate/frame/revive/src/precompiles/builtin/p256_verify.rs index ae08ab28c9b44..21d996e32fee6 100644 --- a/substrate/frame/revive/src/precompiles/builtin/p256_verify.rs +++ b/substrate/frame/revive/src/precompiles/builtin/p256_verify.rs @@ -24,9 +24,9 @@ //! P256 elliptic curve. use crate::{ + Config, U256, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, U256, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/point_eval.rs b/substrate/frame/revive/src/precompiles/builtin/point_eval.rs index 69a87e7396cbb..e8913bd274c1f 100644 --- a/substrate/frame/revive/src/precompiles/builtin/point_eval.rs +++ b/substrate/frame/revive/src/precompiles/builtin/point_eval.rs @@ -16,8 +16,8 @@ // limitations under the License. use crate::{ - precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, Config, Error as CrateError, + precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/ripemd160.rs b/substrate/frame/revive/src/precompiles/builtin/ripemd160.rs index 288a8159fecf6..5b23d216bb0ad 100644 --- a/substrate/frame/revive/src/precompiles/builtin/ripemd160.rs +++ b/substrate/frame/revive/src/precompiles/builtin/ripemd160.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/sha256.rs b/substrate/frame/revive/src/precompiles/builtin/sha256.rs index e977cb96894b5..718103034de95 100644 --- a/substrate/frame/revive/src/precompiles/builtin/sha256.rs +++ b/substrate/frame/revive/src/precompiles/builtin/sha256.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ + Config, precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile}, vm::RuntimeCosts, - Config, }; use alloc::vec::Vec; use core::{marker::PhantomData, num::NonZero}; diff --git a/substrate/frame/revive/src/precompiles/builtin/storage.rs b/substrate/frame/revive/src/precompiles/builtin/storage.rs index 5f6cc05133b41..1ccd9335dc8a4 100644 --- a/substrate/frame/revive/src/precompiles/builtin/storage.rs +++ b/substrate/frame/revive/src/precompiles/builtin/storage.rs @@ -16,16 +16,15 @@ // limitations under the License. use crate::{ - limits, + Config, Key, limits, precompiles::{BuiltinAddressMatcher, BuiltinPrecompile, Error, Ext}, storage::WriteOutcome, vm::RuntimeCosts, - Config, Key, }; use alloc::vec::Vec; use alloy_core::sol_types::SolValue; use core::{marker::PhantomData, num::NonZero}; -use pallet_revive_uapi::{precompiles::storage::IStorage, StorageFlags}; +use pallet_revive_uapi::{StorageFlags, precompiles::storage::IStorage}; use sp_core::hexdisplay::AsBytesRef; pub struct Storage(PhantomData); diff --git a/substrate/frame/revive/src/precompiles/builtin/system.rs b/substrate/frame/revive/src/precompiles/builtin/system.rs index 981cb31a703fa..bcf6128d75f8b 100644 --- a/substrate/frame/revive/src/precompiles/builtin/system.rs +++ b/substrate/frame/revive/src/precompiles/builtin/system.rs @@ -16,10 +16,10 @@ // limitations under the License. use crate::{ + Config, H160, address::AddressMapper, precompiles::{BuiltinAddressMatcher, BuiltinPrecompile, Error, Ext}, vm::RuntimeCosts, - Config, H160, }; use alloc::vec::Vec; use alloy_core::sol_types::SolValue; @@ -126,13 +126,13 @@ mod tests { use super::*; use crate::{ address::AddressMapper, - call_builder::{caller_funding, CallSetup}, + call_builder::{CallSetup, caller_funding}, metering::Token, pallet, precompiles::{ - alloy::sol_types::{sol_data::Bytes, SolType}, - tests::run_test_vectors, BuiltinPrecompile, + alloy::sol_types::{SolType, sol_data::Bytes}, + tests::run_test_vectors, }, test_utils::ALICE, tests::{ExtBuilder, Test}, diff --git a/substrate/frame/revive/src/primitives.rs b/substrate/frame/revive/src/primitives.rs index 162c22e7eb16b..b6450b280aa95 100644 --- a/substrate/frame/revive/src/primitives.rs +++ b/substrate/frame/revive/src/primitives.rs @@ -18,19 +18,19 @@ //! A crate that hosts a common definitions that are relevant for the pallet-revive. use crate::{ - evm::DryRunConfig, mock::MockHandler, storage::WriteOutcome, - transient_storage::TransientStorage, BalanceOf, Config, Time, H160, U256, + BalanceOf, Config, H160, Time, U256, evm::DryRunConfig, mock::MockHandler, + storage::WriteOutcome, transient_storage::TransientStorage, }; use alloc::{boxed::Box, fmt::Debug, string::String, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use core::cell::RefCell; -use frame_support::{traits::tokens::Balance, weights::Weight, DefaultNoBound}; +use frame_support::{DefaultNoBound, traits::tokens::Balance, weights::Weight}; use pallet_revive_uapi::ReturnFlags; use scale_info::TypeInfo; use sp_core::Get; use sp_runtime::{ - traits::{One, Saturating, Zero}, DispatchError, + traits::{One, Saturating, Zero}, }; /// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and @@ -172,11 +172,7 @@ impl BalanceWithDust { /// Returns the Balance rounded to the nearest whole unit if the dust is non-zero. pub fn into_rounded_balance(self) -> Balance { - if self.dust == 0 { - self.value - } else { - self.value.saturating_add(Balance::one()) - } + if self.dust == 0 { self.value } else { self.value.saturating_add(Balance::one()) } } } diff --git a/substrate/frame/revive/src/storage.rs b/substrate/frame/revive/src/storage.rs index 64fad423330cd..ba5758a34c1cb 100644 --- a/substrate/frame/revive/src/storage.rs +++ b/substrate/frame/revive/src/storage.rs @@ -18,32 +18,32 @@ //! This module contains routines for accessing and altering a contract related state. use crate::{ + AccountInfoOf, BalanceOf, BalanceWithDust, Config, DeletionQueue, DeletionQueueCounter, Error, + SENTINEL, TrieId, address::AddressMapper, exec::{AccountIdOf, Key}, metering::FrameMeter, tracing::if_tracing, weights::WeightInfo, - AccountInfoOf, BalanceOf, BalanceWithDust, Config, DeletionQueue, DeletionQueueCounter, Error, - TrieId, SENTINEL, }; use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use core::marker::PhantomData; use frame_support::{ + CloneNoBound, DebugNoBound, DefaultNoBound, storage::child::{self, ChildInfo}, traits::{ fungible::Inspect, tokens::{Fortitude, Preservation}, }, weights::{Weight, WeightMeter}, - CloneNoBound, DebugNoBound, DefaultNoBound, }; use scale_info::TypeInfo; use sp_core::{Get, H160}; use sp_io::KillStorageResult; use sp_runtime::{ - traits::{Hash, Saturating, Zero}, Debug, DispatchError, + traits::{Hash, Saturating, Zero}, }; use crate::metering::Diff; diff --git a/substrate/frame/revive/src/test_utils/builder.rs b/substrate/frame/revive/src/test_utils/builder.rs index 16b29bfde69a0..d370a3d199a87 100644 --- a/substrate/frame/revive/src/test_utils/builder.rs +++ b/substrate/frame/revive/src/test_utils/builder.rs @@ -15,11 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{deposit_limit, ETH_GAS_LIMIT, WEIGHT_LIMIT}; +use super::{ETH_GAS_LIMIT, WEIGHT_LIMIT, deposit_limit}; use crate::{ - address::AddressMapper, evm::TransactionSigned, metering::TransactionLimits, AccountIdOf, - BalanceOf, Code, Config, ContractResult, ExecConfig, ExecReturnValue, InstantiateReturnValue, - OriginFor, Pallet, Weight, U256, + AccountIdOf, BalanceOf, Code, Config, ContractResult, ExecConfig, ExecReturnValue, + InstantiateReturnValue, OriginFor, Pallet, U256, Weight, address::AddressMapper, + evm::TransactionSigned, metering::TransactionLimits, }; use alloc::{vec, vec::Vec}; use frame_support::pallet_prelude::DispatchResultWithPostInfo; diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 09bf141887468..2196a032f98f4 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -25,7 +25,9 @@ mod stipends; use std::collections::HashMap; use crate::{ - self as pallet_revive, + self as pallet_revive, AccountId32Mapper, AddressMapper, BalanceOf, BalanceWithDust, Call, + CodeInfoOf, Config, DelegateInfo, ExecOrigin as Origin, ExecReturnValue, GenesisConfig, + OriginFor, Pallet, PristineCode, evm::{ fees::{BlockRatioFee, Info as FeeInfo}, runtime::{EthExtra, SetWeightLimit}, @@ -33,26 +35,22 @@ use crate::{ genesis::{Account, ContractData}, mock::MockHandler, test_utils::*, - AccountId32Mapper, AddressMapper, BalanceOf, BalanceWithDust, Call, CodeInfoOf, Config, - DelegateInfo, ExecOrigin as Origin, ExecReturnValue, GenesisConfig, OriginFor, Pallet, - PristineCode, }; use frame_support::{ - assert_ok, derive_impl, + DefaultNoBound, assert_ok, derive_impl, pallet_prelude::EnsureOrigin, parameter_types, traits::{ConstU32, ConstU64, FindAuthor, OriginTrait, StorageVersion}, - weights::{constants::WEIGHT_REF_TIME_PER_SECOND, FixedFee, Weight}, - DefaultNoBound, + weights::{FixedFee, Weight, constants::WEIGHT_REF_TIME_PER_SECOND}, }; use pallet_revive_fixtures::compile_module; use pallet_transaction_payment::{ChargeTransactionPayment, ConstFeeMultiplier, Multiplier}; use sp_core::{H160, U256}; -use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; +use sp_keystore::{KeystoreExt, testing::MemoryKeystore}; use sp_runtime::{ + AccountId32, BuildStorage, FixedU128, MultiAddress, MultiSignature, Perbill, Storage, generic::Header, traits::{BlakeTwo256, Convert, IdentityLookup, One}, - AccountId32, BuildStorage, FixedU128, MultiAddress, MultiSignature, Perbill, Storage, }; pub type Address = MultiAddress; @@ -117,8 +115,8 @@ pub mod test_utils { Test, }; use crate::{ - address::AddressMapper, exec::AccountIdOf, AccountInfo, AccountInfoOf, BalanceOf, CodeInfo, - CodeInfoOf, Config, ContractInfo, PristineCode, + AccountInfo, AccountInfoOf, BalanceOf, CodeInfo, CodeInfoOf, Config, ContractInfo, + PristineCode, address::AddressMapper, exec::AccountIdOf, }; use codec::{Encode, MaxEncodedLen}; use frame_support::traits::fungible::{InspectHold, Mutate}; @@ -217,9 +215,9 @@ pub mod test_utils { pub(crate) mod builder { use super::Test; use crate::{ - test_utils::{builder::*, ALICE}, - tests::RuntimeOrigin, Code, + test_utils::{ALICE, builder::*}, + tests::RuntimeOrigin, }; use sp_core::{H160, H256}; @@ -574,11 +572,7 @@ impl MockHandler for MockHandlerImpl { } fn mocked_code(&self, address: H160) -> Option<&[u8]> { - if self.mock_call.contains_key(&address) { - Some(&MOCK_CODE) - } else { - None - } + if self.mock_call.contains_key(&address) { Some(&MOCK_CODE) } else { None } } } diff --git a/substrate/frame/revive/src/tests/block_hash.rs b/substrate/frame/revive/src/tests/block_hash.rs index d83b55916e9be..766dce8609ba1 100644 --- a/substrate/frame/revive/src/tests/block_hash.rs +++ b/substrate/frame/revive/src/tests/block_hash.rs @@ -18,17 +18,17 @@ //! The pallet-revive ETH block hash specific integration test suite. use crate::{ - evm::{block_hash::EthereumBlockBuilder, fees::InfoT, Block, TransactionSigned}, - test_utils::{builder::Contract, deposit_limit, ALICE}, - tests::{assert_ok, builder, Contracts, ExtBuilder, RuntimeOrigin, System, Test, Timestamp}, BalanceWithDust, Code, Config, EthBlock, EthBlockBuilderFirstValues, EthBlockBuilderIR, EthereumBlock, Pallet, ReceiptGasInfo, ReceiptInfoData, + evm::{Block, TransactionSigned, block_hash::EthereumBlockBuilder, fees::InfoT}, + test_utils::{ALICE, builder::Contract, deposit_limit}, + tests::{Contracts, ExtBuilder, RuntimeOrigin, System, Test, Timestamp, assert_ok, builder}, }; use alloy_consensus::RlpEncodableReceipt; use alloy_core::primitives::{FixedBytes, Log as AlloyLog}; use frame_support::traits::{ - fungible::{Balanced, Mutate}, Hooks, + fungible::{Balanced, Mutate}, }; use pallet_revive_fixtures::compile_module; use sp_state_machine::BasicExternalities; @@ -93,10 +93,12 @@ fn transactions_are_captured() { // eth calls are captured. assert_ok!(builder::eth_call(addr).transaction_encoded(vec![1]).value(balance).build()); - assert_ok!(builder::eth_instantiate_with_code(binary) - .value(balance) - .transaction_encoded(vec![2]) - .build()); + assert_ok!( + builder::eth_instantiate_with_code(binary) + .value(balance) + .transaction_encoded(vec![2]) + .build() + ); assert_ok!(builder::eth_call(addr2).transaction_encoded(vec![3]).build()); // non-eth calls are not captured. diff --git a/substrate/frame/revive/src/tests/precompiles.rs b/substrate/frame/revive/src/tests/precompiles.rs index b50acab03fb19..37a76a156ec8e 100644 --- a/substrate/frame/revive/src/tests/precompiles.rs +++ b/substrate/frame/revive/src/tests/precompiles.rs @@ -18,9 +18,9 @@ //! Precompiles added to the test runtime. use crate::{ + Config, DispatchError, ExecOrigin as Origin, ReentrancyProtection, U256, Weight, exec::{CallResources, ErrorOrigin, ExecError}, precompiles::{AddressMatcher, Error, Ext, ExtWithInfo, Precompile, Token}, - Config, DispatchError, ExecOrigin as Origin, ReentrancyProtection, Weight, U256, }; use alloc::vec::Vec; use alloy_core::{ diff --git a/substrate/frame/revive/src/tests/pvm.rs b/substrate/frame/revive/src/tests/pvm.rs index 9fb379c427426..287729880c601 100644 --- a/substrate/frame/revive/src/tests/pvm.rs +++ b/substrate/frame/revive/src/tests/pvm.rs @@ -22,27 +22,27 @@ use super::{ precompiles::{INoInfo, NoInfo}, }; use crate::{ - address::{create1, create2, AddressMapper}, + AccountInfo, AccountInfoOf, BalanceWithDust, Code, Config, ContractInfo, DebugSettings, + DeletionQueueCounter, Error, ExecConfig, HoldReason, Origin, Pallet, StorageDeposit, + address::{AddressMapper, create1, create2}, assert_refcount, assert_return_code, - evm::{fees::InfoT, CallTrace, CallTracer, CallType}, + evm::{CallTrace, CallTracer, CallType, fees::InfoT}, exec::Key, limits, metering::TransactionLimits, precompiles::alloy::sol_types::{ - sol_data::{Bool, FixedBytes}, SolType, + sol_data::{Bool, FixedBytes}, }, storage::{DeletionQueueManager, WriteOutcome}, - test_utils::{builder::Contract, WEIGHT_LIMIT}, + test_utils::{WEIGHT_LIMIT, builder::Contract}, tests::{ - builder, initialize_block, test_utils::*, Balances, Contracts, DepositPerByte, - DepositPerItem, ExtBuilder, InstantiateAccount, RuntimeCall, RuntimeEvent, RuntimeOrigin, - System, Test, UploadAccount, DEPOSIT_PER_BYTE, *, + Balances, Contracts, DEPOSIT_PER_BYTE, DepositPerByte, DepositPerItem, ExtBuilder, + InstantiateAccount, RuntimeCall, RuntimeEvent, RuntimeOrigin, System, Test, UploadAccount, + builder, initialize_block, test_utils::*, *, }, tracing::trace, weights::WeightInfo, - AccountInfo, AccountInfoOf, BalanceWithDust, Code, Config, ContractInfo, DebugSettings, - DeletionQueueCounter, Error, ExecConfig, HoldReason, Origin, Pallet, StorageDeposit, }; use assert_matches::assert_matches; use codec::Encode; @@ -50,9 +50,9 @@ use frame_support::{ assert_err, assert_err_ignore_postinfo, assert_noop, assert_ok, storage::child, traits::{ + OnIdle, OnInitialize, fungible::{Balanced, BalancedHold, Inspect, Mutate}, tokens::Preservation, - OnIdle, OnInitialize, }, weights::{Weight, WeightMeter}, }; @@ -63,7 +63,7 @@ use pretty_assertions::{assert_eq, assert_ne}; use sp_core::U256; use sp_io::hashing::blake2_256; use sp_runtime::{ - testing::H256, AccountId32, BoundedVec, DispatchError, SaturatedConversion, TokenError, + AccountId32, BoundedVec, DispatchError, SaturatedConversion, TokenError, testing::H256, }; #[test] @@ -78,10 +78,12 @@ fn eth_call_transfer_with_dust_works() { let balance = Pallet::::convert_native_to_evm(BalanceWithDust::new_unchecked::(100, 10)); - assert_ok!(builder::eth_call(addr) - .origin(Origin::EthTransaction(ALICE).into()) - .value(balance) - .build()); + assert_ok!( + builder::eth_call(addr) + .origin(Origin::EthTransaction(ALICE).into()) + .value(balance) + .build() + ); assert_eq!(Pallet::::evm_balance(&addr), balance); }); @@ -331,10 +333,12 @@ fn deposit_event_max_value_limit() { .build_and_unwrap_contract(); // Call contract with allowed event size. - assert_ok!(builder::call(addr) - .weight_limit(WEIGHT_LIMIT.set_ref_time(WEIGHT_LIMIT.ref_time() * 2)) // we are copying a huge buffer, - .data(limits::EVENT_BYTES.encode()) - .build()); + assert_ok!( + builder::call(addr) + .weight_limit(WEIGHT_LIMIT.set_ref_time(WEIGHT_LIMIT.ref_time() * 2)) // we are copying a huge buffer, + .data(limits::EVENT_BYTES.encode()) + .build() + ); // Call contract with too large a evene size assert_err_ignore_postinfo!( @@ -500,10 +504,12 @@ fn storage_max_value_limit() { get_contract(&addr); // Call contract with allowed storage value. - assert_ok!(builder::call(addr) - .weight_limit(WEIGHT_LIMIT.set_ref_time(WEIGHT_LIMIT.ref_time() * 2)) // we are copying a huge buffer - .data(limits::STORAGE_BYTES.encode()) - .build()); + assert_ok!( + builder::call(addr) + .weight_limit(WEIGHT_LIMIT.set_ref_time(WEIGHT_LIMIT.ref_time() * 2)) // we are copying a huge buffer + .data(limits::STORAGE_BYTES.encode()) + .build() + ); // Call contract with too large a storage value. assert_err_ignore_postinfo!( @@ -559,9 +565,9 @@ fn transient_storage_limit_in_call() { // Call contracts with storage values within the limit. // Caller and Callee contracts each set a transient storage value of size 100. - assert_ok!(builder::call(addr_caller) - .data((100u32, 100u32, &addr_callee).encode()) - .build(),); + assert_ok!( + builder::call(addr_caller).data((100u32, 100u32, &addr_callee).encode()).build(), + ); // Call a contract with a storage value that is too large. // Limit exceeded in the caller contract. @@ -619,12 +625,14 @@ fn deploy_and_call_other_contract() { // Call BOB contract, which attempts to instantiate and call the callee contract and // makes various assertions on the results from those calls. - assert_ok!(builder::call(caller_addr) - .data( - (callee_code_hash, code_load_weight.ref_time(), code_load_weight.proof_size()) - .encode() - ) - .build()); + assert_ok!( + builder::call(caller_addr) + .data( + (callee_code_hash, code_load_weight.ref_time(), code_load_weight.proof_size()) + .encode() + ) + .build() + ); assert_eq!( System::events(), @@ -708,10 +716,12 @@ fn delegate_call() { .native_value(100_000) .build_and_unwrap_contract(); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((callee_addr, u64::MAX, u64::MAX).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((callee_addr, u64::MAX, u64::MAX).encode()) + .build() + ); }); } @@ -728,10 +738,12 @@ fn delegate_call_non_existant_is_noop() { .native_value(300_000) .build_and_unwrap_contract(); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((BOB_ADDR, u64::MAX, u64::MAX).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((BOB_ADDR, u64::MAX, u64::MAX).encode()) + .build() + ); assert_eq!(get_balance(&BOB_FALLBACK), 0); }); @@ -767,10 +779,12 @@ fn delegate_call_with_weight_limit() { Error::::ContractTrapped, ); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((callee_addr, 500_000_000u64, 100_000u64).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((callee_addr, 500_000_000u64, 100_000u64).encode()) + .build() + ); }); } @@ -803,10 +817,12 @@ fn delegate_call_with_deposit_limit() { .build_and_unwrap_result(); assert_return_code!(ret, RuntimeReturnCode::OutOfResources); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((callee_addr, 82u64).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((callee_addr, 82u64).encode()) + .build() + ); }); } @@ -2557,10 +2573,12 @@ fn storage_deposit_limit_is_enforced() { ); // now with enough limit - assert_ok!(builder::call(addr) - .storage_deposit_limit(51) - .data(1u32.to_le_bytes().to_vec()) - .build()); + assert_ok!( + builder::call(addr) + .storage_deposit_limit(51) + .data(1u32.to_le_bytes().to_vec()) + .build() + ); // Use 4 more bytes of the storage for the same item, which requires 4 Balance. // Should fail as DefaultDepositLimit is 3 and hence isn't enough. @@ -2590,10 +2608,12 @@ fn deposit_limit_in_nested_calls() { // Create 100 bytes of storage with a price of per byte // This is 100 Balance + 2 Balance for the item // 48 for the key - assert_ok!(builder::call(addr_callee) - .storage_deposit_limit(102 + 48) - .data(100u32.to_le_bytes().to_vec()) - .build()); + assert_ok!( + builder::call(addr_callee) + .storage_deposit_limit(102 + 48) + .data(100u32.to_le_bytes().to_vec()) + .build() + ); // We do not remove any storage but add a storage item of 12 bytes in the caller // contract. This would cost 12 + 2 + 72 = 86 Balance. @@ -2668,10 +2688,12 @@ fn deposit_limit_in_nested_calls() { // Free up enough storage in the callee so that the caller can create a new item // We set the special deposit limit of 1 Balance for the nested call, which isn't // enforced as callee frees up storage. This should pass. - assert_ok!(builder::call(addr_caller) - .storage_deposit_limit(78) - .data((0u32, &addr_callee, U256::from(1u64)).encode()) - .build()); + assert_ok!( + builder::call(addr_caller) + .storage_deposit_limit(78) + .data((0u32, &addr_callee, U256::from(1u64)).encode()) + .build() + ); }); } @@ -2874,9 +2896,11 @@ fn block_hash_works() { H256::from(block_hash), ); - assert_ok!(builder::call(addr) - .data((U256::zero(), H256::from(block_hash)).encode()) - .build()); + assert_ok!( + builder::call(addr) + .data((U256::zero(), H256::from(block_hash)).encode()) + .build() + ); // A block number out of range returns the zero value assert_ok!(builder::call(addr).data((U256::from(1), H256::zero()).encode()).build()); @@ -3546,10 +3570,12 @@ fn return_data_api_works() { .build_and_unwrap_contract(); // Call the contract: It will issue calls and deploys, asserting on - assert_ok!(builder::call(addr) - .value(10 * 1024) - .data(hash_return_with_data.encode()) - .build()); + assert_ok!( + builder::call(addr) + .value(10 * 1024) + .data(hash_return_with_data.encode()) + .build() + ); }); } @@ -3644,7 +3670,7 @@ fn origin_api_works() { #[test] fn code_hash_works() { - use crate::precompiles::{Precompile, EVM_REVERT}; + use crate::precompiles::{EVM_REVERT, Precompile}; use precompiles::NoInfo; let builtin_precompile = H160(NoInfo::::MATCHER.base_address()); @@ -3666,13 +3692,17 @@ fn code_hash_works() { // code hash of itself assert_ok!(builder::call(addr).data((addr, self_code_hash).encode()).build()); // code hash of primitive pre-compile (exist but have no bytecode) - assert_ok!(builder::call(addr) - .data((primitive_precompile, crate::exec::EMPTY_CODE_HASH).encode()) - .build()); + assert_ok!( + builder::call(addr) + .data((primitive_precompile, crate::exec::EMPTY_CODE_HASH).encode()) + .build() + ); // code hash of normal pre-compile (do have a bytecode) - assert_ok!(builder::call(addr) - .data((builtin_precompile, sp_io::hashing::keccak_256(&EVM_REVERT)).encode()) - .build()); + assert_ok!( + builder::call(addr) + .data((builtin_precompile, sp_io::hashing::keccak_256(&EVM_REVERT)).encode()) + .build() + ); // EOA doesn't exists assert_err!( @@ -3692,9 +3722,11 @@ fn code_hash_works() { ); // EOA returns empty code hash - assert_ok!(builder::call(addr) - .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) - .build()); + assert_ok!( + builder::call(addr) + .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) + .build() + ); }); } @@ -3718,9 +3750,9 @@ fn code_size_works() { assert_ok!(builder::call(tester_addr).data((dummy_addr, dummy_code_len).encode()).build()); // code size of own contract address - assert_ok!(builder::call(tester_addr) - .data((tester_addr, tester_code_len).encode()) - .build()); + assert_ok!( + builder::call(tester_addr).data((tester_addr, tester_code_len).encode()).build() + ); // code size of non contract accounts assert_ok!(builder::call(tester_addr).data(([8u8; 20], 0u64).encode()).build()); @@ -5185,8 +5217,8 @@ fn existential_deposit_shall_not_be_charged_twice() { #[test] fn self_destruct_by_syscall_tracing_works() { use crate::{ - evm::{PrestateTrace, PrestateTracer, PrestateTracerConfig, Tracer}, Trace, + evm::{PrestateTrace, PrestateTracer, PrestateTracerConfig, Tracer}, }; let (binary, _code_hash) = compile_module("self_destruct_by_syscall").unwrap(); @@ -5401,10 +5433,12 @@ fn delegate_call_with_gas_limit() { Error::::ContractTrapped, ); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((callee_addr, 100_000_000_000u64).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((callee_addr, 100_000_000_000u64).encode()) + .build() + ); }); } @@ -5436,14 +5470,18 @@ fn call_with_gas_limit() { ); // succeeds, not enough gas but call stipend will be added - assert_ok!(builder::call(caller_addr) - .value(1337) - .data((callee_addr, 100u64).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .value(1337) + .data((callee_addr, 100u64).encode()) + .build() + ); // succeeds, enough gas - assert_ok!(builder::call(caller_addr) - .data((callee_addr, 100_000_000_000u64).encode()) - .build()); + assert_ok!( + builder::call(caller_addr) + .data((callee_addr, 100_000_000_000u64).encode()) + .build() + ); }); } diff --git a/substrate/frame/revive/src/tests/sol.rs b/substrate/frame/revive/src/tests/sol.rs index f902e38fe4005..4a16906771389 100644 --- a/substrate/frame/revive/src/tests/sol.rs +++ b/substrate/frame/revive/src/tests/sol.rs @@ -16,25 +16,23 @@ // limitations under the License. use crate::{ - assert_refcount, + BalanceOf, Code, Config, Error, EthBlockBuilderFirstValues, GenesisConfig, Origin, Pallet, + PristineCode, assert_refcount, call_builder::VmBinaryModule, debug::DebugSettings, evm::{PrestateTrace, PrestateTracer, PrestateTracerConfig}, - test_utils::{builder::Contract, ALICE, ALICE_ADDR, BOB}, + test_utils::{ALICE, ALICE_ADDR, BOB, builder::Contract}, tests::{ - builder, + AllowEvmBytecode, DebugFlag, ExtBuilder, RuntimeOrigin, Test, builder, test_utils::{contract_base_deposit, ensure_stored, get_contract}, - AllowEvmBytecode, DebugFlag, ExtBuilder, RuntimeOrigin, Test, }, tracing::trace, - BalanceOf, Code, Config, Error, EthBlockBuilderFirstValues, GenesisConfig, Origin, Pallet, - PristineCode, }; use alloy_core::sol_types::{SolCall, SolInterface}; use frame_support::{ assert_err, assert_noop, assert_ok, dispatch::GetDispatchInfo, traits::fungible::Mutate, }; -use pallet_revive_fixtures::{compile_module_with_type, Fibonacci, FixtureType, NestedCounter}; +use pallet_revive_fixtures::{Fibonacci, FixtureType, NestedCounter, compile_module_with_type}; use pretty_assertions::assert_eq; use sp_runtime::Weight; use test_case::test_case; @@ -221,10 +219,10 @@ fn eth_contract_too_large() { #[test] fn upload_evm_runtime_code_works() { use crate::{ + Pallet, TransactionMeter, exec::Executable, primitives::ExecConfig, storage::{AccountInfo, ContractInfo}, - Pallet, TransactionMeter, }; let (runtime_code, _runtime_hash) = @@ -360,8 +358,7 @@ fn prestate_diff_mode_tracing_works() { "nonce": 2, "code": "{{CONTRACT_CODE}}", "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000000": "{{CHILD_ADDR_PADDED}}", - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000007" + "0x0000000000000000000000000000000000000000000000000000000000000000": "{{SLOT0_PACKED_7}}" } }, "{{CHILD_ADDR}}": { @@ -396,8 +393,7 @@ fn prestate_diff_mode_tracing_works() { "nonce": 2, "code": "{{CONTRACT_CODE}}", "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000000": "{{CHILD_ADDR_PADDED}}", - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000007" + "0x0000000000000000000000000000000000000000000000000000000000000000": "{{SLOT0_PACKED_7}}" } }, "{{CHILD_ADDR}}": { @@ -417,7 +413,7 @@ fn prestate_diff_mode_tracing_works() { "nonce": 2, "code": "{{CONTRACT_CODE}}", "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000007" + "0x0000000000000000000000000000000000000000000000000000000000000000": "{{SLOT0_PACKED_7}}" } }, "{{CHILD_ADDR}}": { @@ -432,7 +428,7 @@ fn prestate_diff_mode_tracing_works() { "post": { "{{CONTRACT_ADDR}}": { "storage": { - "0x0000000000000000000000000000000000000000000000000000000000000001": "0x0000000000000000000000000000000000000000000000000000000000000008" + "0x0000000000000000000000000000000000000000000000000000000000000000": "{{SLOT0_PACKED_8}}" } }, "{{CHILD_ADDR}}": { @@ -460,8 +456,13 @@ fn prestate_diff_mode_tracing_works() { let replace_placeholders = |json: &str| -> String { let alice_balance_post = Pallet::::evm_balance(&ALICE_ADDR); - let mut child_addr_bytes = [0u8; 32]; - child_addr_bytes[12..32].copy_from_slice(child_addr.as_bytes()); + // Packed slot 0: [4 zero bytes][uint64 number BE][20-byte address] + let slot0_packed = |number: u64| -> String { + let mut slot = [0u8; 32]; + slot[4..12].copy_from_slice(&number.to_be_bytes()); + slot[12..32].copy_from_slice(child_addr.as_bytes()); + format!("0x{}", hex::encode(slot)) + }; json.replace("{{ALICE_ADDR}}", &format!("{:#x}", ALICE_ADDR)) .replace("{{CONTRACT_ADDR}}", &format!("{:#x}", contract_addr)) @@ -473,10 +474,8 @@ fn prestate_diff_mode_tracing_works() { &format!("0x{}", hex::encode(&contract_runtime_code)), ) .replace("{{CHILD_CODE}}", &format!("0x{}", hex::encode(&child_runtime_code))) - .replace( - "{{CHILD_ADDR_PADDED}}", - &format!("0x{}", hex::encode(child_addr_bytes)), - ) + .replace("{{SLOT0_PACKED_7}}", &slot0_packed(7)) + .replace("{{SLOT0_PACKED_8}}", &slot0_packed(8)) }; let mut tracer = PrestateTracer::::new(test_case.config.clone()); diff --git a/substrate/frame/revive/src/tests/sol/arithmetic.rs b/substrate/frame/revive/src/tests/sol/arithmetic.rs index c4f6cfb8edb5a..818b60312d368 100644 --- a/substrate/frame/revive/src/tests/sol/arithmetic.rs +++ b/substrate/frame/revive/src/tests/sol/arithmetic.rs @@ -16,15 +16,15 @@ // limitations under the License. use crate::{ - evm::decode_revert_reason, - test_utils::{builder::Contract, ALICE}, - tests::{builder, ExtBuilder, Test}, Code, Config, + evm::decode_revert_reason, + test_utils::{ALICE, builder::Contract}, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::SolInterface; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, Arithmetic, FixtureType}; +use pallet_revive_fixtures::{Arithmetic, FixtureType, compile_module_with_type}; use test_case::test_case; #[test_case(FixtureType::Solc)] diff --git a/substrate/frame/revive/src/tests/sol/bitwise.rs b/substrate/frame/revive/src/tests/sol/bitwise.rs index 513170363acbd..a092809f12d2e 100644 --- a/substrate/frame/revive/src/tests/sol/bitwise.rs +++ b/substrate/frame/revive/src/tests/sol/bitwise.rs @@ -17,15 +17,15 @@ /// Tests for bitwise operations. use crate::{ - evm::decode_revert_reason, - test_utils::{builder::Contract, ALICE}, - tests::{builder, ExtBuilder, Test}, Code, Config, + evm::decode_revert_reason, + test_utils::{ALICE, builder::Contract}, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::SolInterface; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, Bitwise, FixtureType}; +use pallet_revive_fixtures::{Bitwise, FixtureType, compile_module_with_type}; use test_case::test_case; #[test_case(FixtureType::Solc)] diff --git a/substrate/frame/revive/src/tests/sol/block_info.rs b/substrate/frame/revive/src/tests/sol/block_info.rs index 628010044f5f3..62c5c9715176e 100644 --- a/substrate/frame/revive/src/tests/sol/block_info.rs +++ b/substrate/frame/revive/src/tests/sol/block_info.rs @@ -18,15 +18,15 @@ //! The pallet-revive shared VM integration test suite. use crate::{ - test_utils::{builder::Contract, ALICE}, - tests::{builder, Contracts, ExtBuilder, System, Test, Timestamp}, - vm::evm::DIFFICULTY, Code, Config, DryRunConfig, ExecConfig, Pallet, + test_utils::{ALICE, builder::Contract}, + tests::{Contracts, ExtBuilder, System, Test, Timestamp, builder}, + vm::evm::DIFFICULTY, }; use alloy_core::sol_types::{SolCall, SolInterface}; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, BlockInfo, FixtureType}; +use pallet_revive_fixtures::{BlockInfo, FixtureType, compile_module_with_type}; use pretty_assertions::assert_eq; use sp_core::H160; use test_case::test_case; diff --git a/substrate/frame/revive/src/tests/sol/contract.rs b/substrate/frame/revive/src/tests/sol/contract.rs index ab7f60124adb5..fdbd3f89244dd 100644 --- a/substrate/frame/revive/src/tests/sol/contract.rs +++ b/substrate/frame/revive/src/tests/sol/contract.rs @@ -20,13 +20,13 @@ use core::iter; use crate::{ + BalanceOf, Code, Config, DelegateInfo, DispatchError, Error, ExecConfig, ExecOrigin, + ExecReturnValue, Weight, address::AddressMapper, evm::{decode_revert_reason, fees::InfoT}, metering::TransactionLimits, - test_utils::{builder::Contract, deposit_limit, ALICE, ALICE_ADDR, BOB_ADDR, WEIGHT_LIMIT}, - tests::{builder, ExtBuilder, MockHandlerImpl, Test, MOCK_CODE}, - BalanceOf, Code, Config, DelegateInfo, DispatchError, Error, ExecConfig, ExecOrigin, - ExecReturnValue, Weight, + test_utils::{ALICE, ALICE_ADDR, BOB_ADDR, WEIGHT_LIMIT, builder::Contract, deposit_limit}, + tests::{ExtBuilder, MOCK_CODE, MockHandlerImpl, Test, builder}, }; use alloy_core::{ primitives::{Bytes, FixedBytes}, @@ -37,7 +37,7 @@ use frame_support::{ traits::fungible::{Balanced, Mutate}, }; use itertools::Itertools; -use pallet_revive_fixtures::{compile_module_with_type, Callee, Caller, FixtureType, Host}; +use pallet_revive_fixtures::{Callee, Caller, FixtureType, Host, compile_module_with_type}; use pallet_revive_uapi::ReturnFlags; use pretty_assertions::assert_eq; use sp_core::{H160, H256}; @@ -620,7 +620,7 @@ fn create_works() { let magic_number = 42u64; // Check if the created contract is working - let echo_result = builder::bare_call(callee_addr.0 .0.into()) + let echo_result = builder::bare_call(callee_addr.0.0.into()) .data(Callee::echoCall { _data: magic_number }.abi_encode()) .build_and_unwrap_result(); @@ -658,7 +658,7 @@ fn create2_works() { // Compute expected CREATE2 address let expected_addr = crate::address::create2(&caller_addr, &initcode, &[], &salt); - let callee_addr: H160 = callee_addr.0 .0.into(); + let callee_addr: H160 = callee_addr.0.0.into(); assert_eq!(callee_addr, expected_addr, "CREATE2 address should be deterministic"); let magic_number = 42u64; diff --git a/substrate/frame/revive/src/tests/sol/control.rs b/substrate/frame/revive/src/tests/sol/control.rs index 0c953f496b6f0..d8782679e5162 100644 --- a/substrate/frame/revive/src/tests/sol/control.rs +++ b/substrate/frame/revive/src/tests/sol/control.rs @@ -16,10 +16,10 @@ // limitations under the License. use crate::{ - metering::TransactionLimits, - test_utils::{builder::Contract, ALICE}, - tests::{builder, sol::make_initcode_from_runtime_code, ExtBuilder, Test}, Code, Config, Error, U256, + metering::TransactionLimits, + test_utils::{ALICE, builder::Contract}, + tests::{ExtBuilder, Test, builder, sol::make_initcode_from_runtime_code}, }; use frame_support::{assert_err, traits::fungible::Mutate}; use pallet_revive_uapi::ReturnFlags; diff --git a/substrate/frame/revive/src/tests/sol/host.rs b/substrate/frame/revive/src/tests/sol/host.rs index f6a54e6b0a364..876ecd29667c4 100644 --- a/substrate/frame/revive/src/tests/sol/host.rs +++ b/substrate/frame/revive/src/tests/sol/host.rs @@ -17,17 +17,17 @@ //! The pallet-revive shared VM integration test suite. use crate::{ + Code, Config, Error, H256, Key, System, U256, address::AddressMapper, metering::TransactionLimits, - test_utils::{builder::Contract, ALICE, BOB, BOB_ADDR}, - tests::{builder, test_utils, test_utils::get_contract, ExtBuilder, RuntimeEvent, Test}, - Code, Config, Error, Key, System, H256, U256, + test_utils::{ALICE, BOB, BOB_ADDR, builder::Contract}, + tests::{ExtBuilder, RuntimeEvent, Test, builder, test_utils, test_utils::get_contract}, }; use frame_support::assert_err_ignore_postinfo; use alloy_core::sol_types::{SolCall, SolInterface}; -use frame_support::traits::{fungible::Mutate, Get}; -use pallet_revive_fixtures::{compile_module_with_type, Caller, FixtureType, Host}; +use frame_support::traits::{Get, fungible::Mutate}; +use pallet_revive_fixtures::{Caller, FixtureType, Host, compile_module_with_type}; use pretty_assertions::assert_eq; use test_case::test_case; diff --git a/substrate/frame/revive/src/tests/sol/memory.rs b/substrate/frame/revive/src/tests/sol/memory.rs index 3ebd49dceb30b..aa217ba11598a 100644 --- a/substrate/frame/revive/src/tests/sol/memory.rs +++ b/substrate/frame/revive/src/tests/sol/memory.rs @@ -16,14 +16,14 @@ // limitations under the License. use crate::{ - evm::decode_revert_reason, - test_utils::{builder::Contract, ALICE}, - tests::{builder, ExtBuilder, Test}, Code, Config, Error, ExecReturnValue, LOG_TARGET, + evm::decode_revert_reason, + test_utils::{ALICE, builder::Contract}, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::{SolCall, SolInterface}; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, FixtureType, Memory}; +use pallet_revive_fixtures::{FixtureType, Memory, compile_module_with_type}; use pallet_revive_uapi::ReturnFlags; use pretty_assertions::assert_eq; use test_case::test_case; diff --git a/substrate/frame/revive/src/tests/sol/stack.rs b/substrate/frame/revive/src/tests/sol/stack.rs index 2bcdc731f6bb5..9ecaa9c57332c 100644 --- a/substrate/frame/revive/src/tests/sol/stack.rs +++ b/substrate/frame/revive/src/tests/sol/stack.rs @@ -16,9 +16,9 @@ // limitations under the License. use crate::{ - test_utils::{builder::Contract, ALICE}, - tests::{builder, sol::make_initcode_from_runtime_code, ExtBuilder, Test}, Code, Config, U256, + test_utils::{ALICE, builder::Contract}, + tests::{ExtBuilder, Test, builder, sol::make_initcode_from_runtime_code}, }; use frame_support::traits::fungible::Mutate; use pretty_assertions::assert_eq; diff --git a/substrate/frame/revive/src/tests/sol/system.rs b/substrate/frame/revive/src/tests/sol/system.rs index 56aaf8a254427..edcfae94159da 100644 --- a/substrate/frame/revive/src/tests/sol/system.rs +++ b/substrate/frame/revive/src/tests/sol/system.rs @@ -18,16 +18,16 @@ //! The pallet-revive shared VM integration test suite. use crate::{ - evm::fees::InfoT, - test_utils::{builder::Contract, deposit_limit, ALICE, ALICE_ADDR, WEIGHT_LIMIT}, - tests::{builder, Contracts, ExtBuilder, Test}, Code, Config, ExecConfig, TransactionLimits, TransactionMeter, U256, + evm::fees::InfoT, + test_utils::{ALICE, ALICE_ADDR, WEIGHT_LIMIT, builder::Contract, deposit_limit}, + tests::{Contracts, ExtBuilder, Test, builder}, }; use alloy_core::sol_types::{Revert, SolCall, SolConstructor, SolError}; use frame_support::traits::fungible::{Balanced, Mutate}; use pallet_revive_fixtures::{ - compile_module_with_type, Callee, FixtureType, System as SystemFixture, + Callee, FixtureType, System as SystemFixture, compile_module_with_type, }; use pretty_assertions::assert_eq; use revm::primitives::Bytes; diff --git a/substrate/frame/revive/src/tests/sol/terminate.rs b/substrate/frame/revive/src/tests/sol/terminate.rs index e17b66e3f3e5d..15b9435a1aafa 100644 --- a/substrate/frame/revive/src/tests/sol/terminate.rs +++ b/substrate/frame/revive/src/tests/sol/terminate.rs @@ -16,19 +16,18 @@ // limitations under the License. use crate::{ + BalanceOf, Code, Config, H160, Pallet, address::AddressMapper, - test_utils::{builder::Contract, ALICE, DJANGO, DJANGO_ADDR}, + test_utils::{ALICE, DJANGO, DJANGO_ADDR, builder::Contract}, tests::{ - builder, + Contracts, ExtBuilder, RuntimeOrigin, Test, builder, test_utils::{get_balance, get_contract_checked}, - Contracts, ExtBuilder, RuntimeOrigin, Test, }, - BalanceOf, Code, Config, Pallet, H160, }; use alloy_core::sol_types::{SolCall, SolConstructor}; use frame_support::traits::fungible::Mutate; use pallet_revive_fixtures::{ - compile_module_with_type, FixtureType, Terminate, TerminateCaller, TerminateDelegator, + FixtureType, Terminate, TerminateCaller, TerminateDelegator, compile_module_with_type, }; use pretty_assertions::assert_eq; use test_case::{test_case, test_matrix}; diff --git a/substrate/frame/revive/src/tests/sol/tx_info.rs b/substrate/frame/revive/src/tests/sol/tx_info.rs index a2072ab67a984..c24fce688124d 100644 --- a/substrate/frame/revive/src/tests/sol/tx_info.rs +++ b/substrate/frame/revive/src/tests/sol/tx_info.rs @@ -18,13 +18,13 @@ //! The pallet-revive shared VM integration test suite. use crate::{ - test_utils::{builder::Contract, ALICE, ALICE_ADDR}, - tests::{builder, ExtBuilder, Test}, Code, Config, Pallet, + test_utils::{ALICE, ALICE_ADDR, builder::Contract}, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::{SolCall, SolInterface}; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, FixtureType, TransactionInfo}; +use pallet_revive_fixtures::{FixtureType, TransactionInfo, compile_module_with_type}; use pretty_assertions::assert_eq; use sp_core::H160; use test_case::test_case; diff --git a/substrate/frame/revive/src/tests/stipends.rs b/substrate/frame/revive/src/tests/stipends.rs index 3204b66807e2a..825ad8531ed8e 100644 --- a/substrate/frame/revive/src/tests/stipends.rs +++ b/substrate/frame/revive/src/tests/stipends.rs @@ -16,13 +16,13 @@ // limitations under the License. use crate::{ - test_utils::builder::Contract, - tests::{builder, ExtBuilder, Test}, Code, Config, + test_utils::builder::Contract, + tests::{ExtBuilder, Test, builder}, }; use alloy_core::sol_types::SolCall; use frame_support::traits::fungible::Mutate; -use pallet_revive_fixtures::{compile_module_with_type, FixtureType, StipendTest}; +use pallet_revive_fixtures::{FixtureType, StipendTest, compile_module_with_type}; #[test] fn evm_call_stipends_work_for_transfers() { diff --git a/substrate/frame/revive/src/tracing.rs b/substrate/frame/revive/src/tracing.rs index 40954d0d9d31c..217b7318876a3 100644 --- a/substrate/frame/revive/src/tracing.rs +++ b/substrate/frame/revive/src/tracing.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{evm::Bytes, primitives::ExecReturnValue, Code, DispatchError, Key, Weight}; +use crate::{Code, DispatchError, Key, Weight, evm::Bytes, primitives::ExecReturnValue}; use alloc::vec::Vec; use environmental::environmental; use sp_core::{H160, H256, U256}; diff --git a/substrate/frame/revive/src/transient_storage.rs b/substrate/frame/revive/src/transient_storage.rs index 8cfc00df53d25..6ea7e00175f86 100644 --- a/substrate/frame/revive/src/transient_storage.rs +++ b/substrate/frame/revive/src/transient_storage.rs @@ -18,9 +18,9 @@ //! This module contains routines for accessing and altering a contract transient storage. use crate::{ + Config, Error, exec::{AccountIdOf, Key}, storage::WriteOutcome, - Config, Error, }; use alloc::{collections::BTreeMap, vec::Vec}; use codec::Encode; @@ -343,7 +343,7 @@ impl TransientStorage { #[cfg(test)] mod tests { use super::*; - use crate::{test_utils::*, tests::Test, Error}; + use crate::{Error, test_utils::*, tests::Test}; use core::u32::MAX; // Calculate the allocation size for the given entry. diff --git a/substrate/frame/revive/src/vm/evm.rs b/substrate/frame/revive/src/vm/evm.rs index 643c7e2827b98..6164c42a859b7 100644 --- a/substrate/frame/revive/src/vm/evm.rs +++ b/substrate/frame/revive/src/vm/evm.rs @@ -15,12 +15,12 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ + AccountIdOf, CodeInfo, Config, ContractBlob, DispatchError, Error, H256, LOG_TARGET, Weight, debug::DebugSettings, precompiles::Token, tracing, - vm::{evm::instructions::exec_instruction, BytecodeType, ExecResult, Ext}, + vm::{BytecodeType, ExecResult, Ext, evm::instructions::exec_instruction}, weights::WeightInfo, - AccountIdOf, CodeInfo, Config, ContractBlob, DispatchError, Error, Weight, H256, LOG_TARGET, }; use alloc::vec::Vec; use core::{convert::Infallible, ops::ControlFlow}; diff --git a/substrate/frame/revive/src/vm/evm/instructions/arithmetic.rs b/substrate/frame/revive/src/vm/evm/instructions/arithmetic.rs index bd9bbb505389b..a74fa0ee566fa 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/arithmetic.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/arithmetic.rs @@ -21,11 +21,11 @@ mod modular; use modular::Modular; use crate::{ + Error, U256, vm::{ - evm::{interpreter::Halt, EVMGas, Interpreter}, Ext, + evm::{EVMGas, Interpreter, interpreter::Halt}, }, - Error, U256, }; use core::ops::ControlFlow; use revm::interpreter::gas::{EXP, LOW, MID, VERYLOW}; diff --git a/substrate/frame/revive/src/vm/evm/instructions/arithmetic/i256.rs b/substrate/frame/revive/src/vm/evm/instructions/arithmetic/i256.rs index e43de27cede3b..10e881681d1c8 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/arithmetic/i256.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/arithmetic/i256.rs @@ -139,11 +139,7 @@ pub fn i256_mod(mut first: U256, mut second: U256) -> U256 { // Set sign bit to zero u256_remove_sign(&mut r); - if first_sign == Sign::Minus { - two_compl(r) - } else { - r - } + if first_sign == Sign::Minus { two_compl(r) } else { r } } #[cfg(test)] diff --git a/substrate/frame/revive/src/vm/evm/instructions/bitwise.rs b/substrate/frame/revive/src/vm/evm/instructions/bitwise.rs index 4172333bba555..78cd645ce8771 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/bitwise.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/bitwise.rs @@ -19,11 +19,11 @@ mod bits; use super::{arithmetic::i256::i256_cmp, utility::as_usize_saturated}; use crate::{ + U256, vm::{ - evm::{interpreter::Halt, EVMGas, Interpreter}, Ext, + evm::{EVMGas, Interpreter, interpreter::Halt}, }, - U256, }; use bits::Bits; use core::{cmp::Ordering, ops::ControlFlow}; @@ -320,15 +320,17 @@ mod tests { test_interpreter!(interpreter); for test in test_cases { - assert!((|| { - interpreter.stack.push(test.value)?; - interpreter.stack.push(test.shift)?; - shl(&mut interpreter)?; - let [res] = interpreter.stack.popn::<1>()?; - assert_eq!(res, test.expected); - ControlFlow::Continue(()) - })() - .is_continue()); + assert!( + (|| { + interpreter.stack.push(test.value)?; + interpreter.stack.push(test.shift)?; + shl(&mut interpreter)?; + let [res] = interpreter.stack.popn::<1>()?; + assert_eq!(res, test.expected); + ControlFlow::Continue(()) + })() + .is_continue() + ); } } @@ -444,15 +446,17 @@ mod tests { test_interpreter!(interpreter); for test in test_cases { - assert!((|| { - interpreter.stack.push(test.value)?; - interpreter.stack.push(test.shift)?; - shr(&mut interpreter)?; - let [res] = interpreter.stack.popn::<1>()?; - assert_eq!(res, test.expected); - ControlFlow::Continue(()) - })() - .is_continue()); + assert!( + (|| { + interpreter.stack.push(test.value)?; + interpreter.stack.push(test.shift)?; + shr(&mut interpreter)?; + let [res] = interpreter.stack.popn::<1>()?; + assert_eq!(res, test.expected); + ControlFlow::Continue(()) + })() + .is_continue() + ); } } @@ -613,15 +617,17 @@ mod tests { test_interpreter!(interpreter); for test in test_cases { - assert!((|| { - interpreter.stack.push(test.value)?; - interpreter.stack.push(test.shift)?; - sar(&mut interpreter)?; - let [res] = interpreter.stack.popn::<1>()?; - assert_eq!(res, test.expected); - ControlFlow::Continue(()) - })() - .is_continue()); + assert!( + (|| { + interpreter.stack.push(test.value)?; + interpreter.stack.push(test.shift)?; + sar(&mut interpreter)?; + let [res] = interpreter.stack.popn::<1>()?; + assert_eq!(res, test.expected); + ControlFlow::Continue(()) + })() + .is_continue() + ); } } @@ -645,15 +651,17 @@ mod tests { test_interpreter!(interpreter); for test in test_cases.iter() { - assert!((|| { - interpreter.stack.push(test.input)?; - interpreter.stack.push(U256::from(test.index))?; - byte(&mut interpreter)?; - let [res] = interpreter.stack.popn::<1>()?; - assert_eq!(res, test.expected, "Failed at index: {}", test.index); - ControlFlow::Continue(()) - })() - .is_continue()); + assert!( + (|| { + interpreter.stack.push(test.input)?; + interpreter.stack.push(U256::from(test.index))?; + byte(&mut interpreter)?; + let [res] = interpreter.stack.popn::<1>()?; + assert_eq!(res, test.expected, "Failed at index: {}", test.index); + ControlFlow::Continue(()) + })() + .is_continue() + ); } } @@ -703,18 +711,20 @@ mod tests { test_interpreter!(interpreter); for test in test_cases.iter() { - assert!((|| { - interpreter.stack.push(test.value)?; - clz(&mut interpreter)?; - let [res] = interpreter.stack.popn::<1>()?; - assert_eq!( - res, test.expected, - "CLZ for value {:#x} failed. Expected: {}, Got: {}", - test.value, test.expected, res - ); - ControlFlow::Continue(()) - })() - .is_continue()); + assert!( + (|| { + interpreter.stack.push(test.value)?; + clz(&mut interpreter)?; + let [res] = interpreter.stack.popn::<1>()?; + assert_eq!( + res, test.expected, + "CLZ for value {:#x} failed. Expected: {}, Got: {}", + test.value, test.expected, res + ); + ControlFlow::Continue(()) + })() + .is_continue() + ); } } } diff --git a/substrate/frame/revive/src/vm/evm/instructions/block_info.rs b/substrate/frame/revive/src/vm/evm/instructions/block_info.rs index 4c770648c197d..9b503ab9c3d83 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/block_info.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/block_info.rs @@ -16,11 +16,11 @@ // limitations under the License. use crate::{ + Error, RuntimeCosts, vm::{ - evm::{interpreter::Halt, EVMGas, Interpreter, DIFFICULTY}, Ext, + evm::{DIFFICULTY, EVMGas, Interpreter, interpreter::Halt}, }, - Error, RuntimeCosts, }; use core::ops::ControlFlow; use revm::interpreter::gas::BASE; diff --git a/substrate/frame/revive/src/vm/evm/instructions/contract.rs b/substrate/frame/revive/src/vm/evm/instructions/contract.rs index 82f238137cd12..8757ca17f4eec 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/contract.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/contract.rs @@ -19,12 +19,12 @@ mod call_helpers; use super::utility::IntoAddress; use crate::{ + Code, DebugSettings, Error, H160, LOG_TARGET, Pallet, ReentrancyProtection, U256, exec::CallResources, vm::{ - evm::{interpreter::Halt, util::as_usize_or_halt, Interpreter}, Ext, RuntimeCosts, + evm::{Interpreter, interpreter::Halt, util::as_usize_or_halt}, }, - Code, DebugSettings, Error, Pallet, ReentrancyProtection, H160, LOG_TARGET, U256, }; use alloc::{vec, vec::Vec}; pub use call_helpers::{charge_call_gas, get_memory_in_and_out_ranges}; diff --git a/substrate/frame/revive/src/vm/evm/instructions/contract/call_helpers.rs b/substrate/frame/revive/src/vm/evm/instructions/contract/call_helpers.rs index 3038f1ec50164..9821973df1634 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/contract/call_helpers.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/contract/call_helpers.rs @@ -16,12 +16,12 @@ // limitations under the License. use crate::{ + Pallet, RuntimeCosts, precompiles::{All as AllPrecompiles, Precompiles}, vm::{ - evm::{interpreter::Halt, util::as_usize_or_halt, Interpreter}, Ext, + evm::{Interpreter, interpreter::Halt, util::as_usize_or_halt}, }, - Pallet, RuntimeCosts, }; use core::ops::{ControlFlow, Range}; use revm::interpreter::interpreter_action::CallScheme; diff --git a/substrate/frame/revive/src/vm/evm/instructions/control.rs b/substrate/frame/revive/src/vm/evm/instructions/control.rs index 658d564294a8f..62a605194e7ad 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/control.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/control.rs @@ -16,15 +16,15 @@ // limitations under the License. use crate::{ + Error, U256, vm::{ + Ext, evm::{ + EVMGas, Interpreter, interpreter::Halt, util::{as_usize_or_halt, as_usize_or_halt_with}, - EVMGas, Interpreter, }, - Ext, }, - Error, U256, }; use alloc::vec::Vec; use core::ops::ControlFlow; diff --git a/substrate/frame/revive/src/vm/evm/instructions/host.rs b/substrate/frame/revive/src/vm/evm/instructions/host.rs index d3cb9c77a5462..0b72a3e282855 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/host.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/host.rs @@ -15,18 +15,17 @@ // See the License for the specific language governing permissions and // limitations under the License. use crate::{ - limits, + DispatchError, Error, Key, LOG_TARGET, RuntimeCosts, U256, limits, metering::Token, storage::WriteOutcome, vec::Vec, vm::{ + Ext, evm::{ - instructions::utility::IntoAddress, interpreter::Halt, util::as_usize_or_halt, - Interpreter, + Interpreter, instructions::utility::IntoAddress, interpreter::Halt, + util::as_usize_or_halt, }, - Ext, }, - DispatchError, Error, Key, RuntimeCosts, LOG_TARGET, U256, }; use core::ops::ControlFlow; diff --git a/substrate/frame/revive/src/vm/evm/instructions/memory.rs b/substrate/frame/revive/src/vm/evm/instructions/memory.rs index 150d547131e07..50c77c14191e3 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/memory.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/memory.rs @@ -16,14 +16,14 @@ // limitations under the License. use crate::{ + Error, U256, vm::{ - evm::{interpreter::Halt, util::as_usize_or_halt, EVMGas, Interpreter}, Ext, + evm::{EVMGas, Interpreter, interpreter::Halt, util::as_usize_or_halt}, }, - Error, U256, }; use core::{cmp::max, ops::ControlFlow}; -use revm::interpreter::gas::{copy_cost_verylow, BASE, VERYLOW}; +use revm::interpreter::gas::{BASE, VERYLOW, copy_cost_verylow}; /// Implements the MLOAD instruction. /// diff --git a/substrate/frame/revive/src/vm/evm/instructions/mod.rs b/substrate/frame/revive/src/vm/evm/instructions/mod.rs index e15be8cfee16f..e74fed961af77 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/mod.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/mod.rs @@ -17,7 +17,7 @@ /// EVM opcode implementations. use super::interpreter::Interpreter; -use crate::vm::{evm::Halt, Ext}; +use crate::vm::{Ext, evm::Halt}; use revm::bytecode::opcode::*; /// Arithmetic operations (ADD, SUB, MUL, DIV, etc.). diff --git a/substrate/frame/revive/src/vm/evm/instructions/stack.rs b/substrate/frame/revive/src/vm/evm/instructions/stack.rs index c29a220602b8b..26b2cf656f1b9 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/stack.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/stack.rs @@ -16,11 +16,11 @@ // limitations under the License. use crate::{ + U256, vm::{ - evm::{interpreter::Halt, EVMGas, Interpreter}, Ext, + evm::{EVMGas, Interpreter, interpreter::Halt}, }, - U256, }; use core::ops::ControlFlow; use revm::interpreter::gas::{BASE, VERYLOW}; diff --git a/substrate/frame/revive/src/vm/evm/instructions/system.rs b/substrate/frame/revive/src/vm/evm/instructions/system.rs index 129d88b6aca81..66e3698c1ada2 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/system.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/system.rs @@ -17,12 +17,12 @@ use super::utility::as_usize_saturated; use crate::{ + Config, Error, U256, address::AddressMapper, vm::{ - evm::{interpreter::Halt, util::as_usize_or_halt, EVMGas, Interpreter}, Ext, RuntimeCosts, + evm::{EVMGas, Interpreter, interpreter::Halt, util::as_usize_or_halt}, }, - Config, Error, U256, }; use core::ops::ControlFlow; use revm::interpreter::gas::{BASE, VERYLOW}; diff --git a/substrate/frame/revive/src/vm/evm/instructions/tx_info.rs b/substrate/frame/revive/src/vm/evm/instructions/tx_info.rs index 83dd1cb7e1bed..76f6c6222c55b 100644 --- a/substrate/frame/revive/src/vm/evm/instructions/tx_info.rs +++ b/substrate/frame/revive/src/vm/evm/instructions/tx_info.rs @@ -16,12 +16,12 @@ // limitations under the License. use crate::{ + Config, Error, address::AddressMapper, vm::{ - evm::{interpreter::Halt, Interpreter}, Ext, RuntimeCosts, + evm::{Interpreter, interpreter::Halt}, }, - Config, Error, }; use core::ops::ControlFlow; diff --git a/substrate/frame/revive/src/vm/evm/interpreter.rs b/substrate/frame/revive/src/vm/evm/interpreter.rs index 97fd16a87b1d3..fe98b6e12aa2a 100644 --- a/substrate/frame/revive/src/vm/evm/interpreter.rs +++ b/substrate/frame/revive/src/vm/evm/interpreter.rs @@ -17,13 +17,13 @@ use super::ExtBytecode; use crate::{ + Config, DispatchError, Error, Weight, primitives::ExecReturnValue, tracing::FrameTraceInfo, vm::{ - evm::{memory::Memory, stack::Stack}, ExecResult, Ext, + evm::{memory::Memory, stack::Stack}, }, - Config, DispatchError, Error, Weight, }; use alloc::vec::Vec; use pallet_revive_uapi::ReturnFlags; diff --git a/substrate/frame/revive/src/vm/evm/memory.rs b/substrate/frame/revive/src/vm/evm/memory.rs index c793c7c3b89da..3b3679cde7f7d 100644 --- a/substrate/frame/revive/src/vm/evm/memory.rs +++ b/substrate/frame/revive/src/vm/evm/memory.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{vm::evm::Halt, Config, Error}; +use crate::{Config, Error, vm::evm::Halt}; use alloc::vec::Vec; use core::ops::{ControlFlow, Range}; diff --git a/substrate/frame/revive/src/vm/evm/stack.rs b/substrate/frame/revive/src/vm/evm/stack.rs index 7ab47ded45527..f7d9a384494fd 100644 --- a/substrate/frame/revive/src/vm/evm/stack.rs +++ b/substrate/frame/revive/src/vm/evm/stack.rs @@ -17,7 +17,7 @@ //! Custom EVM stack implementation using sp_core::U256 -use crate::{limits::EVM_STACK_LIMIT, vm::evm::interpreter::Halt, Config, Error}; +use crate::{Config, Error, limits::EVM_STACK_LIMIT, vm::evm::interpreter::Halt}; use alloc::vec::Vec; use core::ops::ControlFlow; use sp_core::{H160, H256, U256}; diff --git a/substrate/frame/revive/src/vm/evm/util.rs b/substrate/frame/revive/src/vm/evm/util.rs index a19084d210c2b..9743f3ccd9e00 100644 --- a/substrate/frame/revive/src/vm/evm/util.rs +++ b/substrate/frame/revive/src/vm/evm/util.rs @@ -14,7 +14,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use crate::{vm::evm::interpreter::Halt, Config, Error, U256}; +use crate::{Config, Error, U256, vm::evm::interpreter::Halt}; use core::ops::ControlFlow; /// Helper function to convert U256 to usize, checking for overflow diff --git a/substrate/frame/revive/src/vm/mod.rs b/substrate/frame/revive/src/vm/mod.rs index ff58b525f4cb2..edb88d3e5a0ee 100644 --- a/substrate/frame/revive/src/vm/mod.rs +++ b/substrate/frame/revive/src/vm/mod.rs @@ -25,12 +25,12 @@ mod runtime_costs; pub use runtime_costs::RuntimeCosts; use crate::{ + AccountIdOf, BalanceOf, CodeInfoOf, CodeRemoved, Config, Error, ExecConfig, ExecError, + HoldReason, LOG_TARGET, Pallet, PristineCode, StorageDeposit, Weight, exec::{ExecResult, Executable, ExportedFunction, Ext}, frame_support::{ensure, error::BadOrigin}, metering::{ResourceMeter, State, Token}, weights::WeightInfo, - AccountIdOf, BalanceOf, CodeInfoOf, CodeRemoved, Config, Error, ExecConfig, ExecError, - HoldReason, Pallet, PristineCode, StorageDeposit, Weight, LOG_TARGET, }; use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; diff --git a/substrate/frame/revive/src/vm/pvm.rs b/substrate/frame/revive/src/vm/pvm.rs index 712e03aec847f..c7e9ebcf3a0e2 100644 --- a/substrate/frame/revive/src/vm/pvm.rs +++ b/substrate/frame/revive/src/vm/pvm.rs @@ -20,13 +20,13 @@ pub mod env; use crate::{ + Code, Config, Error, LOG_TARGET, Pallet, ReentrancyProtection, RuntimeCosts, SENTINEL, exec::{CallResources, ExecError, ExecResult, Ext, Key}, limits, metering::ChargedAmount, precompiles::{All as AllPrecompiles, Precompiles}, primitives::ExecReturnValue, tracing::FrameTraceInfo, - Code, Config, Error, Pallet, ReentrancyProtection, RuntimeCosts, LOG_TARGET, SENTINEL, }; use alloc::{vec, vec::Vec}; use codec::Encode; @@ -216,11 +216,7 @@ impl PolkaVmInstance for polkavm::RawInstance { impl From<&ExecReturnValue> for ReturnErrorCode { fn from(from: &ExecReturnValue) -> Self { - if from.flags.contains(ReturnFlags::REVERT) { - Self::CalleeReverted - } else { - Self::Success - } + if from.flags.contains(ReturnFlags::REVERT) { Self::CalleeReverted } else { Self::Success } } } @@ -269,9 +265,7 @@ impl fmt::Display for TrapReason { /// We need this access as a macro because sometimes hiding the lifetimes behind /// a function won't work out. macro_rules! charge_gas { - ($runtime:expr, $costs:expr) => {{ - $runtime.ext.frame_meter_mut().charge_weight_token($costs) - }}; + ($runtime:expr, $costs:expr) => {{ $runtime.ext.frame_meter_mut().charge_weight_token($costs) }}; } /// The kind of call that should be performed. diff --git a/substrate/frame/revive/src/vm/pvm/env.rs b/substrate/frame/revive/src/vm/pvm/env.rs index b916fb961ea98..8bc3b523660cf 100644 --- a/substrate/frame/revive/src/vm/pvm/env.rs +++ b/substrate/frame/revive/src/vm/pvm/env.rs @@ -18,13 +18,13 @@ use super::*; use crate::{ + AccountIdOf, CodeInfo, Config, ContractBlob, Error, SENTINEL, Weight, address::AddressMapper, debug::DebugSettings, exec::Ext, limits, primitives::ExecReturnValue, - vm::{calculate_code_deposit, BytecodeType, ExportedFunction, RuntimeCosts}, - AccountIdOf, CodeInfo, Config, ContractBlob, Error, Weight, SENTINEL, + vm::{BytecodeType, ExportedFunction, RuntimeCosts, calculate_code_deposit}, }; use alloc::vec::Vec; use core::mem; diff --git a/substrate/frame/revive/src/vm/runtime_costs.rs b/substrate/frame/revive/src/vm/runtime_costs.rs index ed56512045ce0..80fd6fb61d54a 100644 --- a/substrate/frame/revive/src/vm/runtime_costs.rs +++ b/substrate/frame/revive/src/vm/runtime_costs.rs @@ -16,10 +16,10 @@ // limitations under the License. use crate::{ - limits, metering::Token, weightinfo_extension::OnFinalizeBlockParts, weights::WeightInfo, - Config, + Config, limits, metering::Token, weightinfo_extension::OnFinalizeBlockParts, + weights::WeightInfo, }; -use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}; +use frame_support::weights::{Weight, constants::WEIGHT_REF_TIME_PER_SECOND}; /// Current approximation of the gas/s consumption considering /// EVM execution over compiled WASM (on 4.4Ghz CPU).