diff --git a/CHANGELOG.md b/CHANGELOG.md index e9f8ff4054f..491f0b2e7f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -190,6 +190,7 @@ See [the compatibility section](https://use.ink/faq/migrating-from-ink-4-to-5/#c - [Drink backend] Backend choice ‒ [#1864](https://github.com/use-ink/ink/pull/1864) - [Drink backend] Backend traits - [#1857](https://github.com/use-ink/ink/pull/1857) - [Drink backend] Abstract error and result structs - [#1844](https://github.com/use-ink/ink/pull/1844) +- Added support for caller_is_root - [#2310] (https://github.com/use-ink/ink/pull/2310) #### Changed - Use name-only syntax for `anonymous` ink! event item configuration argument - [#2140](https://github.com/use-ink/ink/pull/2140) diff --git a/crates/allocator/src/bump.rs b/crates/allocator/src/bump.rs index 16db4bf7434..e1c27026393 100644 --- a/crates/allocator/src/bump.rs +++ b/crates/allocator/src/bump.rs @@ -18,10 +18,7 @@ //! is `64KiB`). We will request new pages of memory as needed until we run out of memory, //! at which point we will crash with an `OOM` error instead of freeing any memory. -use core::alloc::{ - GlobalAlloc, - Layout, -}; +use core::alloc::{GlobalAlloc, Layout}; /// A page in Wasm is `64KiB` const PAGE_SIZE: usize = 64 * 1024; @@ -357,10 +354,7 @@ mod tests { #[cfg(all(test, feature = "ink-fuzz-tests"))] mod fuzz_tests { use super::*; - use quickcheck::{ - quickcheck, - TestResult, - }; + use quickcheck::{quickcheck, TestResult}; use std::mem::size_of; #[quickcheck] @@ -449,13 +443,13 @@ mod fuzz_tests { let mut inner = InnerAlloc::new(); if sequence.is_empty() { - return TestResult::discard() + return TestResult::discard(); } // We don't want any negative numbers so we can be sure our conversions to `usize` // later are valid if !sequence.iter().all(|n| n.is_positive()) { - return TestResult::discard() + return TestResult::discard(); } // We can't just use `required_pages(Iterator::sum())` here because it ends up @@ -468,7 +462,7 @@ mod fuzz_tests { // We know this is going to end up overflowing, we'll check this case in a // different test if pages_required > max_pages { - return TestResult::discard() + return TestResult::discard(); } let mut expected_alloc_start = 0; @@ -532,13 +526,13 @@ mod fuzz_tests { let mut inner = InnerAlloc::new(); if sequence.is_empty() { - return TestResult::discard() + return TestResult::discard(); } // We don't want any negative numbers so we can be sure our conversions to `usize` // later are valid if !sequence.iter().all(|n| n.is_positive()) { - return TestResult::discard() + return TestResult::discard(); } // We can't just use `required_pages(Iterator::sum())` here because it ends up @@ -551,7 +545,7 @@ mod fuzz_tests { // We want to explicitly test for the case where a series of allocations // eventually runs out of pages of memory if pages_required <= max_pages { - return TestResult::discard() + return TestResult::discard(); } let mut results = vec![]; diff --git a/crates/e2e/macro/src/codegen.rs b/crates/e2e/macro/src/codegen.rs index df59283007e..7d82923848c 100644 --- a/crates/e2e/macro/src/codegen.rs +++ b/crates/e2e/macro/src/codegen.rs @@ -13,10 +13,7 @@ // limitations under the License. use crate::{ - config::{ - Backend, - Node, - }, + config::{Backend, Node}, ir, }; use derive_more::From; diff --git a/crates/e2e/macro/src/config.rs b/crates/e2e/macro/src/config.rs index 5cb27544f00..fc3df808787 100644 --- a/crates/e2e/macro/src/config.rs +++ b/crates/e2e/macro/src/config.rs @@ -52,12 +52,12 @@ impl Node { /// /// Returns `None` if [`Self::Auto`] and `CONTRACTS_NODE_URL` not specified. pub fn url(&self) -> Option { - std::env::var("CONTRACTS_NODE_URL").ok().or_else(|| { - match self { + std::env::var("CONTRACTS_NODE_URL") + .ok() + .or_else(|| match self { Node::Auto => None, Node::Url(url) => Some(url.clone()), - } - }) + }) } } @@ -112,10 +112,7 @@ impl E2EConfig { #[cfg(test)] mod tests { use super::*; - use darling::{ - ast::NestedMeta, - FromMeta, - }; + use darling::{ast::NestedMeta, FromMeta}; use quote::quote; #[test] diff --git a/crates/e2e/macro/src/ir.rs b/crates/e2e/macro/src/ir.rs index ccbd4a71170..9d6d7d567f9 100644 --- a/crates/e2e/macro/src/ir.rs +++ b/crates/e2e/macro/src/ir.rs @@ -13,10 +13,7 @@ // limitations under the License. use crate::config::E2EConfig; -use darling::{ - ast::NestedMeta, - FromMeta, -}; +use darling::{ast::NestedMeta, FromMeta}; use proc_macro2::TokenStream as TokenStream2; /// The End-to-End test with all required information. diff --git a/crates/e2e/sandbox/src/api.rs b/crates/e2e/sandbox/src/api.rs index 01fe8d48367..78de0e53012 100644 --- a/crates/e2e/sandbox/src/api.rs +++ b/crates/e2e/sandbox/src/api.rs @@ -5,9 +5,7 @@ pub mod timestamp_api; pub mod prelude { pub use super::{ - balance_api::BalanceAPI, - contracts_api::ContractAPI, - system_api::SystemAPI, + balance_api::BalanceAPI, contracts_api::ContractAPI, system_api::SystemAPI, timestamp_api::TimestampAPI, }; } diff --git a/crates/e2e/sandbox/src/api/balance_api.rs b/crates/e2e/sandbox/src/api/balance_api.rs index 70fb0e7ba8a..3305c03da03 100644 --- a/crates/e2e/sandbox/src/api/balance_api.rs +++ b/crates/e2e/sandbox/src/api/balance_api.rs @@ -1,11 +1,5 @@ -use crate::{ - AccountIdFor, - Sandbox, -}; -use frame_support::{ - sp_runtime::DispatchError, - traits::fungible::Mutate, -}; +use crate::{AccountIdFor, Sandbox}; +use frame_support::{sp_runtime::DispatchError, traits::fungible::Mutate}; type BalanceOf = ::Balance; diff --git a/crates/e2e/sandbox/src/api/contracts_api.rs b/crates/e2e/sandbox/src/api/contracts_api.rs index c02c5c27f14..a6cd8adb292 100644 --- a/crates/e2e/sandbox/src/api/contracts_api.rs +++ b/crates/e2e/sandbox/src/api/contracts_api.rs @@ -1,21 +1,11 @@ use crate::{ - AccountIdFor, - ContractExecResultFor, - ContractInstantiateResultFor, - EventRecordOf, + AccountIdFor, ContractExecResultFor, ContractInstantiateResultFor, EventRecordOf, Sandbox, }; -use frame_support::{ - traits::fungible::Inspect, - weights::Weight, -}; +use frame_support::{traits::fungible::Inspect, weights::Weight}; use frame_system::Config as SysConfig; use pallet_contracts::{ - Code, - CodeUploadResult, - CollectEvents, - ContractInstantiateResult, - DebugInfo, + Code, CodeUploadResult, CollectEvents, ContractInstantiateResult, DebugInfo, Determinism, }; use scale::Decode as _; @@ -244,12 +234,7 @@ pub fn decode_debug_buffer(buffer: &[u8]) -> Vec { #[cfg(test)] mod tests { use super::*; - use crate::{ - api::prelude::*, - DefaultSandbox, - RuntimeEventOf, - RuntimeOf, - }; + use crate::{api::prelude::*, DefaultSandbox, RuntimeEventOf, RuntimeOf}; use frame_support::sp_runtime::traits::Hash; use pallet_contracts::Origin; diff --git a/crates/e2e/sandbox/src/api/system_api.rs b/crates/e2e/sandbox/src/api/system_api.rs index c743afe28a5..5fe5d946b29 100644 --- a/crates/e2e/sandbox/src/api/system_api.rs +++ b/crates/e2e/sandbox/src/api/system_api.rs @@ -1,13 +1,6 @@ -use crate::{ - EventRecordOf, - RuntimeCall, - Sandbox, -}; +use crate::{EventRecordOf, RuntimeCall, Sandbox}; use frame_support::sp_runtime::{ - traits::{ - Dispatchable, - Saturating, - }, + traits::{Dispatchable, Saturating}, DispatchResultWithInfo, }; use frame_system::pallet_prelude::BlockNumberFor; @@ -100,17 +93,10 @@ where #[cfg(test)] mod tests { use crate::{ - api::prelude::*, - DefaultSandbox, - RuntimeCall, - RuntimeEventOf, - RuntimeOf, - Sandbox, + api::prelude::*, DefaultSandbox, RuntimeCall, RuntimeEventOf, RuntimeOf, Sandbox, }; use frame_support::sp_runtime::{ - traits::Dispatchable, - AccountId32, - DispatchResultWithInfo, + traits::Dispatchable, AccountId32, DispatchResultWithInfo, }; fn make_transfer( diff --git a/crates/e2e/sandbox/src/api/timestamp_api.rs b/crates/e2e/sandbox/src/api/timestamp_api.rs index ea8a2679fac..1802ccb1174 100644 --- a/crates/e2e/sandbox/src/api/timestamp_api.rs +++ b/crates/e2e/sandbox/src/api/timestamp_api.rs @@ -39,10 +39,7 @@ where #[cfg(test)] mod tests { - use crate::{ - api::prelude::*, - DefaultSandbox, - }; + use crate::{api::prelude::*, DefaultSandbox}; #[test] fn getting_and_setting_timestamp_works() { diff --git a/crates/e2e/sandbox/src/lib.rs b/crates/e2e/sandbox/src/lib.rs index d4a46c4e1d9..832b9969316 100644 --- a/crates/e2e/sandbox/src/lib.rs +++ b/crates/e2e/sandbox/src/lib.rs @@ -5,42 +5,20 @@ pub mod macros; pub use frame_metadata::RuntimeMetadataPrefixed; pub use frame_support::weights::Weight; -use frame_support::{ - sp_runtime::traits::Dispatchable, - traits::fungible::Inspect, -}; -use frame_system::{ - pallet_prelude::BlockNumberFor, - EventRecord, -}; -pub use macros::{ - BlockBuilder, - DefaultSandbox, -}; -use pallet_contracts::{ - ContractExecResult, - ContractInstantiateResult, -}; +use frame_support::{sp_runtime::traits::Dispatchable, traits::fungible::Inspect}; +use frame_system::{pallet_prelude::BlockNumberFor, EventRecord}; +pub use macros::{BlockBuilder, DefaultSandbox}; +use pallet_contracts::{ContractExecResult, ContractInstantiateResult}; /// Export pallets that are used in [`crate::create_sandbox`] pub use { frame_support::sp_runtime::testing::H256, frame_support::{ self, - sp_runtime::{ - AccountId32, - DispatchError, - }, + sp_runtime::{AccountId32, DispatchError}, }, - frame_system, - pallet_balances, - pallet_contracts, - pallet_timestamp, - paste, + frame_system, pallet_balances, pallet_contracts, pallet_timestamp, paste, sp_core::crypto::Ss58Codec, - sp_externalities::{ - self, - Extension, - }, + sp_externalities::{self, Extension}, sp_io::TestExternalities, }; diff --git a/crates/e2e/sandbox/src/macros.rs b/crates/e2e/sandbox/src/macros.rs index 6b6feafa93d..aa096e738b1 100644 --- a/crates/e2e/sandbox/src/macros.rs +++ b/crates/e2e/sandbox/src/macros.rs @@ -2,10 +2,7 @@ use std::time::SystemTime; use frame_support::{ sp_runtime::{ - traits::{ - Header, - One, - }, + traits::{Header, One}, BuildStorage, }, traits::Hooks, diff --git a/crates/e2e/src/backend.rs b/crates/e2e/src/backend.rs index 6b72dfc53ba..415e41e7d32 100644 --- a/crates/e2e/src/backend.rs +++ b/crates/e2e/src/backend.rs @@ -14,30 +14,14 @@ use super::Keypair; use crate::{ - backend_calls::{ - InstantiateBuilder, - RemoveCodeBuilder, - UploadBuilder, - }, + backend_calls::{InstantiateBuilder, RemoveCodeBuilder, UploadBuilder}, builders::CreateBuilderPartial, - contract_results::{ - BareInstantiationResult, - InstantiateDryRunResult, - }, - CallBuilder, - CallBuilderFinal, - CallDryRunResult, - UploadResult, -}; -use ink_env::{ - DefaultEnvironment, - Environment, + contract_results::{BareInstantiationResult, InstantiateDryRunResult}, + CallBuilder, CallBuilderFinal, CallDryRunResult, UploadResult, }; +use ink_env::{DefaultEnvironment, Environment}; use jsonrpsee::core::async_trait; -use scale::{ - Decode, - Encode, -}; +use scale::{Decode, Encode}; use sp_weights::Weight; use subxt::dynamic::Value; diff --git a/crates/e2e/src/backend_calls.rs b/crates/e2e/src/backend_calls.rs index aedba9683bb..79e269c1f1a 100644 --- a/crates/e2e/src/backend_calls.rs +++ b/crates/e2e/src/backend_calls.rs @@ -13,22 +13,13 @@ // limitations under the License. use ink_env::Environment; -use scale::{ - Decode, - Encode, -}; +use scale::{Decode, Encode}; use sp_weights::Weight; use crate::{ - backend::BuilderClient, - builders::CreateBuilderPartial, - CallBuilderFinal, - CallDryRunResult, - CallResult, - ContractsBackend, - InstantiateDryRunResult, - InstantiationResult, - UploadResult, + backend::BuilderClient, builders::CreateBuilderPartial, CallBuilderFinal, + CallDryRunResult, CallResult, ContractsBackend, InstantiateDryRunResult, + InstantiationResult, UploadResult, }; use super::Keypair; diff --git a/crates/e2e/src/builders.rs b/crates/e2e/src/builders.rs index 93453c32d4c..f136427ab9a 100644 --- a/crates/e2e/src/builders.rs +++ b/crates/e2e/src/builders.rs @@ -14,14 +14,8 @@ use ink_env::{ call::{ - utils::{ - ReturnType, - Set, - Unset, - }, - CreateBuilder, - ExecutionInput, - LimitParamsV2, + utils::{ReturnType, Set, Unset}, + CreateBuilder, ExecutionInput, LimitParamsV2, }, Environment, }; diff --git a/crates/e2e/src/client_utils.rs b/crates/e2e/src/client_utils.rs index 69b9901fcd9..d97e93d4e4f 100644 --- a/crates/e2e/src/client_utils.rs +++ b/crates/e2e/src/client_utils.rs @@ -13,10 +13,7 @@ // limitations under the License. use crate::log_info; -use std::{ - collections::BTreeMap, - path::PathBuf, -}; +use std::{collections::BTreeMap, path::PathBuf}; /// Generate a unique salt based on the system time. pub fn salt() -> Vec { diff --git a/crates/e2e/src/contract_build.rs b/crates/e2e/src/contract_build.rs index c65357fd9e5..8de0fbf42c7 100644 --- a/crates/e2e/src/contract_build.rs +++ b/crates/e2e/src/contract_build.rs @@ -13,33 +13,14 @@ // limitations under the License. use contract_build::{ - BuildArtifacts, - BuildMode, - ExecuteArgs, - Features, - ImageVariant, - ManifestPath, - Network, - OptimizationPasses, - OutputType, - Target, - UnstableFlags, - Verbosity, + BuildArtifacts, BuildMode, ExecuteArgs, Features, ImageVariant, ManifestPath, + Network, OptimizationPasses, OutputType, Target, UnstableFlags, Verbosity, DEFAULT_MAX_MEMORY_PAGES, }; use std::{ - collections::{ - hash_map::Entry, - HashMap, - }, - path::{ - Path, - PathBuf, - }, - sync::{ - Mutex, - OnceLock, - }, + collections::{hash_map::Entry, HashMap}, + path::{Path, PathBuf}, + sync::{Mutex, OnceLock}, }; /// Builds the "root" contract (the contract in which the E2E tests are defined) together @@ -172,13 +153,11 @@ fn build_contract(path_to_cargo_toml: &Path) -> PathBuf { }; match contract_build::execute(args) { - Ok(build_result) => { - build_result - .dest_wasm - .expect("Wasm code artifact not generated") - .canonicalize() - .expect("Invalid dest bundle path") - } + Ok(build_result) => build_result + .dest_wasm + .expect("Wasm code artifact not generated") + .canonicalize() + .expect("Invalid dest bundle path"), Err(err) => { panic!( "contract build for {} failed: {err}", diff --git a/crates/e2e/src/contract_results.rs b/crates/e2e/src/contract_results.rs index 2c19473a270..fbee9f957ac 100644 --- a/crates/e2e/src/contract_results.rs +++ b/crates/e2e/src/contract_results.rs @@ -13,26 +13,13 @@ // limitations under the License. use ink::codegen::ContractCallBuilder; -use ink_env::{ - call::FromAccountId, - Environment, -}; -use ink_primitives::{ - ConstructorResult, - MessageResult, -}; +use ink_env::{call::FromAccountId, Environment}; +use ink_primitives::{ConstructorResult, MessageResult}; use pallet_contracts::{ - CodeUploadResult, - ContractExecResult, - ContractInstantiateResult, - ExecReturnValue, + CodeUploadResult, ContractExecResult, ContractInstantiateResult, ExecReturnValue, InstantiateReturnValue, }; -use std::{ - fmt, - fmt::Debug, - marker::PhantomData, -}; +use std::{fmt, fmt::Debug, marker::PhantomData}; /// Result of a contract instantiation using bare call. pub struct BareInstantiationResult { diff --git a/crates/e2e/src/events.rs b/crates/e2e/src/events.rs index 96c5a605d3b..15ecf849f31 100644 --- a/crates/e2e/src/events.rs +++ b/crates/e2e/src/events.rs @@ -18,10 +18,7 @@ use std::fmt::Debug; use subxt::{ events::StaticEvent, - ext::{ - scale_decode, - scale_encode, - }, + ext::{scale_decode, scale_encode}, }; /// A contract was successfully instantiated. diff --git a/crates/e2e/src/lib.rs b/crates/e2e/src/lib.rs index 61cfada3a84..d2183687fb1 100644 --- a/crates/e2e/src/lib.rs +++ b/crates/e2e/src/lib.rs @@ -34,50 +34,23 @@ mod subxt_client; mod xts; pub use crate::contract_build::build_root_and_contract_dependencies; -pub use backend::{ - ChainBackend, - ContractsBackend, - E2EBackend, -}; -pub use backend_calls::{ - CallBuilder, - InstantiateBuilder, -}; +pub use backend::{ChainBackend, ContractsBackend, E2EBackend}; +pub use backend_calls::{CallBuilder, InstantiateBuilder}; pub use contract_results::{ - CallDryRunResult, - CallResult, - InstantiateDryRunResult, - InstantiationResult, + CallDryRunResult, CallResult, InstantiateDryRunResult, InstantiationResult, UploadResult, }; pub use ink_e2e_macro::test; -pub use node_proc::{ - TestNodeProcess, - TestNodeProcessBuilder, -}; +pub use node_proc::{TestNodeProcess, TestNodeProcessBuilder}; #[cfg(feature = "sandbox")] -pub use sandbox_client::{ - preset, - Client as SandboxClient, -}; +pub use sandbox_client::{preset, Client as SandboxClient}; pub use sp_core::H256; pub use sp_keyring::AccountKeyring; -pub use subxt::{ - self, - backend::rpc::RpcClient, -}; -pub use subxt_client::{ - CallBuilderFinal, - Client, - Error, -}; +pub use subxt::{self, backend::rpc::RpcClient}; +pub use subxt_client::{CallBuilderFinal, Client, Error}; pub use subxt_signer::{ self, - sr25519::{ - self, - dev::*, - Keypair, - }, + sr25519::{self, dev::*, Keypair}, }; pub use tokio; pub use tracing_subscriber; @@ -86,19 +59,9 @@ pub use tracing_subscriber; pub use ink_sandbox::DefaultSandbox; use ink::codegen::ContractCallBuilder; -use ink_env::{ - call::FromAccountId, - ContractEnv, - Environment, -}; -use pallet_contracts::{ - ContractExecResult, - ContractInstantiateResult, -}; -use std::{ - cell::RefCell, - sync::Once, -}; +use ink_env::{call::FromAccountId, ContractEnv, Environment}; +use pallet_contracts::{ContractExecResult, ContractInstantiateResult}; +use std::{cell::RefCell, sync::Once}; use xts::ContractsApi; pub use subxt::PolkadotConfig; diff --git a/crates/e2e/src/node_proc.rs b/crates/e2e/src/node_proc.rs index 8df4f3cab26..fee652f7666 100644 --- a/crates/e2e/src/node_proc.rs +++ b/crates/e2e/src/node_proc.rs @@ -14,22 +14,11 @@ use sp_keyring::AccountKeyring; use std::{ - ffi::{ - OsStr, - OsString, - }, - io::{ - BufRead, - BufReader, - Read, - }, + ffi::{OsStr, OsString}, + io::{BufRead, BufReader, Read}, process, }; -use subxt::{ - backend::rpc::RpcClient, - Config, - OnlineClient, -}; +use subxt::{backend::rpc::RpcClient, Config, OnlineClient}; /// Spawn a local substrate node for testing. pub struct TestNodeProcess { @@ -89,7 +78,7 @@ where if let Err(err) = self.proc.kill() { let err = format!("Error killing node process {}: {}", self.proc.id(), err); tracing::error!("{}", err); - return Err(err) + return Err(err); } Ok(()) } @@ -173,14 +162,12 @@ where .map_err(|err| format!("Error initializing rpc client: {}", err))?; let client = OnlineClient::from_url(url.clone()).await; match client { - Ok(client) => { - Ok(TestNodeProcess { - proc, - rpc, - client, - url: url.clone(), - }) - } + Ok(client) => Ok(TestNodeProcess { + proc, + rpc, + client, + url: url.clone(), + }), Err(err) => { let err = format!("Failed to connect to node rpc at {url}: {err}"); tracing::error!("{}", err); @@ -229,10 +216,7 @@ fn find_substrate_port_from_output(r: impl Read + Send + 'static) -> u16 { #[cfg(test)] mod tests { use super::*; - use subxt::{ - backend::legacy::LegacyRpcMethods, - PolkadotConfig as SubxtConfig, - }; + use subxt::{backend::legacy::LegacyRpcMethods, PolkadotConfig as SubxtConfig}; #[tokio::test] #[allow(unused_assignments)] diff --git a/crates/e2e/src/sandbox_client.rs b/crates/e2e/src/sandbox_client.rs index fe5358e2d2c..368b0c9eeb4 100644 --- a/crates/e2e/src/sandbox_client.rs +++ b/crates/e2e/src/sandbox_client.rs @@ -14,61 +14,30 @@ use crate::{ backend::BuilderClient, - builders::{ - constructor_exec_input, - CreateBuilderPartial, - }, - client_utils::{ - salt, - ContractsRegistry, - }, + builders::{constructor_exec_input, CreateBuilderPartial}, + client_utils::{salt, ContractsRegistry}, contract_results::BareInstantiationResult, error::SandboxErr, - log_error, - CallBuilderFinal, - CallDryRunResult, - ChainBackend, - ContractsBackend, - E2EBackend, - InstantiateDryRunResult, - UploadResult, + log_error, CallBuilderFinal, CallDryRunResult, ChainBackend, ContractsBackend, + E2EBackend, InstantiateDryRunResult, UploadResult, }; use frame_support::traits::fungible::Inspect; use ink_sandbox::{ - api::prelude::*, - pallet_balances, - pallet_contracts, - AccountIdFor, - RuntimeCall, - Sandbox, - Weight, + api::prelude::*, pallet_balances, pallet_contracts, AccountIdFor, RuntimeCall, + Sandbox, Weight, }; use pallet_contracts::ContractResult; use ink_env::Environment; use jsonrpsee::core::async_trait; use pallet_contracts::{ - CodeUploadReturnValue, - ContractInstantiateResult, - InstantiateReturnValue, -}; -use scale::{ - Decode, - Encode, -}; -use sp_core::{ - sr25519::Pair, - Pair as _, -}; -use std::{ - marker::PhantomData, - path::PathBuf, -}; -use subxt::{ - dynamic::Value, - tx::TxPayload, + CodeUploadReturnValue, ContractInstantiateResult, InstantiateReturnValue, }; +use scale::{Decode, Encode}; +use sp_core::{sr25519::Pair, Pair as _}; +use std::{marker::PhantomData, path::PathBuf}; +use subxt::{dynamic::Value, tx::TxPayload}; use subxt_signer::sr25519::Keypair; type BalanceOf = ::Balance; @@ -293,11 +262,9 @@ where gas_required: result.gas_required, storage_deposit: result.storage_deposit, debug_message: result.debug_message, - result: result.result.map(|r| { - InstantiateReturnValue { - result: r.result, - account_id, - } + result: result.result.map(|r| InstantiateReturnValue { + result: r.result, + account_id, }), events: None, }; @@ -321,7 +288,7 @@ where Ok(result) => result, Err(err) => { log_error(&format!("Upload failed: {err:?}")); - return Err(SandboxErr::new(format!("bare_upload: {err:?}"))) + return Err(SandboxErr::new(format!("bare_upload: {err:?}"))); } }; @@ -463,13 +430,8 @@ where pub mod preset { pub mod mock_network { use ink_sandbox::{ - frame_system, - AccountIdFor, - BlockBuilder, - Extension, - RuntimeMetadataPrefixed, - Sandbox, - Snapshot, + frame_system, AccountIdFor, BlockBuilder, Extension, RuntimeMetadataPrefixed, + Sandbox, Snapshot, }; pub use pallet_contracts_mock_network::*; use sp_runtime::traits::Dispatchable; diff --git a/crates/e2e/src/subxt_client.rs b/crates/e2e/src/subxt_client.rs index ba70d5e3129..f4f05aabd7b 100644 --- a/crates/e2e/src/subxt_client.rs +++ b/crates/e2e/src/subxt_client.rs @@ -13,48 +13,26 @@ // limitations under the License. use super::{ - builders::{ - constructor_exec_input, - CreateBuilderPartial, - }, - events::{ - CodeStoredEvent, - ContractInstantiatedEvent, - EventWithTopics, - }, - log_error, - log_info, - sr25519, - ContractsApi, - InstantiateDryRunResult, - Keypair, + builders::{constructor_exec_input, CreateBuilderPartial}, + events::{CodeStoredEvent, ContractInstantiatedEvent, EventWithTopics}, + log_error, log_info, sr25519, ContractsApi, InstantiateDryRunResult, Keypair, }; use crate::{ backend::BuilderClient, contract_results::{ - BareInstantiationResult, - CallDryRunResult, - CallResult, - UploadResult, + BareInstantiationResult, CallDryRunResult, CallResult, UploadResult, }, }; use ink_env::{ call::{ - utils::{ - ReturnType, - Set, - }, - Call, - ExecutionInput, + utils::{ReturnType, Set}, + Call, ExecutionInput, }, Environment, }; use jsonrpsee::core::async_trait; use pallet_contracts::ContractResult; -use scale::{ - Decode, - Encode, -}; +use scale::{Decode, Encode}; use sp_weights::Weight; #[cfg(feature = "std")] use std::fmt::Debug; @@ -62,28 +40,16 @@ use std::path::PathBuf; use crate::{ backend::ChainBackend, - client_utils::{ - salt, - ContractsRegistry, - }, + client_utils::{salt, ContractsRegistry}, error::DryRunError, - events, - ContractsBackend, - E2EBackend, + events, ContractsBackend, E2EBackend, }; use subxt::{ blocks::ExtrinsicEvents, - config::{ - DefaultExtrinsicParams, - ExtrinsicParams, - }, + config::{DefaultExtrinsicParams, ExtrinsicParams}, error::DispatchError, events::EventDetails, - ext::scale_value::{ - Composite, - Value, - ValueDef, - }, + ext::scale_value::{Composite, Value, ValueDef}, tx::Signer, }; @@ -190,7 +156,7 @@ where log_error(&format!( "extrinsic for instantiate failed: {dispatch_error}" )); - return Err(Error::InstantiateExtrinsic(dispatch_error)) + return Err(Error::InstantiateExtrinsic(dispatch_error)); } } let account_id = account_id.expect("cannot extract `account_id` from events"); @@ -218,7 +184,7 @@ where log_info(&format!("upload dry run: {dry_run:?}")); if let Err(err) = dry_run { let dispatch_err = self.runtime_dispatch_error_to_subxt_dispatch_error(&err); - return Err(Error::UploadDryRun(dispatch_err)) + return Err(Error::UploadDryRun(dispatch_err)); } let tx_events = self.api.upload(signer, code, storage_deposit_limit).await; @@ -239,7 +205,7 @@ where uploaded.code_hash )); hash = Some(uploaded.code_hash); - break + break; } else if is_extrinsic_failed_event(&evt) { let metadata = self.api.client.metadata(); let dispatch_error = @@ -247,7 +213,7 @@ where .map_err(|e| Error::Decoding(e.to_string()))?; log_error(&format!("extrinsic for upload failed: {dispatch_error}")); - return Err(Error::UploadExtrinsic(dispatch_error)) + return Err(Error::UploadExtrinsic(dispatch_error)); } } @@ -444,7 +410,7 @@ where .map_err(|e| Error::Decoding(e.to_string()))?; log_error(&format!("extrinsic for call failed: {dispatch_error}")); - return Err(Error::CallExtrinsic(dispatch_error)) + return Err(Error::CallExtrinsic(dispatch_error)); } } @@ -559,7 +525,7 @@ where let dispatch_error = DispatchError::decode_from(evt.field_bytes(), metadata) .map_err(|e| Error::Decoding(e.to_string()))?; - return Err(Error::RemoveCodeExtrinsic(dispatch_error)) + return Err(Error::RemoveCodeExtrinsic(dispatch_error)); } } @@ -604,7 +570,7 @@ where DispatchError::decode_from(evt.field_bytes(), metadata) .map_err(|e| Error::Decoding(e.to_string()))?; log_error(&format!("extrinsic for call failed: {dispatch_error}")); - return Err(Error::CallExtrinsic(dispatch_error)) + return Err(Error::CallExtrinsic(dispatch_error)); } } diff --git a/crates/e2e/src/xts.rs b/crates/e2e/src/xts.rs index 0b2a43fdd03..7494d060701 100644 --- a/crates/e2e/src/xts.rs +++ b/crates/e2e/src/xts.rs @@ -12,34 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - log_info, - sr25519, - ContractExecResult, - ContractInstantiateResult, - Keypair, -}; +use super::{log_info, sr25519, ContractExecResult, ContractInstantiateResult, Keypair}; use ink_env::Environment; use core::marker::PhantomData; use pallet_contracts::CodeUploadResult; use sp_core::H256; use subxt::{ - backend::{ - legacy::LegacyRpcMethods, - rpc::RpcClient, - }, + backend::{legacy::LegacyRpcMethods, rpc::RpcClient}, blocks::ExtrinsicEvents, - config::{ - DefaultExtrinsicParams, - DefaultExtrinsicParamsBuilder, - ExtrinsicParams, - }, + config::{DefaultExtrinsicParams, DefaultExtrinsicParamsBuilder, ExtrinsicParams}, ext::scale_encode, - tx::{ - Signer, - TxStatus, - }, + tx::{Signer, TxStatus}, utils::MultiAddress, OnlineClient, }; diff --git a/crates/engine/src/chain_extension.rs b/crates/engine/src/chain_extension.rs index 09619795747..c3df6f7a30d 100644 --- a/crates/engine/src/chain_extension.rs +++ b/crates/engine/src/chain_extension.rs @@ -14,10 +14,7 @@ use super::Error; use derive_more::From; -use std::collections::{ - hash_map::Entry, - HashMap, -}; +use std::collections::{hash_map::Entry, HashMap}; /// Chain extension registry. /// diff --git a/crates/engine/src/exec_context.rs b/crates/engine/src/exec_context.rs index 4ee6daa50fe..e10f0e09e2a 100644 --- a/crates/engine/src/exec_context.rs +++ b/crates/engine/src/exec_context.rs @@ -12,12 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::types::{ - AccountId, - Balance, - BlockNumber, - BlockTimestamp, -}; +use super::types::{AccountId, Balance, BlockNumber, BlockTimestamp}; /// The context of a contract execution. #[cfg_attr(test, derive(Debug, PartialEq, Eq))] @@ -80,10 +75,7 @@ impl ExecContext { #[cfg(test)] mod tests { - use super::{ - AccountId, - ExecContext, - }; + use super::{AccountId, ExecContext}; #[test] fn basic_operations() { diff --git a/crates/engine/src/ext.rs b/crates/engine/src/ext.rs index 8a0bb963998..fb940f6505e 100644 --- a/crates/engine/src/ext.rs +++ b/crates/engine/src/ext.rs @@ -21,15 +21,8 @@ use crate::{ chain_extension::ChainExtensionHandler, database::Database, exec_context::ExecContext, - test_api::{ - DebugInfo, - EmittedEvent, - }, - types::{ - AccountId, - Balance, - BlockTimestamp, - }, + test_api::{DebugInfo, EmittedEvent}, + types::{AccountId, Balance, BlockTimestamp}, }; pub use pallet_contracts_uapi::ReturnErrorCode as Error; use scale::Encode; @@ -394,12 +387,8 @@ impl Engine { output: &mut [u8; 33], ) -> Result<(), Error> { use secp256k1::{ - ecdsa::{ - RecoverableSignature, - RecoveryId, - }, - Message, - SECP256K1, + ecdsa::{RecoverableSignature, RecoveryId}, + Message, SECP256K1, }; // In most implementations, the v is just 0 or 1 internally, but 27 was added diff --git a/crates/engine/src/hashing.rs b/crates/engine/src/hashing.rs index c05fd37e38e..4819facdefa 100644 --- a/crates/engine/src/hashing.rs +++ b/crates/engine/src/hashing.rs @@ -16,10 +16,7 @@ /// Conduct the BLAKE2 256-bit hash and place the result into `output`. pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) { - use ::blake2::digest::{ - consts::U32, - Digest as _, - }; + use ::blake2::digest::{consts::U32, Digest as _}; type Blake2b256 = ::blake2::Blake2b; @@ -31,10 +28,7 @@ pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) { /// Conduct the BLAKE2 128-bit hash and place the result into `output`. pub fn blake2b_128(input: &[u8], output: &mut [u8; 16]) { - use ::blake2::digest::{ - consts::U16, - Digest as _, - }; + use ::blake2::digest::{consts::U16, Digest as _}; type Blake2b128 = ::blake2::Blake2b; @@ -46,10 +40,7 @@ pub fn blake2b_128(input: &[u8], output: &mut [u8; 16]) { /// Conduct the KECCAK 256-bit hash and place the result into `output`. pub fn keccak_256(input: &[u8], output: &mut [u8; 32]) { - use sha3::{ - digest::generic_array::GenericArray, - Digest as _, - }; + use sha3::{digest::generic_array::GenericArray, Digest as _}; let mut hasher = sha3::Keccak256::new(); hasher.update(input); hasher.finalize_into(<&mut GenericArray>::from(&mut output[..])); @@ -57,10 +48,7 @@ pub fn keccak_256(input: &[u8], output: &mut [u8; 32]) { /// Conduct the SHA-2 256-bit hash and place the result into `output`. pub fn sha2_256(input: &[u8], output: &mut [u8; 32]) { - use sha2::{ - digest::generic_array::GenericArray, - Digest as _, - }; + use sha2::{digest::generic_array::GenericArray, Digest as _}; let mut hasher = sha2::Sha256::new(); hasher.update(input); hasher.finalize_into(<&mut GenericArray>::from(&mut output[..])); diff --git a/crates/engine/src/test_api.rs b/crates/engine/src/test_api.rs index 460faf774ad..9fdbdad7b43 100644 --- a/crates/engine/src/test_api.rs +++ b/crates/engine/src/test_api.rs @@ -14,14 +14,8 @@ use crate::{ ext::Engine, - types::{ - AccountId, - Balance, - BlockNumber, - BlockTimestamp, - }, - AccountError, - Error, + types::{AccountId, Balance, BlockNumber, BlockTimestamp}, + AccountError, Error, }; use std::collections::HashMap; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a62b96cbda1..ce79519b173 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12,17 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::ext::{ - Engine, - Error, -}; -use secp256k1::{ - ecdsa::RecoverableSignature, - Message, - PublicKey, - SecretKey, - SECP256K1, -}; +use crate::ext::{Engine, Error}; +use secp256k1::{ecdsa::RecoverableSignature, Message, PublicKey, SecretKey, SECP256K1}; /// The public methods of the `contracts` pallet write their result into an /// `output` buffer instead of returning them. Since we aim to emulate this diff --git a/crates/env/src/api.rs b/crates/env/src/api.rs index 654ea7987da..cb3a15df6e5 100644 --- a/crates/env/src/api.rs +++ b/crates/env/src/api.rs @@ -15,33 +15,16 @@ //! The public raw interface towards the host Wasm engine. use crate::{ - backend::{ - EnvBackend, - TypedEnvBackend, - }, + backend::{EnvBackend, TypedEnvBackend}, call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, - }, - engine::{ - EnvInstance, - OnInstance, + Call, CallParams, CallV1, ConstructorReturnType, CreateParams, DelegateCall, + FromAccountId, LimitParamsV1, LimitParamsV2, }, + engine::{EnvInstance, OnInstance}, event::Event, - hash::{ - CryptoHash, - HashOutput, - }, + hash::{CryptoHash, HashOutput}, types::Gas, - Environment, - Result, + Environment, Result, }; use ink_storage_traits::Storable; use pallet_contracts_uapi::ReturnFlags; @@ -729,6 +712,26 @@ where }) } +/// Checks whether the caller of the current contract is root. +/// +/// Note that only the origin of the call stack can be root. Hence this function returning +/// `true` implies that the contract is being called by the origin. +/// +/// A return value of `true` indicates that this contract is being called by a root origin, +/// and `false` indicates that the caller is a signed origin. +/// +/// # Errors +/// +/// If the returned value cannot be properly decoded. +pub fn caller_is_root() -> bool +where + E: Environment, +{ + ::on_instance(|instance| { + TypedEnvBackend::caller_is_root::(instance) + }) +} + /// Replace the contract code at the specified address with new code. /// /// # Note diff --git a/crates/env/src/arithmetic.rs b/crates/env/src/arithmetic.rs index 07707ef1a7c..e9daa41d246 100644 --- a/crates/env/src/arithmetic.rs +++ b/crates/env/src/arithmetic.rs @@ -14,24 +14,8 @@ //! Primitive traits for runtime arithmetic, copied from substrate -use core::ops::{ - Add, - AddAssign, - Div, - DivAssign, - Mul, - MulAssign, - Sub, - SubAssign, -}; -use num_traits::{ - checked_pow, - Bounded, - CheckedMul, - One, - Unsigned, - Zero, -}; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; +use num_traits::{checked_pow, Bounded, CheckedMul, One, Unsigned, Zero}; /// Types that allow for simple arithmetic operations. /// diff --git a/crates/env/src/backend.rs b/crates/env/src/backend.rs index 1ace832dfaf..219c9e1bb75 100644 --- a/crates/env/src/backend.rs +++ b/crates/env/src/backend.rs @@ -14,23 +14,12 @@ use crate::{ call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, + Call, CallParams, CallV1, ConstructorReturnType, CreateParams, DelegateCall, + FromAccountId, LimitParamsV1, LimitParamsV2, }, event::Event, - hash::{ - CryptoHash, - HashOutput, - }, - Environment, - Result, + hash::{CryptoHash, HashOutput}, + Environment, Result, }; use ink_storage_traits::Storable; pub use pallet_contracts_uapi::ReturnFlags; @@ -413,6 +402,15 @@ pub trait TypedEnvBackend: EnvBackend { where E: Environment; + /// Checks whether the caller of the current contract is root. + /// + /// # Note + /// + /// For more details visit: [`caller_is_root`][`crate::caller_is_root`] + fn caller_is_root(&mut self) -> bool + where + E: Environment; + /// Retrieves the code hash of the contract at the given `account` id. /// /// # Note diff --git a/crates/env/src/call/call_builder/call.rs b/crates/env/src/call/call_builder/call.rs index 087d700a61f..c7ece152dfd 100644 --- a/crates/env/src/call/call_builder/call.rs +++ b/crates/env/src/call/call_builder/call.rs @@ -14,20 +14,11 @@ use crate::{ call::{ - common::{ - ReturnType, - Set, - Unset, - }, + common::{ReturnType, Set, Unset}, execution::EmptyArgumentList, - CallBuilder, - CallParams, - CallV1, - ExecutionInput, + CallBuilder, CallParams, CallV1, ExecutionInput, }, - Environment, - Error, - Gas, + Environment, Error, Gas, }; use num_traits::Zero; use pallet_contracts_uapi::CallFlags; diff --git a/crates/env/src/call/call_builder/call_v1.rs b/crates/env/src/call/call_builder/call_v1.rs index e3563d1bb1d..47d7c77dbbc 100644 --- a/crates/env/src/call/call_builder/call_v1.rs +++ b/crates/env/src/call/call_builder/call_v1.rs @@ -15,18 +15,11 @@ use super::CallParams; use crate::{ call::{ - common::{ - ReturnType, - Set, - Unset, - }, + common::{ReturnType, Set, Unset}, execution::EmptyArgumentList, - CallBuilder, - ExecutionInput, + CallBuilder, ExecutionInput, }, - Environment, - Error, - Gas, + Environment, Error, Gas, }; use num_traits::Zero; use pallet_contracts_uapi::CallFlags; diff --git a/crates/env/src/call/call_builder/delegate.rs b/crates/env/src/call/call_builder/delegate.rs index 9473432e714..981826251fa 100644 --- a/crates/env/src/call/call_builder/delegate.rs +++ b/crates/env/src/call/call_builder/delegate.rs @@ -14,18 +14,11 @@ use crate::{ call::{ - common::{ - ReturnType, - Set, - Unset, - }, + common::{ReturnType, Set, Unset}, execution::EmptyArgumentList, - CallBuilder, - CallParams, - ExecutionInput, + CallBuilder, CallParams, ExecutionInput, }, - Environment, - Error, + Environment, Error, }; use pallet_contracts_uapi::CallFlags; diff --git a/crates/env/src/call/call_builder/mod.rs b/crates/env/src/call/call_builder/mod.rs index bc9acaead7c..9772a7d8cbb 100644 --- a/crates/env/src/call/call_builder/mod.rs +++ b/crates/env/src/call/call_builder/mod.rs @@ -22,14 +22,8 @@ pub use delegate::DelegateCall; use crate::{ call::{ - utils::{ - EmptyArgumentList, - ReturnType, - Set, - Unset, - }, - Execution, - ExecutionInput, + utils::{EmptyArgumentList, ReturnType, Set, Unset}, + Execution, ExecutionInput, }, Environment, }; diff --git a/crates/env/src/call/create_builder.rs b/crates/env/src/call/create_builder.rs index 34a17dd76d6..e4bd8a335c7 100644 --- a/crates/env/src/call/create_builder.rs +++ b/crates/env/src/call/create_builder.rs @@ -14,18 +14,10 @@ use crate::{ call::{ - utils::{ - EmptyArgumentList, - ReturnType, - Set, - Unset, - }, - ExecutionInput, - Selector, + utils::{EmptyArgumentList, ReturnType, Set, Unset}, + ExecutionInput, Selector, }, - ContractEnv, - Environment, - Error, + ContractEnv, Environment, Error, }; use core::marker::PhantomData; diff --git a/crates/env/src/call/execution.rs b/crates/env/src/call/execution.rs index 1a87a5dffe1..b3275d7d6dd 100644 --- a/crates/env/src/call/execution.rs +++ b/crates/env/src/call/execution.rs @@ -12,10 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - utils::ReturnType, - Selector, -}; +use super::{utils::ReturnType, Selector}; use crate::Environment; /// The input data and the expected return type of a contract execution. diff --git a/crates/env/src/call/mod.rs b/crates/env/src/call/mod.rs index 59156e23950..59a4580b241 100644 --- a/crates/env/src/call/mod.rs +++ b/crates/env/src/call/mod.rs @@ -23,45 +23,19 @@ mod selector; /// Utility types for the cross-contract calling API. pub mod utils { pub use super::{ - common::{ - ReturnType, - Set, - Unset, - Unwrap, - }, + common::{ReturnType, Set, Unset, Unwrap}, execution::{ - ArgsList, - Argument, - ArgumentList, - ArgumentListEnd, - EmptyArgumentList, + ArgsList, Argument, ArgumentList, ArgumentListEnd, EmptyArgumentList, }, }; } pub use self::{ - call_builder::{ - build_call, - Call, - CallBuilder, - CallParams, - CallV1, - DelegateCall, - }, + call_builder::{build_call, Call, CallBuilder, CallParams, CallV1, DelegateCall}, create_builder::{ - build_create, - state, - ConstructorReturnType, - CreateBuilder, - CreateParams, - FromAccountId, - LimitParamsV1, - LimitParamsV2, - }, - execution::{ - Execution, - ExecutionInput, - Executor, + build_create, state, ConstructorReturnType, CreateBuilder, CreateParams, + FromAccountId, LimitParamsV1, LimitParamsV2, }, + execution::{Execution, ExecutionInput, Executor}, selector::Selector, }; diff --git a/crates/env/src/chain_extension.rs b/crates/env/src/chain_extension.rs index e2ef7280f17..49bf80fae20 100644 --- a/crates/env/src/chain_extension.rs +++ b/crates/env/src/chain_extension.rs @@ -19,10 +19,7 @@ use crate::{ backend::EnvBackend, - engine::{ - EnvInstance, - OnInstance, - }, + engine::{EnvInstance, OnInstance}, }; use core::marker::PhantomData; diff --git a/crates/env/src/engine/mod.rs b/crates/env/src/engine/mod.rs index 08a72ff4379..c9850f88cef 100644 --- a/crates/env/src/engine/mod.rs +++ b/crates/env/src/engine/mod.rs @@ -13,22 +13,12 @@ // limitations under the License. use crate::{ - backend::{ - EnvBackend, - TypedEnvBackend, - }, - call::{ - ConstructorReturnType, - FromAccountId, - }, - Error, - Result as EnvResult, + backend::{EnvBackend, TypedEnvBackend}, + call::{ConstructorReturnType, FromAccountId}, + Error, Result as EnvResult, }; use cfg_if::cfg_if; -use ink_primitives::{ - ConstructorResult, - LangError, -}; +use ink_primitives::{ConstructorResult, LangError}; use pallet_contracts_uapi::ReturnErrorCode; @@ -148,10 +138,7 @@ where #[cfg(test)] mod decode_instantiate_result_tests { use super::*; - use crate::{ - DefaultEnvironment, - Environment, - }; + use crate::{DefaultEnvironment, Environment}; use scale::Encode; // The `Result` type used to represent the programmer defined contract output. diff --git a/crates/env/src/engine/off_chain/call_data.rs b/crates/env/src/engine/off_chain/call_data.rs index af8a247df5a..be5335477ea 100644 --- a/crates/env/src/engine/off_chain/call_data.rs +++ b/crates/env/src/engine/off_chain/call_data.rs @@ -13,10 +13,7 @@ // limitations under the License. use crate::call::Selector; -use ink_prelude::{ - vec, - vec::Vec, -}; +use ink_prelude::{vec, vec::Vec}; /// The raw ABI respecting input data to a call. /// @@ -91,7 +88,7 @@ impl scale::Decode for CallData { if bytes.len() < 4 { return Err(scale::Error::from( "require at least 4 bytes for input data", - )) + )); } Ok(Self { bytes }) } diff --git a/crates/env/src/engine/off_chain/impls.rs b/crates/env/src/engine/off_chain/impls.rs index 727bee025aa..501ca46cc12 100644 --- a/crates/env/src/engine/off_chain/impls.rs +++ b/crates/env/src/engine/off_chain/impls.rs @@ -15,47 +15,17 @@ use super::EnvInstance; use crate::{ call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, + Call, CallParams, CallV1, ConstructorReturnType, CreateParams, DelegateCall, + FromAccountId, LimitParamsV1, LimitParamsV2, }, - event::{ - Event, - TopicsBuilderBackend, - }, - hash::{ - Blake2x128, - Blake2x256, - CryptoHash, - HashOutput, - Keccak256, - Sha2x256, - }, - Clear, - EnvBackend, - Environment, - Result, - TypedEnvBackend, + event::{Event, TopicsBuilderBackend}, + hash::{Blake2x128, Blake2x256, CryptoHash, HashOutput, Keccak256, Sha2x256}, + Clear, EnvBackend, Environment, Result, TypedEnvBackend, }; use ink_engine::ext::Engine; -use ink_storage_traits::{ - decode_all, - Storable, -}; -use pallet_contracts_uapi::{ - ReturnErrorCode, - ReturnFlags, -}; -use schnorrkel::{ - PublicKey, - Signature, -}; +use ink_storage_traits::{decode_all, Storable}; +use pallet_contracts_uapi::{ReturnErrorCode, ReturnFlags}; +use schnorrkel::{PublicKey, Signature}; /// The capacity of the static buffer. /// This is the same size as the ink! on-chain environment. We chose to use the same size @@ -268,12 +238,8 @@ impl EnvBackend for EnvInstance { output: &mut [u8; 33], ) -> Result<()> { use secp256k1::{ - ecdsa::{ - RecoverableSignature, - RecoveryId, - }, - Message, - SECP256K1, + ecdsa::{RecoverableSignature, RecoveryId}, + Message, SECP256K1, }; // In most implementations, the v is just 0 or 1 internally, but 27 was added @@ -567,6 +533,13 @@ impl TypedEnvBackend for EnvInstance { unimplemented!("off-chain environment does not support cross-contract calls") } + fn caller_is_root(&mut self) -> bool + where + E: Environment, + { + unimplemented!("off-chain environment does not support `caller_is_root`") + } + fn code_hash(&mut self, _account: &E::AccountId) -> Result where E: Environment, diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index 5c1e00bfeb2..a4bafaea471 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -14,23 +14,14 @@ //! Operations on the off-chain testing environment. -use super::{ - EnvInstance, - OnInstance, -}; -use crate::{ - Environment, - Result, -}; +use super::{EnvInstance, OnInstance}; +use crate::{Environment, Result}; use core::fmt::Debug; use ink_engine::test_api::RecordedDebugMessages; use std::panic::UnwindSafe; pub use super::call_data::CallData; -pub use ink_engine::{ - ext::ChainSpec, - ChainExtension, -}; +pub use ink_engine::{ext::ChainSpec, ChainExtension}; /// Record for an emitted event. #[derive(Clone)] diff --git a/crates/env/src/engine/off_chain/tests.rs b/crates/env/src/engine/off_chain/tests.rs index 9b9848576cc..9b3838c8f55 100644 --- a/crates/env/src/engine/off_chain/tests.rs +++ b/crates/env/src/engine/off_chain/tests.rs @@ -13,14 +13,10 @@ // limitations under the License. use crate::{ - engine::off_chain::{ - impls::TopicsBuilder, - test_api::set_account_balance, - }, + engine::off_chain::{impls::TopicsBuilder, test_api::set_account_balance}, event::TopicsBuilderBackend, types::Environment, - DefaultEnvironment, - Result, + DefaultEnvironment, Result, }; #[test] diff --git a/crates/env/src/engine/off_chain/types.rs b/crates/env/src/engine/off_chain/types.rs index 0fcbba3459e..dd672e73c0d 100644 --- a/crates/env/src/engine/off_chain/types.rs +++ b/crates/env/src/engine/off_chain/types.rs @@ -15,12 +15,7 @@ //! Contains the necessary conversions from `ink_engine` types to types //! of this crate. -use super::{ - test_api::EmittedEvent, - AccountError, - Error, - OffChainError, -}; +use super::{test_api::EmittedEvent, AccountError, Error, OffChainError}; impl From for EmittedEvent { fn from(evt: ink_engine::test_api::EmittedEvent) -> Self { diff --git a/crates/env/src/engine/on_chain/impls.rs b/crates/env/src/engine/on_chain/impls.rs index bf3fea473fa..a155bea2179 100644 --- a/crates/env/src/engine/on_chain/impls.rs +++ b/crates/env/src/engine/on_chain/impls.rs @@ -12,51 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - EnvInstance, - ScopedBuffer, -}; +use super::{EnvInstance, ScopedBuffer}; use crate::{ call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, - }, - event::{ - Event, - TopicsBuilderBackend, + Call, CallParams, CallV1, ConstructorReturnType, CreateParams, DelegateCall, + FromAccountId, LimitParamsV1, LimitParamsV2, }, - hash::{ - Blake2x128, - Blake2x256, - CryptoHash, - HashOutput, - Keccak256, - Sha2x256, - }, - Clear, - EnvBackend, - Environment, - FromLittleEndian, - Result, - TypedEnvBackend, -}; -use ink_storage_traits::{ - decode_all, - Storable, + event::{Event, TopicsBuilderBackend}, + hash::{Blake2x128, Blake2x256, CryptoHash, HashOutput, Keccak256, Sha2x256}, + Clear, EnvBackend, Environment, FromLittleEndian, Result, TypedEnvBackend, }; +use ink_storage_traits::{decode_all, Storable}; use pallet_contracts_uapi::{ - CallFlags, - HostFn, - HostFnImpl as ext, - ReturnErrorCode, - ReturnFlags, + CallFlags, HostFn, HostFnImpl as ext, ReturnErrorCode, ReturnFlags, }; use xcm::VersionedXcm; diff --git a/crates/env/src/engine/on_chain/mod.rs b/crates/env/src/engine/on_chain/mod.rs index 274384174b7..33d973cff45 100644 --- a/crates/env/src/engine/on_chain/mod.rs +++ b/crates/env/src/engine/on_chain/mod.rs @@ -15,11 +15,7 @@ mod buffer; mod impls; -use self::buffer::{ - EncodeScope, - ScopedBuffer, - StaticBuffer, -}; +use self::buffer::{EncodeScope, ScopedBuffer, StaticBuffer}; use super::OnInstance; /// The on-chain environment. diff --git a/crates/env/src/lib.rs b/crates/env/src/lib.rs index 7c3931ab6cc..e8ef0d6f416 100644 --- a/crates/env/src/lib.rs +++ b/crates/env/src/lib.rs @@ -103,33 +103,16 @@ mod tests; pub use self::engine::off_chain::test_api as test; #[doc(inline)] -pub use pallet_contracts_uapi::{ - CallFlags, - ReturnErrorCode, - ReturnFlags, -}; +pub use pallet_contracts_uapi::{CallFlags, ReturnErrorCode, ReturnFlags}; -use self::backend::{ - EnvBackend, - TypedEnvBackend, -}; +use self::backend::{EnvBackend, TypedEnvBackend}; pub use self::{ api::*, - contract::{ - ContractEnv, - ContractReference, - }, - error::{ - Error, - Result, - }, + contract::{ContractEnv, ContractReference}, + error::{Error, Result}, event::Event, types::{ - AccountIdGuard, - DefaultEnvironment, - Environment, - FromLittleEndian, - Gas, + AccountIdGuard, DefaultEnvironment, Environment, FromLittleEndian, Gas, NoChainExtension, }, }; diff --git a/crates/env/src/types.rs b/crates/env/src/types.rs index 0e26f9b29b1..e45c78fa355 100644 --- a/crates/env/src/types.rs +++ b/crates/env/src/types.rs @@ -32,11 +32,7 @@ //! the trait bounds on the `Environment` trait types. use super::arithmetic::AtLeast32BitUnsigned; -use ink_primitives::{ - AccountId, - Clear, - Hash, -}; +use ink_primitives::{AccountId, Clear, Hash}; #[cfg(feature = "std")] use scale_info::TypeInfo; diff --git a/crates/ink/codegen/src/generator/arg_list.rs b/crates/ink/codegen/src/generator/arg_list.rs index 0fe0891a5a9..c625f0c47e1 100644 --- a/crates/ink/codegen/src/generator/arg_list.rs +++ b/crates/ink/codegen/src/generator/arg_list.rs @@ -13,15 +13,8 @@ // limitations under the License. use heck::ToLowerCamelCase as _; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - format_ident, - quote, - quote_spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{format_ident, quote, quote_spanned}; /// Returns the associated output type for an ink! trait message. pub fn output_ident(message_name: &syn::Ident) -> syn::Ident { @@ -50,14 +43,10 @@ pub fn input_types(inputs: ir::InputsIter) -> Vec<&syn::Type> { /// Returns the sequence of input idents for the message. pub fn input_message_idents(inputs: ir::InputsIter) -> Vec<&syn::Ident> { inputs - .map(|input| { - match &*input.pat { - syn::Pat::Ident(ident) => &ident.ident, - _ => { - unreachable!( - "encountered ink! dispatch input with missing identifier" - ) - } + .map(|input| match &*input.pat { + syn::Pat::Ident(ident) => &ident.ident, + _ => { + unreachable!("encountered ink! dispatch input with missing identifier") } }) .collect::>() diff --git a/crates/ink/codegen/src/generator/as_dependency/call_builder.rs b/crates/ink/codegen/src/generator/as_dependency/call_builder.rs index 56475a391f2..e5bbaa871ce 100644 --- a/crates/ink/codegen/src/generator/as_dependency/call_builder.rs +++ b/crates/ink/codegen/src/generator/as_dependency/call_builder.rs @@ -12,18 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - generator, - GenerateCode, -}; +use crate::{generator, GenerateCode}; use derive_more::From; use ir::Callable; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote, - quote_spanned, -}; +use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned as _; /// Generates code for the call builder of the ink! smart contract. diff --git a/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs b/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs index 69ebceda761..db8b2a3b106 100644 --- a/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs +++ b/crates/ink/codegen/src/generator/as_dependency/contract_ref.rs @@ -12,20 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - generator, - GenerateCode, -}; +use crate::{generator, GenerateCode}; use derive_more::From; -use ir::{ - Callable, - IsDocAttribute as _, -}; +use ir::{Callable, IsDocAttribute as _}; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - quote_spanned, -}; +use quote::{quote, quote_spanned}; use syn::spanned::Spanned as _; /// Generates code for the contract reference of the ink! smart contract. diff --git a/crates/ink/codegen/src/generator/as_dependency/mod.rs b/crates/ink/codegen/src/generator/as_dependency/mod.rs index 5a1965957e0..6c9937ff501 100644 --- a/crates/ink/codegen/src/generator/as_dependency/mod.rs +++ b/crates/ink/codegen/src/generator/as_dependency/mod.rs @@ -15,14 +15,8 @@ mod call_builder; mod contract_ref; -use self::{ - call_builder::CallBuilder, - contract_ref::ContractRef, -}; -use crate::{ - traits::GenerateCodeUsing, - GenerateCode, -}; +use self::{call_builder::CallBuilder, contract_ref::ContractRef}; +use crate::{traits::GenerateCodeUsing, GenerateCode}; use derive_more::From; use proc_macro2::TokenStream as TokenStream2; use quote::quote; diff --git a/crates/ink/codegen/src/generator/chain_extension.rs b/crates/ink/codegen/src/generator/chain_extension.rs index 47327358577..4c31b9ec52b 100644 --- a/crates/ink/codegen/src/generator/chain_extension.rs +++ b/crates/ink/codegen/src/generator/chain_extension.rs @@ -16,10 +16,7 @@ use crate::GenerateCode; use derive_more::From; use ir::ChainExtensionMethod; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote_spanned, -}; +use quote::{format_ident, quote_spanned}; use syn::spanned::Spanned; /// Generator to create an ink! chain extension. diff --git a/crates/ink/codegen/src/generator/contract.rs b/crates/ink/codegen/src/generator/contract.rs index 06d5f5b80da..9054147be3c 100644 --- a/crates/ink/codegen/src/generator/contract.rs +++ b/crates/ink/codegen/src/generator/contract.rs @@ -12,11 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - generator, - GenerateCode, - GenerateCodeUsing, -}; +use crate::{generator, GenerateCode, GenerateCodeUsing}; use derive_more::From; use proc_macro2::TokenStream as TokenStream2; use quote::quote; diff --git a/crates/ink/codegen/src/generator/dispatch.rs b/crates/ink/codegen/src/generator/dispatch.rs index d3b56f14793..bca338c5a6d 100644 --- a/crates/ink/codegen/src/generator/dispatch.rs +++ b/crates/ink/codegen/src/generator/dispatch.rs @@ -14,28 +14,12 @@ use core::iter; -use crate::{ - generator, - GenerateCode, -}; +use crate::{generator, GenerateCode}; use derive_more::From; -use ir::{ - Callable, - CallableWithSelector, - Constructor, - HexLiteral as _, - Message, -}; +use ir::{Callable, CallableWithSelector, Constructor, HexLiteral as _, Message}; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote, - quote_spanned, -}; -use syn::{ - spanned::Spanned as _, - LitInt, -}; +use quote::{format_ident, quote, quote_spanned}; +use syn::{spanned::Spanned as _, LitInt}; /// A message to be dispatched. /// Contains its callable and calculated unique id diff --git a/crates/ink/codegen/src/generator/item_impls.rs b/crates/ink/codegen/src/generator/item_impls.rs index f982dd7911b..2a57de1e43f 100644 --- a/crates/ink/codegen/src/generator/item_impls.rs +++ b/crates/ink/codegen/src/generator/item_impls.rs @@ -17,17 +17,9 @@ use core::iter; use crate::GenerateCode; use derive_more::From; use heck::ToLowerCamelCase as _; -use ir::{ - Callable as _, - HexLiteral, -}; +use ir::{Callable as _, HexLiteral}; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote, - quote_spanned, - ToTokens, -}; +use quote::{format_ident, quote, quote_spanned, ToTokens}; use syn::spanned::Spanned as _; /// Generates code for all ink! implementation blocks. diff --git a/crates/ink/codegen/src/generator/metadata.rs b/crates/ink/codegen/src/generator/metadata.rs index b1ac9276937..49333909ac7 100644 --- a/crates/ink/codegen/src/generator/metadata.rs +++ b/crates/ink/codegen/src/generator/metadata.rs @@ -15,23 +15,10 @@ use crate::GenerateCode; use ::core::iter; use derive_more::From; -use ir::{ - Callable as _, - HexLiteral, - IsDocAttribute, -}; -use proc_macro2::{ - Ident, - TokenStream as TokenStream2, -}; -use quote::{ - quote, - quote_spanned, -}; -use syn::{ - parse_quote, - spanned::Spanned as _, -}; +use ir::{Callable as _, HexLiteral, IsDocAttribute}; +use proc_macro2::{Ident, TokenStream as TokenStream2}; +use quote::{quote, quote_spanned}; +use syn::{parse_quote, spanned::Spanned as _}; /// Generates code to generate the metadata of the contract. #[derive(From)] @@ -371,11 +358,11 @@ pub fn generate_type_spec(ty: &syn::Type) -> TokenStream2 { if let syn::Type::Path(type_path) = ty { if type_path.qself.is_some() { - return without_display_name(ty) + return without_display_name(ty); } let path = &type_path.path; if path.segments.is_empty() { - return without_display_name(ty) + return without_display_name(ty); } let segs = path .segments diff --git a/crates/ink/codegen/src/generator/mod.rs b/crates/ink/codegen/src/generator/mod.rs index cb50a7e61f7..65b5b190e51 100644 --- a/crates/ink/codegen/src/generator/mod.rs +++ b/crates/ink/codegen/src/generator/mod.rs @@ -44,13 +44,8 @@ mod trait_def; pub use self::{ arg_list::{ - generate_argument_list, - generate_reference_to_trait_info, - input_bindings, - input_bindings_tuple, - input_message_idents, - input_types, - input_types_tuple, + generate_argument_list, generate_reference_to_trait_info, input_bindings, + input_bindings_tuple, input_message_idents, input_types, input_types_tuple, output_ident, }, as_dependency::ContractReference, @@ -62,14 +57,8 @@ pub use self::{ event::Event, ink_test::InkTest, item_impls::ItemImpls, - metadata::{ - generate_type_spec, - Metadata, - }, - selector::{ - SelectorBytes, - SelectorId, - }, + metadata::{generate_type_spec, Metadata}, + selector::{SelectorBytes, SelectorId}, storage::Storage, storage_item::StorageItem, trait_def::TraitDefinition, diff --git a/crates/ink/codegen/src/generator/storage.rs b/crates/ink/codegen/src/generator/storage.rs index 6dd2cbbce83..30214cf9509 100644 --- a/crates/ink/codegen/src/generator/storage.rs +++ b/crates/ink/codegen/src/generator/storage.rs @@ -15,10 +15,7 @@ use crate::GenerateCode; use derive_more::From; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - quote_spanned, -}; +use quote::{quote, quote_spanned}; use syn::spanned::Spanned as _; /// Generator to create the ink! storage struct and important trait implementations. diff --git a/crates/ink/codegen/src/generator/storage_item.rs b/crates/ink/codegen/src/generator/storage_item.rs index dc5a7e82d05..efdc0129fe3 100644 --- a/crates/ink/codegen/src/generator/storage_item.rs +++ b/crates/ink/codegen/src/generator/storage_item.rs @@ -14,27 +14,9 @@ use crate::GenerateCode; use derive_more::From; -use proc_macro2::{ - Ident, - TokenStream as TokenStream2, - TokenStream, -}; -use quote::{ - format_ident, - quote, - quote_spanned, - ToTokens, -}; -use syn::{ - spanned::Spanned, - Data, - DataEnum, - DataStruct, - DataUnion, - Field, - Fields, - Type, -}; +use proc_macro2::{Ident, TokenStream as TokenStream2, TokenStream}; +use quote::{format_ident, quote, quote_spanned, ToTokens}; +use syn::{spanned::Spanned, Data, DataEnum, DataStruct, DataUnion, Field, Fields, Type}; /// Generates code for the storage item. #[derive(From, Copy, Clone)] diff --git a/crates/ink/codegen/src/generator/trait_def/call_builder.rs b/crates/ink/codegen/src/generator/trait_def/call_builder.rs index f111fb2e88b..c7210929377 100644 --- a/crates/ink/codegen/src/generator/trait_def/call_builder.rs +++ b/crates/ink/codegen/src/generator/trait_def/call_builder.rs @@ -13,19 +13,10 @@ // limitations under the License. use super::TraitDefinition; -use crate::{ - generator, - traits::GenerateCode, -}; +use crate::{generator, traits::GenerateCode}; use derive_more::From; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - quote, - quote_spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{quote, quote_spanned}; impl<'a> TraitDefinition<'a> { /// Generates code for the global trait call builder for an ink! trait. diff --git a/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs b/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs index 9904ffbb478..b0621511008 100644 --- a/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs +++ b/crates/ink/codegen/src/generator/trait_def/call_forwarder.rs @@ -13,19 +13,10 @@ // limitations under the License. use super::TraitDefinition; -use crate::{ - generator, - traits::GenerateCode, -}; +use crate::{generator, traits::GenerateCode}; use derive_more::From; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - quote, - quote_spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{quote, quote_spanned}; impl<'a> TraitDefinition<'a> { /// Generates code for the global trait call forwarder for an ink! trait. diff --git a/crates/ink/codegen/src/generator/trait_def/definition.rs b/crates/ink/codegen/src/generator/trait_def/definition.rs index 9ea66e1f65b..e919aa982a2 100644 --- a/crates/ink/codegen/src/generator/trait_def/definition.rs +++ b/crates/ink/codegen/src/generator/trait_def/definition.rs @@ -17,11 +17,7 @@ use super::TraitDefinition; use heck::ToLowerCamelCase as _; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote, - quote_spanned, -}; +use quote::{format_ident, quote, quote_spanned}; impl<'a> TraitDefinition<'a> { fn generate_for_message(message: ir::InkTraitMessage<'a>) -> TokenStream2 { diff --git a/crates/ink/codegen/src/generator/trait_def/message_builder.rs b/crates/ink/codegen/src/generator/trait_def/message_builder.rs index 1864e8aab1a..93c4971761c 100644 --- a/crates/ink/codegen/src/generator/trait_def/message_builder.rs +++ b/crates/ink/codegen/src/generator/trait_def/message_builder.rs @@ -13,19 +13,10 @@ // limitations under the License. use super::TraitDefinition; -use crate::{ - generator, - traits::GenerateCode, -}; +use crate::{generator, traits::GenerateCode}; use derive_more::From; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - quote, - quote_spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{quote, quote_spanned}; impl<'a> TraitDefinition<'a> { /// Generates code for the global trait call builder for an ink! trait. diff --git a/crates/ink/codegen/src/generator/trait_def/mod.rs b/crates/ink/codegen/src/generator/trait_def/mod.rs index 378ad3d258c..e6683fd5b7a 100644 --- a/crates/ink/codegen/src/generator/trait_def/mod.rs +++ b/crates/ink/codegen/src/generator/trait_def/mod.rs @@ -20,14 +20,8 @@ mod trait_registry; use crate::GenerateCode; use derive_more::From; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - format_ident, - quote_spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{format_ident, quote_spanned}; /// Generator to create the ink! storage struct and important trait implementations. #[derive(From, Copy, Clone)] diff --git a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs index 85267921f4d..4900ed7edbc 100644 --- a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs +++ b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs @@ -21,26 +21,14 @@ use super::TraitDefinition; use crate::{ - generator::{ - self, - }, + generator::{self}, traits::GenerateCode, EnforcedErrors, }; use derive_more::From; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; -use quote::{ - format_ident, - quote, - quote_spanned, -}; -use syn::{ - parse_quote, - spanned::Spanned, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::{format_ident, quote, quote_spanned}; +use syn::{parse_quote, spanned::Spanned}; impl<'a> TraitDefinition<'a> { /// Generates the code for the global trait registry implementation. diff --git a/crates/ink/codegen/src/lib.rs b/crates/ink/codegen/src/lib.rs index 48f3ef4beb7..702aa80736a 100644 --- a/crates/ink/codegen/src/lib.rs +++ b/crates/ink/codegen/src/lib.rs @@ -43,10 +43,7 @@ pub use generator::generate_type_spec; use self::{ enforced_error::EnforcedErrors, - traits::{ - GenerateCode, - GenerateCodeUsing, - }, + traits::{GenerateCode, GenerateCodeUsing}, }; use proc_macro2::TokenStream as TokenStream2; diff --git a/crates/ink/ir/src/ast/attr_args.rs b/crates/ink/ir/src/ast/attr_args.rs index c1be7c25ba9..2d6d52e6e0b 100644 --- a/crates/ink/ir/src/ast/attr_args.rs +++ b/crates/ink/ir/src/ast/attr_args.rs @@ -14,10 +14,7 @@ use super::Meta; use syn::{ - parse::{ - Parse, - ParseStream, - }, + parse::{Parse, ParseStream}, punctuated::Punctuated, Token, }; @@ -57,10 +54,7 @@ impl Parse for AttributeArgs { #[cfg(test)] mod tests { use super::*; - use crate::ast::{ - MetaNameValue, - MetaValue, - }; + use crate::ast::{MetaNameValue, MetaValue}; use quote::quote; impl AttributeArgs { diff --git a/crates/ink/ir/src/ast/meta.rs b/crates/ink/ir/src/ast/meta.rs index 25c3a96a581..18eb7bb5174 100644 --- a/crates/ink/ir/src/ast/meta.rs +++ b/crates/ink/ir/src/ast/meta.rs @@ -12,23 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use proc_macro2::{ - Ident, - TokenStream as TokenStream2, -}; +use proc_macro2::{Ident, TokenStream as TokenStream2}; use quote::ToTokens; use syn::{ ext::IdentExt as _, - parse::{ - Parse, - ParseStream, - }, + parse::{Parse, ParseStream}, punctuated::Punctuated, spanned::Spanned, - LitBool, - LitInt, - LitStr, - Token, + LitBool, LitInt, LitStr, Token, }; /// Content of a compile-time structured attribute. @@ -146,13 +137,13 @@ pub enum MetaValue { impl Parse for MetaValue { fn parse(input: ParseStream) -> Result { if input.peek(Token![_]) || input.peek(Token![@]) { - return input.parse::().map(MetaValue::Symbol) + return input.parse::().map(MetaValue::Symbol); } if input.fork().peek(syn::Lit) { - return input.parse::().map(MetaValue::Lit) + return input.parse::().map(MetaValue::Lit); } if input.fork().peek(Ident::peek_any) || input.fork().peek(Token![::]) { - return input.call(parse_meta_path).map(MetaValue::Path) + return input.call(parse_meta_path).map(MetaValue::Path); } Err(input.error("expected a literal, a path or a punct for a meta value")) } @@ -260,15 +251,15 @@ fn parse_meta_path(input: ParseStream) -> Result { let ident = Ident::parse_any(input)?; segments.push_value(syn::PathSegment::from(ident)); if !input.peek(syn::Token![::]) { - break + break; } let punct = input.parse()?; segments.push_punct(punct); } if segments.is_empty() { - return Err(input.error("expected path")) + return Err(input.error("expected path")); } else if segments.trailing_punct() { - return Err(input.error("expected path segment")) + return Err(input.error("expected path segment")); } segments }, @@ -278,10 +269,7 @@ fn parse_meta_path(input: ParseStream) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::ast::{ - MetaValue, - Symbol, - }; + use crate::ast::{MetaValue, Symbol}; use quote::quote; #[test] diff --git a/crates/ink/ir/src/ast/mod.rs b/crates/ink/ir/src/ast/mod.rs index 06f9cd4c03b..82b53e870f3 100644 --- a/crates/ink/ir/src/ast/mod.rs +++ b/crates/ink/ir/src/ast/mod.rs @@ -29,10 +29,5 @@ mod meta; pub use self::{ attr_args::AttributeArgs, - meta::{ - Meta, - MetaNameValue, - MetaValue, - Symbol, - }, + meta::{Meta, MetaNameValue, MetaValue, Symbol}, }; diff --git a/crates/ink/ir/src/ir/attrs.rs b/crates/ink/ir/src/ir/attrs.rs index 03dc97d576e..d8f9673d298 100644 --- a/crates/ink/ir/src/ir/attrs.rs +++ b/crates/ink/ir/src/ir/attrs.rs @@ -16,31 +16,20 @@ use core::result::Result; use std::collections::HashMap; use ink_prelude::IIP2_WILDCARD_COMPLEMENT_SELECTOR; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::ToTokens; use syn::{ - parse::{ - Parse, - ParseStream, - }, + parse::{Parse, ParseStream}, punctuated::Punctuated, spanned::Spanned, Token, }; use crate::{ - ast::{ - self, - }, + ast::{self}, error::ExtError as _, ir, - ir::{ - chain_extension::FunctionId, - Selector, - }, + ir::{chain_extension::FunctionId, Selector}, }; /// An extension trait for [`syn::Attribute`] in order to query for documentation. @@ -713,11 +702,9 @@ where .map(>::try_from) .collect::, syn::Error>>()? .into_iter() - .partition_map(|attr| { - match attr { - Attribute::Ink(ink_attr) => Either::Left(ink_attr), - Attribute::Other(other_attr) => Either::Right(other_attr), - } + .partition_map(|attr| match attr { + Attribute::Ink(ink_attr) => Either::Left(ink_attr), + Attribute::Other(other_attr) => Either::Right(other_attr), }); Attribute::ensure_no_duplicate_attrs(&ink_attrs)?; Ok((ink_attrs, others)) @@ -940,14 +927,10 @@ impl Parse for AttributeFrag { ) })?; match ident.to_string().as_str() { - "selector" => { - SelectorOrWildcard::try_from(&name_value.value) - .map(AttributeArg::Selector) - } - "namespace" => { - Namespace::try_from(&name_value.value) - .map(AttributeArg::Namespace) - } + "selector" => SelectorOrWildcard::try_from(&name_value.value) + .map(AttributeArg::Selector), + "namespace" => Namespace::try_from(&name_value.value) + .map(AttributeArg::Namespace), "signature_topic" => { if let Some(hash) = name_value.value.as_string() { Ok(AttributeArg::SignatureTopic(hash)) @@ -984,13 +967,11 @@ impl Parse for AttributeFrag { )) } } - _ => { - Err(format_err_spanned!( - ident, - "encountered unknown ink! attribute argument: {}", - ident - )) - } + _ => Err(format_err_spanned!( + ident, + "encountered unknown ink! attribute argument: {}", + ident + )), } } ast::Meta::Path(path) => { @@ -1112,15 +1093,13 @@ mod tests { impl From for Attribute { fn from(attr: ir::Attribute) -> Self { match attr { - ir::Attribute::Ink(ink_attr) => { - Self::Ink( - ink_attr - .args - .into_iter() - .map(|arg| arg.arg) - .collect::>(), - ) - } + ir::Attribute::Ink(ink_attr) => Self::Ink( + ink_attr + .args + .into_iter() + .map(|arg| arg.arg) + .collect::>(), + ), ir::Attribute::Other(other_attr) => Self::Other(other_attr), } } diff --git a/crates/ink/ir/src/ir/blake2.rs b/crates/ink/ir/src/ir/blake2.rs index 18c9c6a66e3..aadcc0ee88a 100644 --- a/crates/ink/ir/src/ir/blake2.rs +++ b/crates/ink/ir/src/ir/blake2.rs @@ -17,10 +17,7 @@ use syn::spanned::Spanned as _; /// Computes the BLAKE-2b 256-bit hash for the given input and stores it in output. pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) { - use ::blake2::digest::{ - consts::U32, - Digest as _, - }; + use ::blake2::digest::{consts::U32, Digest as _}; type Blake2b256 = ::blake2::Blake2b; diff --git a/crates/ink/ir/src/ir/chain_extension.rs b/crates/ink/ir/src/ir/chain_extension.rs index 51571af89a7..cc59f2fa0db 100644 --- a/crates/ink/ir/src/ir/chain_extension.rs +++ b/crates/ink/ir/src/ir/chain_extension.rs @@ -12,19 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ast, - error::ExtError, - ir, - ir::idents_lint, -}; +use crate::{ast, error::ExtError, ir, ir::idents_lint}; use core::slice::Iter as SliceIter; use proc_macro2::TokenStream as TokenStream2; use std::collections::HashMap; -use syn::{ - spanned::Spanned as _, - Result, -}; +use syn::{spanned::Spanned as _, Result}; /// An ink! chain extension. #[derive(Debug, PartialEq, Eq)] @@ -344,31 +336,31 @@ impl ChainExtension { return Err(format_err_spanned!( unsafety, "ink! chain extensions cannot be unsafe" - )) + )); } if let Some(auto) = &item_trait.auto_token { return Err(format_err_spanned!( auto, "ink! chain extensions cannot be automatically implemented traits" - )) + )); } if !item_trait.generics.params.is_empty() { return Err(format_err_spanned!( item_trait.generics.params, "ink! chain extensions must not be generic" - )) + )); } if !matches!(item_trait.vis, syn::Visibility::Public(_)) { return Err(format_err_spanned!( item_trait.vis, "ink! chain extensions must have public visibility" - )) + )); } if !item_trait.supertraits.is_empty() { return Err(format_err_spanned!( item_trait.supertraits, "ink! chain extensions with super-traits are not supported, yet" - )) + )); } Ok(()) } @@ -395,19 +387,19 @@ impl ChainExtension { return Err(format_err_spanned!( item_type.generics, "generic chain extension `ErrorCode` types are not supported", - )) + )); } if !item_type.bounds.is_empty() { return Err(format_err_spanned!( item_type.bounds, "bounded chain extension `ErrorCode` types are not supported", - )) + )); } if item_type.default.is_none() { return Err(format_err_spanned!( item_type, "expected a default type for the ink! chain extension ErrorCode", - )) + )); } match previous { Some(previous_error_code) => { @@ -536,37 +528,37 @@ impl ChainExtension { return Err(format_err_spanned!( constness, "const ink! chain extension methods are not supported" - )) + )); } if let Some(asyncness) = &method.sig.asyncness { return Err(format_err_spanned!( asyncness, "async ink! chain extension methods are not supported" - )) + )); } if let Some(unsafety) = &method.sig.unsafety { return Err(format_err_spanned!( unsafety, "unsafe ink! chain extension methods are not supported" - )) + )); } if let Some(abi) = &method.sig.abi { return Err(format_err_spanned!( abi, "ink! chain extension methods with non default ABI are not supported" - )) + )); } if let Some(variadic) = &method.sig.variadic { return Err(format_err_spanned!( variadic, "variadic ink! chain extension methods are not supported" - )) + )); } if !method.sig.generics.params.is_empty() { return Err(format_err_spanned!( method.sig.generics.params, "generic ink! chain extension methods are not supported" - )) + )); } match ir::first_ink_attribute(&method.attrs)? .map(|attr| attr.first().kind().clone()) { @@ -602,20 +594,18 @@ impl ChainExtension { item_method.span(), item_method.attrs.clone(), &ir::AttributeArgKind::Function, - |arg| { - match arg.kind() { - ir::AttributeArg::Function(_) | ir::AttributeArg::HandleStatus(_) => { - Ok(()) - } - _ => Err(None), + |arg| match arg.kind() { + ir::AttributeArg::Function(_) | ir::AttributeArg::HandleStatus(_) => { + Ok(()) } + _ => Err(None), }, )?; if let Some(receiver) = item_method.sig.receiver() { return Err(format_err_spanned!( receiver, "ink! chain extension method must not have a `self` receiver", - )) + )); } let result = ChainExtensionMethod { id: GlobalMethodId::new(ext_id, func_id), diff --git a/crates/ink/ir/src/ir/config.rs b/crates/ink/ir/src/ir/config.rs index 3942071262b..52254588748 100644 --- a/crates/ink/ir/src/ir/config.rs +++ b/crates/ink/ir/src/ir/config.rs @@ -14,10 +14,7 @@ use crate::{ ast, - utils::{ - duplicate_config_err, - WhitelistedAttributes, - }, + utils::{duplicate_config_err, WhitelistedAttributes}, }; /// The ink! configuration. diff --git a/crates/ink/ir/src/ir/contract.rs b/crates/ink/ir/src/ir/contract.rs index e9222fcddeb..38456bfcd63 100644 --- a/crates/ink/ir/src/ir/contract.rs +++ b/crates/ink/ir/src/ir/contract.rs @@ -12,10 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ast, - ir, -}; +use crate::{ast, ir}; use proc_macro2::TokenStream as TokenStream2; /// An ink! contract definition consisting of the ink! configuration and module. diff --git a/crates/ink/ir/src/ir/event/config.rs b/crates/ink/ir/src/ir/event/config.rs index 8206631ad79..70d0c64edbb 100644 --- a/crates/ink/ir/src/ir/event/config.rs +++ b/crates/ink/ir/src/ir/event/config.rs @@ -12,10 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ast, - utils::duplicate_config_err, -}; +use crate::{ast, utils::duplicate_config_err}; /// The configuration arguments to the `#[ink::event(..)]` attribute macro. #[derive(Debug, PartialEq, Eq)] @@ -38,7 +35,12 @@ impl TryFrom for EventConfig { for arg in args.into_iter() { if arg.name().is_ident("anonymous") { if let Some(lit_bool) = anonymous { - return Err(duplicate_config_err(lit_bool, arg, "anonymous", "event")); + return Err(duplicate_config_err( + lit_bool, + arg, + "anonymous", + "event", + )); } if let ast::Meta::Path(path) = arg { anonymous = Some(path) diff --git a/crates/ink/ir/src/ir/event/mod.rs b/crates/ink/ir/src/ir/event/mod.rs index 86a6c8c5673..2e7c37cb9d0 100644 --- a/crates/ink/ir/src/ir/event/mod.rs +++ b/crates/ink/ir/src/ir/event/mod.rs @@ -16,18 +16,11 @@ mod config; mod signature_topic; use config::EventConfig; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::ToTokens; use syn::spanned::Spanned as _; -use crate::{ - error::ExtError, - ir, - utils::extract_cfg_attributes, -}; +use crate::{error::ExtError, ir, utils::extract_cfg_attributes}; pub use signature_topic::SignatureTopicArg; @@ -130,13 +123,11 @@ impl TryFrom for Event { struct_span, item_struct.attrs.clone(), &ir::AttributeArgKind::Event, - |arg| { - match arg.kind() { - ir::AttributeArg::Event - | ir::AttributeArg::SignatureTopic(_) - | ir::AttributeArg::Anonymous => Ok(()), - _ => Err(None), - } + |arg| match arg.kind() { + ir::AttributeArg::Event + | ir::AttributeArg::SignatureTopic(_) + | ir::AttributeArg::Anonymous => Ok(()), + _ => Err(None), }, )?; if ink_attrs.is_anonymous() && ink_attrs.signature_topic_hex().is_some() { diff --git a/crates/ink/ir/src/ir/ink_test.rs b/crates/ink/ir/src/ir/ink_test.rs index 209053ab754..42b4b8f77a4 100644 --- a/crates/ink/ir/src/ir/ink_test.rs +++ b/crates/ink/ir/src/ir/ink_test.rs @@ -37,7 +37,7 @@ impl InkTest { return Err(format_err_spanned!( attr, "unexpected attribute input for ink! test definition" - )) + )); } let item_fn = syn::parse2::(input)?; InkTest::try_from(item_fn) diff --git a/crates/ink/ir/src/ir/item/mod.rs b/crates/ink/ir/src/ir/item/mod.rs index f674b35a8bb..af79484790e 100644 --- a/crates/ink/ir/src/ir/item/mod.rs +++ b/crates/ink/ir/src/ir/item/mod.rs @@ -19,11 +19,7 @@ mod tests; pub use self::storage::Storage; -use crate::{ - error::ExtError as _, - ir, - ir::attrs::Attrs as _, -}; +use crate::{error::ExtError as _, ir, ir::attrs::Attrs as _}; use syn::spanned::Spanned as _; /// An item in the root of the ink! module ([`ir::ItemMod`](`crate::ir::ItemMod`)). @@ -55,7 +51,7 @@ impl TryFrom for Item { match item { syn::Item::Struct(item_struct) => { if !ir::contains_ink_attributes(&item_struct.attrs) { - return Ok(Self::Rust(item_struct.into())) + return Ok(Self::Rust(item_struct.into())); } // At this point we know that there must be at least one ink! // attribute. This can be either the ink! storage struct, @@ -73,17 +69,15 @@ impl TryFrom for Item { .map(Into::into) .map(Self::Ink) } - _invalid => { - Err(format_err!( - attr.span(), - "encountered unsupported ink! attribute argument on struct", - )) - } + _invalid => Err(format_err!( + attr.span(), + "encountered unsupported ink! attribute argument on struct", + )), } } syn::Item::Impl(item_impl) => { if !ir::ItemImpl::is_ink_impl_block(&item_impl)? { - return Ok(Self::Rust(item_impl.into())) + return Ok(Self::Rust(item_impl.into())); } // At this point we know that there must be at least one ink! // attribute on either the `impl` block itself or one of its items. @@ -104,7 +98,7 @@ impl TryFrom for Item { return Err(ink_attrs[1..] .iter() .map(into_err) - .fold(into_err(&ink_attrs[0]), |fst, snd| fst.into_combine(snd))) + .fold(into_err(&ink_attrs[0]), |fst, snd| fst.into_combine(snd))); } Ok(Self::Rust(item)) } @@ -179,7 +173,7 @@ impl InkItem { if ir::Storage::is_ink_storage(item_struct)? || ir::Event::is_ink_event(item_struct)? { - return Ok(true) + return Ok(true); } } syn::Item::Impl(item_impl) => { diff --git a/crates/ink/ir/src/ir/item/storage.rs b/crates/ink/ir/src/ir/item/storage.rs index 598b9aa6a11..5cc8279cd59 100644 --- a/crates/ink/ir/src/ir/item/storage.rs +++ b/crates/ink/ir/src/ir/item/storage.rs @@ -12,10 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ir, - ir::utils, -}; +use crate::{ir, ir::utils}; use proc_macro2::Ident; use syn::spanned::Spanned as _; @@ -64,7 +61,7 @@ impl Storage { item_struct: &syn::ItemStruct, ) -> Result { if !ir::contains_ink_attributes(&item_struct.attrs) { - return Ok(false) + return Ok(false); } // At this point we know that there must be at least one ink! // attribute. This can be either the ink! storage struct, @@ -84,11 +81,9 @@ impl TryFrom for Storage { struct_span, item_struct.attrs, &ir::AttributeArgKind::Storage, - |arg| { - match arg.kind() { - ir::AttributeArg::Storage => Ok(()), - _ => Err(None), - } + |arg| match arg.kind() { + ir::AttributeArg::Storage => Ok(()), + _ => Err(None), }, )?; utils::ensure_pub_visibility("storage structs", struct_span, &item_struct.vis)?; diff --git a/crates/ink/ir/src/ir/item_impl/callable.rs b/crates/ink/ir/src/ir/item_impl/callable.rs index ea10d9230b9..08de8693814 100644 --- a/crates/ink/ir/src/ir/item_impl/callable.rs +++ b/crates/ink/ir/src/ir/item_impl/callable.rs @@ -17,10 +17,7 @@ use crate::ir; use core::fmt; -use proc_macro2::{ - Ident, - Span, -}; +use proc_macro2::{Ident, Span}; use quote::ToTokens as _; use syn::spanned::Spanned as _; @@ -322,7 +319,7 @@ where C: Callable, { if let Some(selector) = callable.user_provided_selector() { - return *selector + return *selector; } let callable_ident = callable.ident().to_string().into_bytes(); let namespace_bytes = item_impl @@ -392,62 +389,60 @@ pub(super) fn ensure_callable_invariants( bad_visibility, "ink! {}s must have public or inherited visibility", kind - )) + )); } if !method_item.sig.generics.params.is_empty() { return Err(format_err_spanned!( method_item.sig.generics.params, "ink! {}s must not be generic", kind, - )) + )); } if method_item.sig.constness.is_some() { return Err(format_err_spanned!( method_item.sig.constness, "ink! {}s must not be const", kind, - )) + )); } if method_item.sig.asyncness.is_some() { return Err(format_err_spanned!( method_item.sig.asyncness, "ink! {}s must not be async", kind, - )) + )); } if method_item.sig.unsafety.is_some() { return Err(format_err_spanned!( method_item.sig.unsafety, "ink! {}s must not be unsafe", kind, - )) + )); } if method_item.sig.abi.is_some() { return Err(format_err_spanned!( method_item.sig.abi, "ink! {}s must not have explicit ABI", kind, - )) + )); } if method_item.sig.variadic.is_some() { return Err(format_err_spanned!( method_item.sig.variadic, "ink! {}s must not be variadic", kind, - )) + )); } - if let Some(arg) = method_item.sig.inputs.iter().find(|input| { - match input { - syn::FnArg::Typed(pat) => !matches!(*pat.pat, syn::Pat::Ident(_)), - _ => false, - } + if let Some(arg) = method_item.sig.inputs.iter().find(|input| match input { + syn::FnArg::Typed(pat) => !matches!(*pat.pat, syn::Pat::Ident(_)), + _ => false, }) { return Err(format_err_spanned!( arg, "ink! {} arguments must have an identifier", kind - )) + )); } Ok(()) } diff --git a/crates/ink/ir/src/ir/item_impl/constructor.rs b/crates/ink/ir/src/ir/item_impl/constructor.rs index 1955334ec41..ecdb384fbd8 100644 --- a/crates/ink/ir/src/ir/item_impl/constructor.rs +++ b/crates/ink/ir/src/ir/item_impl/constructor.rs @@ -12,13 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - ensure_callable_invariants, - Callable, - CallableKind, - InputsIter, - Visibility, -}; +use super::{ensure_callable_invariants, Callable, CallableKind, InputsIter, Visibility}; use crate::{ ir, ir::{ @@ -29,11 +23,7 @@ use crate::{ }, }, }; -use proc_macro2::{ - Ident, - Span, - TokenStream, -}; +use proc_macro2::{Ident, Span, TokenStream}; use syn::spanned::Spanned as _; /// An ink! constructor definition. @@ -104,7 +94,7 @@ impl Constructor { return Err(format_err_spanned!( &method_item.sig, "missing return for ink! constructor", - )) + )); } Ok(()) } @@ -140,14 +130,12 @@ impl Constructor { method_item.span(), method_item.attrs.clone(), &ir::AttributeArgKind::Constructor, - |arg| { - match arg.kind() { - ir::AttributeArg::Constructor - | ir::AttributeArg::Payable - | ir::AttributeArg::Default - | ir::AttributeArg::Selector(_) => Ok(()), - _ => Err(None), - } + |arg| match arg.kind() { + ir::AttributeArg::Constructor + | ir::AttributeArg::Payable + | ir::AttributeArg::Default + | ir::AttributeArg::Selector(_) => Ok(()), + _ => Err(None), }, ) } @@ -187,7 +175,7 @@ impl Callable for Constructor { fn user_provided_selector(&self) -> Option<&ir::Selector> { if let Some(SelectorOrWildcard::UserProvided(selector)) = self.selector.as_ref() { - return Some(selector) + return Some(selector); } None } diff --git a/crates/ink/ir/src/ir/item_impl/impl_item.rs b/crates/ink/ir/src/ir/item_impl/impl_item.rs index 7727bc55131..73f612aaabc 100644 --- a/crates/ink/ir/src/ir/item_impl/impl_item.rs +++ b/crates/ink/ir/src/ir/item_impl/impl_item.rs @@ -12,15 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - Constructor, - Message, -}; -use crate::{ - error::ExtError as _, - ir, - ir::attrs::Attrs as _, -}; +use super::{Constructor, Message}; +use crate::{error::ExtError as _, ir, ir::attrs::Attrs as _}; use syn::spanned::Spanned as _; /// An item within an ink! implementation block. @@ -63,7 +56,7 @@ impl TryFrom for ImplItem { match impl_item { syn::ImplItem::Fn(fn_item) => { if !ir::contains_ink_attributes(&fn_item.attrs) { - return Ok(Self::Other(fn_item.into())) + return Ok(Self::Other(fn_item.into())); } let attr = ir::first_ink_attribute(&fn_item.attrs)? .expect("missing expected ink! attribute for struct"); @@ -98,7 +91,7 @@ impl TryFrom for ImplItem { return Err(ink_attrs[1..] .iter() .map(into_err) - .fold(into_err(&ink_attrs[0]), |fst, snd| fst.into_combine(snd))) + .fold(into_err(&ink_attrs[0]), |fst, snd| fst.into_combine(snd))); } Ok(Self::Other(other_item)) } diff --git a/crates/ink/ir/src/ir/item_impl/iter.rs b/crates/ink/ir/src/ir/item_impl/iter.rs index 4b03c8bdb0a..2e6bd266a79 100644 --- a/crates/ink/ir/src/ir/item_impl/iter.rs +++ b/crates/ink/ir/src/ir/item_impl/iter.rs @@ -12,11 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::{ - CallableWithSelector, - ImplItem, - ItemImpl, -}; +use super::{CallableWithSelector, ImplItem, ItemImpl}; use crate::ir; /// Iterator yielding all ink! constructor within a source ink! @@ -48,9 +44,9 @@ impl<'a> Iterator for IterConstructors<'a> { return Some(CallableWithSelector::new( self.item_impl, constructor, - )) + )); } - continue 'repeat + continue 'repeat; } } } @@ -83,9 +79,9 @@ impl<'a> Iterator for IterMessages<'a> { None => return None, Some(impl_item) => { if let Some(message) = impl_item.filter_map_message() { - return Some(CallableWithSelector::new(self.item_impl, message)) + return Some(CallableWithSelector::new(self.item_impl, message)); } - continue 'repeat + continue 'repeat; } } } diff --git a/crates/ink/ir/src/ir/item_impl/message.rs b/crates/ink/ir/src/ir/item_impl/message.rs index 47d3ab71c4c..a9e3a5e0dda 100644 --- a/crates/ink/ir/src/ir/item_impl/message.rs +++ b/crates/ink/ir/src/ir/item_impl/message.rs @@ -12,6 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +<<<<<<< HEAD +use super::{ensure_callable_invariants, Callable, CallableKind, InputsIter, Visibility}; +use crate::ir::{self, attrs::SelectorOrWildcard, utils, utils::extract_cfg_attributes}; +use proc_macro2::{Ident, Span, TokenStream}; +======= use super::{ ensure_callable_invariants, Callable, @@ -33,6 +38,7 @@ use proc_macro2::{ Span, TokenStream, }; +>>>>>>> master use syn::spanned::Spanned as _; /// The receiver of an ink! message. @@ -147,7 +153,7 @@ impl Message { Some(syn::FnArg::Typed(pat_typed)) => return Err(bail(pat_typed.span())), Some(syn::FnArg::Receiver(receiver)) => { if receiver.reference.is_none() { - return Err(bail(receiver.span())) + return Err(bail(receiver.span())); } } } @@ -168,7 +174,7 @@ impl Message { return Err(format_err!( ret_type, "ink! messages must not return `Self`" - )) + )); } } } @@ -186,14 +192,12 @@ impl Message { method_item.span(), method_item.attrs.clone(), &ir::AttributeArgKind::Message, - |arg| { - match arg.kind() { - ir::AttributeArg::Message - | ir::AttributeArg::Payable - | ir::AttributeArg::Default - | ir::AttributeArg::Selector(_) => Ok(()), - _ => Err(None), - } + |arg| match arg.kind() { + ir::AttributeArg::Message + | ir::AttributeArg::Payable + | ir::AttributeArg::Default + | ir::AttributeArg::Selector(_) => Ok(()), + _ => Err(None), }, ) } @@ -233,7 +237,7 @@ impl Callable for Message { fn user_provided_selector(&self) -> Option<&ir::Selector> { if let Some(SelectorOrWildcard::UserProvided(selector)) = self.selector.as_ref() { - return Some(selector) + return Some(selector); } None } diff --git a/crates/ink/ir/src/ir/item_impl/mod.rs b/crates/ink/ir/src/ir/item_impl/mod.rs index 76237d35ca0..4b91ee967a3 100644 --- a/crates/ink/ir/src/ir/item_impl/mod.rs +++ b/crates/ink/ir/src/ir/item_impl/mod.rs @@ -12,16 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - error::ExtError as _, - ir, - ir::attrs::Attrs as _, -}; -use proc_macro2::{ - Ident, - Span, - TokenStream, -}; +use crate::{error::ExtError as _, ir, ir::attrs::Attrs as _}; +use proc_macro2::{Ident, Span, TokenStream}; mod callable; mod constructor; @@ -34,23 +26,11 @@ mod tests; use self::callable::ensure_callable_invariants; pub use self::{ - callable::{ - Callable, - CallableKind, - CallableWithSelector, - InputsIter, - Visibility, - }, + callable::{Callable, CallableKind, CallableWithSelector, InputsIter, Visibility}, constructor::Constructor, impl_item::ImplItem, - iter::{ - IterConstructors, - IterMessages, - }, - message::{ - Message, - Receiver, - }, + iter::{IterConstructors, IterMessages}, + message::{Message, Receiver}, }; use quote::TokenStreamExt as _; use syn::spanned::Spanned; @@ -168,7 +148,7 @@ impl ItemImpl { .iter() .all(|item| !ir::contains_ink_attributes(item.attrs())) { - return Ok(false) + return Ok(false); } // Check if the implementation block itself has been annotated with // `#[ink(impl)]` and return `true` if this is the case. @@ -183,7 +163,7 @@ impl ItemImpl { .ensure_first(&ir::AttributeArgKind::Implementation) .is_ok() { - return Ok(true) + return Ok(true); } } // Check if any of the implementation block's methods either resembles @@ -192,7 +172,7 @@ impl ItemImpl { match item { syn::ImplItem::Fn(fn_item) => { if !ir::contains_ink_attributes(&fn_item.attrs) { - continue 'repeat + continue 'repeat; } let attr = ir::first_ink_attribute(&fn_item.attrs)? .expect("missing expected ink! attribute for struct"); @@ -224,25 +204,25 @@ impl TryFrom for ItemImpl { return Err(format_err_spanned!( item_impl, "missing ink! annotations on implementation block or on any of its items" - )) + )); } if let Some(defaultness) = item_impl.defaultness { return Err(format_err_spanned!( defaultness, "default implementations are unsupported for ink! implementation blocks", - )) + )); } if let Some(unsafety) = item_impl.unsafety { return Err(format_err_spanned!( unsafety, "unsafe ink! implementation blocks are not supported", - )) + )); } if !item_impl.generics.params.is_empty() { return Err(format_err_spanned!( item_impl.generics.params, "generic ink! implementation blocks are not supported", - )) + )); } let impl_items = item_impl .items @@ -272,7 +252,7 @@ impl TryFrom for ItemImpl { what, if is_trait_impl { "trait" } else { "inherent" }, if requires_pub { "public" } else { "inherited" }, - )) + )); } Ok(()) } @@ -303,13 +283,11 @@ impl TryFrom for ItemImpl { ir::InkAttribute::from_expanded(ink_attrs).map_err(|err| { err.into_combine(format_err!(impl_block_span, "at this invocation",)) })?; - normalized.ensure_no_conflicts(|arg| { - match arg.kind() { - ir::AttributeArg::Implementation | ir::AttributeArg::Namespace(_) => { - Ok(()) - } - _ => Err(None), + normalized.ensure_no_conflicts(|arg| match arg.kind() { + ir::AttributeArg::Implementation | ir::AttributeArg::Namespace(_) => { + Ok(()) } + _ => Err(None), })?; namespace = normalized.namespace(); } diff --git a/crates/ink/ir/src/ir/item_mod.rs b/crates/ink/ir/src/ir/item_mod.rs index 865bd2f8aee..2e1f0a9bfd8 100644 --- a/crates/ink/ir/src/ir/item_mod.rs +++ b/crates/ink/ir/src/ir/item_mod.rs @@ -12,22 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - error::ExtError as _, - ir, - ir::idents_lint, - Callable, -}; -use proc_macro2::{ - Ident, - Span, -}; +use crate::{error::ExtError as _, ir, ir::idents_lint, Callable}; +use proc_macro2::{Ident, Span}; use quote::TokenStreamExt as _; use std::collections::HashMap; -use syn::{ - spanned::Spanned, - token, -}; +use syn::{spanned::Spanned, token}; /// The ink! module. /// @@ -106,7 +95,7 @@ impl ItemMod { .iter() .filter(|item| matches!(item, ir::Item::Ink(ir::InkItem::Storage(_)))); if storage_iter.clone().next().is_none() { - return Err(format_err!(module_span, "missing ink! storage struct",)) + return Err(format_err!(module_span, "missing ink! storage struct",)); } if storage_iter.clone().count() >= 2 { let mut error = format_err!( @@ -116,7 +105,7 @@ impl ItemMod { for storage in storage_iter { error.combine(format_err!(storage, "ink! storage struct here")) } - return Err(error) + return Err(error); } Ok(()) } @@ -128,17 +117,15 @@ impl ItemMod { ) -> Result<(), syn::Error> { let found_message = items .iter() - .filter_map(|item| { - match item { - ir::Item::Ink(ir::InkItem::ImplBlock(item_impl)) => { - Some(item_impl.iter_messages()) - } - _ => None, + .filter_map(|item| match item { + ir::Item::Ink(ir::InkItem::ImplBlock(item_impl)) => { + Some(item_impl.iter_messages()) } + _ => None, }) .any(|mut messages| messages.next().is_some()); if !found_message { - return Err(format_err!(module_span, "missing ink! message")) + return Err(format_err!(module_span, "missing ink! message")); } Ok(()) } @@ -150,17 +137,15 @@ impl ItemMod { ) -> Result<(), syn::Error> { let found_constructor = items .iter() - .filter_map(|item| { - match item { - ir::Item::Ink(ir::InkItem::ImplBlock(item_impl)) => { - Some(item_impl.iter_constructors()) - } - _ => None, + .filter_map(|item| match item { + ir::Item::Ink(ir::InkItem::ImplBlock(item_impl)) => { + Some(item_impl.iter_constructors()) } + _ => None, }) .any(|mut constructors| constructors.next().is_some()); if !found_constructor { - return Err(format_err!(module_span, "missing ink! constructor")) + return Err(format_err!(module_span, "missing ink! constructor")); } Ok(()) } @@ -347,7 +332,7 @@ impl ItemMod { for message in item_impl.iter_messages() { if !message.has_wildcard_selector() { other_messages.push(message); - continue + continue; } match wildcard_selector { None => wildcard_selector = Some(message.callable()), @@ -360,7 +345,7 @@ impl ItemMod { overlap.span(), "first ink! message with overlapping wildcard selector here", ); - return Err(err.into_combine(overlap_err)) + return Err(err.into_combine(overlap_err)); } } } @@ -414,7 +399,7 @@ impl ItemMod { let mut wildcard_selector: Option<&ir::Constructor> = None; for constructor in item_impl.iter_constructors() { if !constructor.has_wildcard_selector() { - continue + continue; } match wildcard_selector { None => wildcard_selector = Some(constructor.callable()), @@ -462,7 +447,7 @@ impl TryFrom for ItemMod { "invalid ink! attribute on module" )) } - return Err(error) + return Err(error); } let items = items .into_iter() @@ -655,9 +640,9 @@ impl<'a> Iterator for IterInkItems<'a> { None => return None, Some(item) => { if let Some(event) = item.map_ink_item() { - return Some(event) + return Some(event); } - continue 'repeat + continue 'repeat; } } } @@ -688,9 +673,9 @@ impl<'a> Iterator for IterEvents<'a> { None => return None, Some(ink_item) => { if let Some(event) = ink_item.filter_map_event_item() { - return Some(event) + return Some(event); } - continue 'repeat + continue 'repeat; } } } @@ -721,9 +706,9 @@ impl<'a> Iterator for IterItemImpls<'a> { None => return None, Some(ink_item) => { if let Some(event) = ink_item.filter_map_impl_block() { - return Some(event) + return Some(event); } - continue 'repeat + continue 'repeat; } } } diff --git a/crates/ink/ir/src/ir/mod.rs b/crates/ink/ir/src/ir/mod.rs index a6f076470ec..6def0c004db 100644 --- a/crates/ink/ir/src/ir/mod.rs +++ b/crates/ink/ir/src/ir/mod.rs @@ -34,82 +34,35 @@ const CFG_IDENT: &str = "cfg"; /// Marker types and definitions. pub mod marker { - pub use super::selector::{ - SelectorBytes, - SelectorId, - }; + pub use super::selector::{SelectorBytes, SelectorId}; } #[cfg(test)] use self::attrs::Attribute; use self::attrs::{ - contains_ink_attributes, - first_ink_attribute, - partition_attributes, - sanitize_attributes, - sanitize_optional_attributes, - AttributeArg, - AttributeArgKind, - AttributeFrag, - InkAttribute, + contains_ink_attributes, first_ink_attribute, partition_attributes, + sanitize_attributes, sanitize_optional_attributes, AttributeArg, AttributeArgKind, + AttributeFrag, InkAttribute, }; pub use self::{ - attrs::{ - IsDocAttribute, - Namespace, - }, - blake2::{ - blake2b_256, - Blake2x256Macro, - }, - chain_extension::{ - ChainExtension, - ChainExtensionMethod, - ExtensionId, - }, + attrs::{IsDocAttribute, Namespace}, + blake2::{blake2b_256, Blake2x256Macro}, + chain_extension::{ChainExtension, ChainExtensionMethod, ExtensionId}, config::Config, contract::Contract, - event::{ - Event, - SignatureTopicArg, - }, + event::{Event, SignatureTopicArg}, ink_test::InkTest, - item::{ - InkItem, - Item, - Storage, - }, + item::{InkItem, Item, Storage}, item_impl::{ - Callable, - CallableKind, - CallableWithSelector, - Constructor, - ImplItem, - InputsIter, - ItemImpl, - IterConstructors, - IterMessages, - Message, - Receiver, - Visibility, - }, - item_mod::{ - ItemMod, - IterEvents, - IterItemImpls, - }, - selector::{ - Selector, - SelectorMacro, - TraitPrefix, + Callable, CallableKind, CallableWithSelector, Constructor, ImplItem, InputsIter, + ItemImpl, IterConstructors, IterMessages, Message, Receiver, Visibility, }, + item_mod::{ItemMod, IterEvents, IterItemImpls}, + selector::{Selector, SelectorMacro, TraitPrefix}, storage_item::StorageItem, trait_def::{ - InkItemTrait, - InkTraitDefinition, - InkTraitItem, - InkTraitMessage, + InkItemTrait, InkTraitDefinition, InkTraitItem, InkTraitMessage, IterInkTraitItems, }, }; diff --git a/crates/ink/ir/src/ir/storage_item/config.rs b/crates/ink/ir/src/ir/storage_item/config.rs index a6aa26e2d19..4769983aa35 100644 --- a/crates/ink/ir/src/ir/storage_item/config.rs +++ b/crates/ink/ir/src/ir/storage_item/config.rs @@ -12,10 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ast, - utils::duplicate_config_err, -}; +use crate::{ast, utils::duplicate_config_err}; /// The ink! configuration. #[derive(Debug, Default, PartialEq, Eq)] diff --git a/crates/ink/ir/src/ir/storage_item/mod.rs b/crates/ink/ir/src/ir/storage_item/mod.rs index a37a8f0efc2..97f6cee03a0 100644 --- a/crates/ink/ir/src/ir/storage_item/mod.rs +++ b/crates/ink/ir/src/ir/storage_item/mod.rs @@ -17,10 +17,7 @@ mod config; use crate::utils::find_storage_key_salt; use config::StorageItemConfig; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - ToTokens, -}; +use quote::{quote, ToTokens}; use std::collections::HashSet; /// A checked ink! storage item with its configuration. @@ -46,7 +43,7 @@ impl StorageItem { return Err(format_err_spanned!( attr, "only one `ink::storage_item` is allowed", - )) + )); } } @@ -64,20 +61,18 @@ impl StorageItem { syn::Data::Struct(st) => { st.fields.iter().map(|field| field.ty.clone()).collect() } - syn::Data::Enum(en) => { - en.variants - .iter() - .flat_map(|variant| variant.fields.iter()) - .map(|field| field.ty.clone()) - .collect() - } - syn::Data::Union(un) => { - un.fields - .named - .iter() - .map(|field| field.ty.clone()) - .collect() - } + syn::Data::Enum(en) => en + .variants + .iter() + .flat_map(|variant| variant.fields.iter()) + .map(|field| field.ty.clone()) + .collect(), + syn::Data::Union(un) => un + .fields + .named + .iter() + .map(|field| field.ty.clone()) + .collect(), }; let mut set = HashSet::new(); res.into_iter() diff --git a/crates/ink/ir/src/ir/trait_def/config.rs b/crates/ink/ir/src/ir/trait_def/config.rs index acde019fc1c..be3cfc60a21 100644 --- a/crates/ink/ir/src/ir/trait_def/config.rs +++ b/crates/ink/ir/src/ir/trait_def/config.rs @@ -14,10 +14,7 @@ use crate::{ ast, - utils::{ - duplicate_config_err, - WhitelistedAttributes, - }, + utils::{duplicate_config_err, WhitelistedAttributes}, }; /// The ink! configuration. diff --git a/crates/ink/ir/src/ir/trait_def/item/iter.rs b/crates/ink/ir/src/ir/trait_def/item/iter.rs index b630a4e14b9..648e1b00332 100644 --- a/crates/ink/ir/src/ir/trait_def/item/iter.rs +++ b/crates/ink/ir/src/ir/trait_def/item/iter.rs @@ -12,13 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - ir, - InkItemTrait, - InkTraitItem, - InkTraitMessage, - Selector, -}; +use crate::{ir, InkItemTrait, InkTraitItem, InkTraitMessage, Selector}; use std::collections::HashMap; /// Iterator over all the ink! trait items of an ink! trait definition. diff --git a/crates/ink/ir/src/ir/trait_def/item/mod.rs b/crates/ink/ir/src/ir/trait_def/item/mod.rs index 8ba95bb3525..081dbf45a22 100644 --- a/crates/ink/ir/src/ir/trait_def/item/mod.rs +++ b/crates/ink/ir/src/ir/trait_def/item/mod.rs @@ -18,30 +18,18 @@ mod trait_item; use self::iter::IterInkTraitItemsRaw; pub use self::{ iter::IterInkTraitItems, - trait_item::{ - InkTraitItem, - InkTraitMessage, - }, + trait_item::{InkTraitItem, InkTraitMessage}, }; use super::TraitDefinitionConfig; use crate::{ ir, - ir::{ - attrs::SelectorOrWildcard, - idents_lint, - }, + ir::{attrs::SelectorOrWildcard, idents_lint}, Selector, }; use ir::TraitPrefix; -use proc_macro2::{ - Ident, - Span, -}; +use proc_macro2::{Ident, Span}; use std::collections::HashMap; -use syn::{ - spanned::Spanned as _, - Result, -}; +use syn::{spanned::Spanned as _, Result}; /// A checked ink! trait definition without its configuration. #[derive(Debug, PartialEq, Eq)] @@ -75,7 +63,7 @@ impl InkItemTrait { return Err(format_err!( item_trait.span(), "encountered invalid empty ink! trait definition" - )) + )); } Ok(Self { item: item_trait, @@ -118,31 +106,31 @@ impl InkItemTrait { return Err(format_err_spanned!( unsafety, "ink! trait definitions cannot be unsafe" - )) + )); } if let Some(auto) = &item_trait.auto_token { return Err(format_err_spanned!( auto, "ink! trait definitions cannot be automatically implemented traits" - )) + )); } if !item_trait.generics.params.is_empty() { return Err(format_err_spanned!( item_trait.generics.params, "ink! trait definitions must not be generic" - )) + )); } if !matches!(item_trait.vis, syn::Visibility::Public(_)) { return Err(format_err_spanned!( item_trait.vis, "ink! trait definitions must have public visibility" - )) + )); } if !item_trait.supertraits.is_empty() { return Err(format_err_spanned!( item_trait.supertraits, "ink! trait definitions with supertraits are not supported, yet" - )) + )); } Ok(()) } @@ -221,43 +209,43 @@ impl InkItemTrait { return Err(format_err_spanned!( default_impl, "ink! trait methods with default implementations are not supported" - )) + )); } if let Some(constness) = &method.sig.constness { return Err(format_err_spanned!( constness, "const ink! trait methods are not supported" - )) + )); } if let Some(asyncness) = &method.sig.asyncness { return Err(format_err_spanned!( asyncness, "async ink! trait methods are not supported" - )) + )); } if let Some(unsafety) = &method.sig.unsafety { return Err(format_err_spanned!( unsafety, "unsafe ink! trait methods are not supported" - )) + )); } if let Some(abi) = &method.sig.abi { return Err(format_err_spanned!( abi, "ink! trait methods with non default ABI are not supported" - )) + )); } if let Some(variadic) = &method.sig.variadic { return Err(format_err_spanned!( variadic, "variadic ink! trait methods are not supported" - )) + )); } if !method.sig.generics.params.is_empty() { return Err(format_err_spanned!( method.sig.generics.params, "generic ink! trait methods are not supported" - )) + )); } match ir::first_ink_attribute(&method.attrs) { Ok(Some(ink_attr)) => { @@ -314,7 +302,7 @@ impl InkItemTrait { return Err(format_err_spanned!( receiver, "self receiver of ink! message must be `&self` or `&mut self`" - )) + )); } } } diff --git a/crates/ink/ir/src/ir/trait_def/item/trait_item.rs b/crates/ink/ir/src/ir/trait_def/item/trait_item.rs index 837b152e858..c82ce5b274c 100644 --- a/crates/ink/ir/src/ir/trait_def/item/trait_item.rs +++ b/crates/ink/ir/src/ir/trait_def/item/trait_item.rs @@ -14,23 +14,11 @@ use super::super::InkAttribute; use crate::{ - ir::{ - self, - attrs::SelectorOrWildcard, - utils, - utils::extract_cfg_attributes, - }, - InputsIter, - Receiver, -}; -use proc_macro2::{ - Span, - TokenStream, -}; -use syn::{ - spanned::Spanned as _, - Result, + ir::{self, attrs::SelectorOrWildcard, utils, utils::extract_cfg_attributes}, + InputsIter, Receiver, }; +use proc_macro2::{Span, TokenStream}; +use syn::{spanned::Spanned as _, Result}; /// An ink! item within an ink! trait definition. #[derive(Debug, Clone)] diff --git a/crates/ink/ir/src/ir/trait_def/mod.rs b/crates/ink/ir/src/ir/trait_def/mod.rs index dcad9230cd7..5c2a563c8db 100644 --- a/crates/ink/ir/src/ir/trait_def/mod.rs +++ b/crates/ink/ir/src/ir/trait_def/mod.rs @@ -20,12 +20,7 @@ mod tests; pub use self::{ config::TraitDefinitionConfig, - item::{ - InkItemTrait, - InkTraitItem, - InkTraitMessage, - IterInkTraitItems, - }, + item::{InkItemTrait, InkTraitItem, InkTraitMessage, IterInkTraitItems}, }; use super::attrs::InkAttribute; use proc_macro2::TokenStream as TokenStream2; diff --git a/crates/ink/ir/src/ir/utils.rs b/crates/ink/ir/src/ir/utils.rs index 5854dbfdb9a..cc9b0ead61b 100644 --- a/crates/ink/ir/src/ir/utils.rs +++ b/crates/ink/ir/src/ir/utils.rs @@ -13,12 +13,7 @@ // limitations under the License. use super::Selector; -use crate::{ - ast, - ast::MetaNameValue, - error::ExtError as _, - format_err, -}; +use crate::{ast, ast::MetaNameValue, error::ExtError as _, format_err}; use proc_macro2::Span; use std::collections::HashMap; use syn::spanned::Spanned; @@ -44,7 +39,7 @@ pub fn ensure_pub_visibility( bad_visibility, "non `pub` ink! {} are not supported", name - )) + )); } Ok(()) } @@ -102,7 +97,7 @@ impl WhitelistedAttributes { arg, "expected a string with attributes separated by `,`", )) - } + }; } /// Returns the filtered input vector of whitelisted attributes. @@ -157,7 +152,7 @@ pub fn find_storage_key_salt(input: &syn::DeriveInput) -> Option let segments = &trait_bound.path.segments; if let Some(last) = segments.last() { if last.ident == "StorageKey" { - return Some(type_param.clone()) + return Some(type_param.clone()); } } } diff --git a/crates/ink/ir/src/lib.rs b/crates/ink/ir/src/lib.rs index fd5de9c61f1..3c5d44d11c9 100644 --- a/crates/ink/ir/src/lib.rs +++ b/crates/ink/ir/src/lib.rs @@ -41,46 +41,13 @@ mod literal; pub use self::{ ir::{ - blake2b_256, - marker, - utils, - Blake2x256Macro, - Callable, - CallableKind, - CallableWithSelector, - ChainExtension, - ChainExtensionMethod, - Config, - Constructor, - Contract, - Event, - ExtensionId, - ImplItem, - InkItem, - InkItemTrait, - InkTest, - InkTraitDefinition, - InkTraitItem, - InkTraitMessage, - InputsIter, - IsDocAttribute, - Item, - ItemImpl, - ItemMod, - IterConstructors, - IterEvents, - IterInkTraitItems, - IterItemImpls, - IterMessages, - Message, - Namespace, - Receiver, - Selector, - SelectorMacro, - SignatureTopicArg, - Storage, - StorageItem, - Visibility, + blake2b_256, marker, utils, Blake2x256Macro, Callable, CallableKind, + CallableWithSelector, ChainExtension, ChainExtensionMethod, Config, Constructor, + Contract, Event, ExtensionId, ImplItem, InkItem, InkItemTrait, InkTest, + InkTraitDefinition, InkTraitItem, InkTraitMessage, InputsIter, IsDocAttribute, + Item, ItemImpl, ItemMod, IterConstructors, IterEvents, IterInkTraitItems, + IterItemImpls, IterMessages, Message, Namespace, Receiver, Selector, + SelectorMacro, SignatureTopicArg, Storage, StorageItem, Visibility, }, literal::HexLiteral, }; diff --git a/crates/ink/macro/src/event/metadata.rs b/crates/ink/macro/src/event/metadata.rs index 45573602b05..9363087a4c4 100644 --- a/crates/ink/macro/src/event/metadata.rs +++ b/crates/ink/macro/src/event/metadata.rs @@ -26,13 +26,11 @@ pub fn event_metadata_derive(mut s: synstructure::Structure) -> TokenStream2 { syn::Data::Struct(_) => { event_metadata_derive_struct(s).unwrap_or_else(|err| err.to_compile_error()) } - _ => { - syn::Error::new( - s.ast().span(), - "can only derive `EventMetadata` for Rust `struct` items", - ) - .to_compile_error() - } + _ => syn::Error::new( + s.ast().span(), + "can only derive `EventMetadata` for Rust `struct` items", + ) + .to_compile_error(), } } diff --git a/crates/ink/macro/src/event/mod.rs b/crates/ink/macro/src/event/mod.rs index 7a7d53266a5..c80433000a0 100644 --- a/crates/ink/macro/src/event/mod.rs +++ b/crates/ink/macro/src/event/mod.rs @@ -14,24 +14,13 @@ mod metadata; -use ink_ir::{ - format_err_spanned, - utils::duplicate_config_err, - SignatureTopicArg, -}; +use ink_ir::{format_err_spanned, utils::duplicate_config_err, SignatureTopicArg}; pub use metadata::event_metadata_derive; use ink_codegen::generate_code; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - quote_spanned, -}; -use syn::{ - punctuated::Punctuated, - spanned::Spanned, - Token, -}; +use quote::{quote, quote_spanned}; +use syn::{punctuated::Punctuated, spanned::Spanned, Token}; /// Event item configurations specified by nested `ink` attributes. struct EventConfig { @@ -125,13 +114,11 @@ pub fn event_derive(mut s: synstructure::Structure) -> TokenStream2 { syn::Data::Struct(_) => { event_derive_struct(s).unwrap_or_else(|err| err.to_compile_error()) } - _ => { - syn::Error::new( - s.ast().span(), - "can only derive `Event` for Rust `struct` items", - ) - .to_compile_error() - } + _ => syn::Error::new( + s.ast().span(), + "can only derive `Event` for Rust `struct` items", + ) + .to_compile_error(), } } @@ -153,16 +140,14 @@ fn event_derive_struct(mut s: synstructure::Structure) -> syn::Result = None; - s.variants_mut()[0].filter(|bi| { - match has_ink_topic_attribute(bi) { - Ok(has_attr) => has_attr, - Err(err) => { - match topic_err { - Some(ref mut topic_err) => topic_err.combine(err), - None => topic_err = Some(err), - } - false + s.variants_mut()[0].filter(|bi| match has_ink_topic_attribute(bi) { + Ok(has_attr) => has_attr, + Err(err) => { + match topic_err { + Some(ref mut topic_err) => topic_err.combine(err), + None => topic_err = Some(err), } + false } }); if let Some(err) = topic_err { diff --git a/crates/ink/macro/src/selector.rs b/crates/ink/macro/src/selector.rs index 3274575cde2..9428b1202d4 100644 --- a/crates/ink/macro/src/selector.rs +++ b/crates/ink/macro/src/selector.rs @@ -14,10 +14,7 @@ use ink_codegen::generate_code; use ink_ir::{ - marker::{ - SelectorBytes, - SelectorId, - }, + marker::{SelectorBytes, SelectorId}, SelectorMacro, }; use proc_macro2::TokenStream as TokenStream2; diff --git a/crates/ink/macro/src/storage/mod.rs b/crates/ink/macro/src/storage/mod.rs index b1568e03638..8e3e36a79af 100644 --- a/crates/ink/macro/src/storage/mod.rs +++ b/crates/ink/macro/src/storage/mod.rs @@ -23,8 +23,6 @@ mod storage_key; mod storage_layout; pub use self::{ - storable::storable_derive, - storable_hint::storable_hint_derive, - storage_key::storage_key_derive, - storage_layout::storage_layout_derive, + storable::storable_derive, storable_hint::storable_hint_derive, + storage_key::storage_key_derive, storage_layout::storage_layout_derive, }; diff --git a/crates/ink/macro/src/storage/storable.rs b/crates/ink/macro/src/storage/storable.rs index c3a7d9e0869..8e6d39d1610 100644 --- a/crates/ink/macro/src/storage/storable.rs +++ b/crates/ink/macro/src/storage/storable.rs @@ -13,10 +13,7 @@ // limitations under the License. use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - quote_spanned, -}; +use quote::{quote, quote_spanned}; use syn::spanned::Spanned; /// `Storable` derive implementation for `struct` types. @@ -79,7 +76,7 @@ fn storable_enum_derive(s: &synstructure::Structure) -> TokenStream2 { s.ast().span(), "Currently only enums with at most 256 variants are supported.", ) - .to_compile_error() + .to_compile_error(); } let decode_body = s diff --git a/crates/ink/macro/src/storage/storable_hint.rs b/crates/ink/macro/src/storage/storable_hint.rs index de59e7a4b52..36298a251c3 100644 --- a/crates/ink/macro/src/storage/storable_hint.rs +++ b/crates/ink/macro/src/storage/storable_hint.rs @@ -14,15 +14,8 @@ use ink_ir::utils::find_storage_key_salt; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - format_ident, - quote, - ToTokens, -}; -use syn::{ - parse2, - GenericParam, -}; +use quote::{format_ident, quote, ToTokens}; +use syn::{parse2, GenericParam}; fn storable_hint_inner(s: synstructure::Structure) -> TokenStream2 { let ident = s.ast().ident.clone(); diff --git a/crates/ink/macro/src/storage/storage_key.rs b/crates/ink/macro/src/storage/storage_key.rs index 3a0c4e54542..38619e37106 100644 --- a/crates/ink/macro/src/storage/storage_key.rs +++ b/crates/ink/macro/src/storage/storage_key.rs @@ -14,10 +14,7 @@ use ink_ir::utils::find_storage_key_salt; use proc_macro2::TokenStream as TokenStream2; -use quote::{ - quote, - ToTokens, -}; +use quote::{quote, ToTokens}; pub fn storage_key_derive(mut s: synstructure::Structure) -> TokenStream2 { s.add_bounds(synstructure::AddBounds::None) diff --git a/crates/ink/macro/src/storage/storage_layout.rs b/crates/ink/macro/src/storage/storage_layout.rs index b08ce7d2fd0..04ea9492dbd 100644 --- a/crates/ink/macro/src/storage/storage_layout.rs +++ b/crates/ink/macro/src/storage/storage_layout.rs @@ -79,7 +79,7 @@ fn storage_layout_enum(s: &synstructure::Structure) -> TokenStream2 { s.ast().span(), "Currently only enums with at most 256 variants are supported.", ) - .to_compile_error() + .to_compile_error(); } let variant_layouts = s.variants().iter().enumerate().map(|(n, variant)| { diff --git a/crates/ink/macro/src/tests/mod.rs b/crates/ink/macro/src/tests/mod.rs index 9481b2479a5..06cd493c168 100644 --- a/crates/ink/macro/src/tests/mod.rs +++ b/crates/ink/macro/src/tests/mod.rs @@ -20,10 +20,7 @@ mod storage_key; mod storage_layout; use crate::storage::{ - storable_derive, - storable_hint_derive, - storage_key_derive, - storage_layout_derive, + storable_derive, storable_hint_derive, storage_key_derive, storage_layout_derive, }; #[cfg(test)] diff --git a/crates/ink/src/codegen/dispatch/execution.rs b/crates/ink/src/codegen/dispatch/execution.rs index 17b9ed5b334..81de187543e 100644 --- a/crates/ink/src/codegen/dispatch/execution.rs +++ b/crates/ink/src/codegen/dispatch/execution.rs @@ -27,7 +27,7 @@ where { let transferred = ink_env::transferred_value::(); if transferred != ::Balance::from(0_u32) { - return Err(DispatchError::PaidUnpayableMessage) + return Err(DispatchError::PaidUnpayableMessage); } Ok(()) } diff --git a/crates/ink/src/codegen/dispatch/mod.rs b/crates/ink/src/codegen/dispatch/mod.rs index 7a621b9e230..2b9c1773bb0 100644 --- a/crates/ink/src/codegen/dispatch/mod.rs +++ b/crates/ink/src/codegen/dispatch/mod.rs @@ -19,8 +19,5 @@ mod type_check; pub use self::{ execution::deny_payment, info::ContractCallBuilder, - type_check::{ - DispatchInput, - DispatchOutput, - }, + type_check::{DispatchInput, DispatchOutput}, }; diff --git a/crates/ink/src/codegen/implies_return.rs b/crates/ink/src/codegen/implies_return.rs index 82d2381bb39..a41291f1d9b 100644 --- a/crates/ink/src/codegen/implies_return.rs +++ b/crates/ink/src/codegen/implies_return.rs @@ -14,13 +14,8 @@ use ink_env::{ call::{ - utils::{ - ReturnType, - Set, - }, - CallBuilder, - Execution, - ExecutionInput, + utils::{ReturnType, Set}, + CallBuilder, Execution, ExecutionInput, }, Environment, }; diff --git a/crates/ink/src/codegen/mod.rs b/crates/ink/src/codegen/mod.rs index 629350a7c33..dc821ab49bb 100644 --- a/crates/ink/src/codegen/mod.rs +++ b/crates/ink/src/codegen/mod.rs @@ -21,23 +21,11 @@ mod trait_def; pub mod utils; pub use self::{ - dispatch::{ - deny_payment, - ContractCallBuilder, - DispatchInput, - DispatchOutput, - }, - env::{ - Env, - StaticEnv, - }, + dispatch::{deny_payment, ContractCallBuilder, DispatchInput, DispatchOutput}, + env::{Env, StaticEnv}, implies_return::ImpliesReturn, trait_def::{ - TraitCallBuilder, - TraitCallForwarder, - TraitCallForwarderFor, - TraitMessageBuilder, - TraitMessagePayable, - TraitMessageSelector, + TraitCallBuilder, TraitCallForwarder, TraitCallForwarderFor, TraitMessageBuilder, + TraitMessagePayable, TraitMessageSelector, }, }; diff --git a/crates/ink/src/codegen/trait_def/mod.rs b/crates/ink/src/codegen/trait_def/mod.rs index c22cc6909cc..0f65feb8ae5 100644 --- a/crates/ink/src/codegen/trait_def/mod.rs +++ b/crates/ink/src/codegen/trait_def/mod.rs @@ -17,13 +17,7 @@ mod trait_message; pub use self::{ call_builder::{ - TraitCallBuilder, - TraitCallForwarder, - TraitCallForwarderFor, - TraitMessageBuilder, - }, - trait_message::{ - TraitMessagePayable, - TraitMessageSelector, + TraitCallBuilder, TraitCallForwarder, TraitCallForwarderFor, TraitMessageBuilder, }, + trait_message::{TraitMessagePayable, TraitMessageSelector}, }; diff --git a/crates/ink/src/codegen/utils/mod.rs b/crates/ink/src/codegen/utils/mod.rs index b56eec5ba23..30ab7ddf758 100644 --- a/crates/ink/src/codegen/utils/mod.rs +++ b/crates/ink/src/codegen/utils/mod.rs @@ -17,7 +17,4 @@ mod identity_type; mod same_type; -pub use self::{ - identity_type::consume_type, - same_type::IsSameType, -}; +pub use self::{identity_type::consume_type, same_type::IsSameType}; diff --git a/crates/ink/src/env_access.rs b/crates/ink/src/env_access.rs index 106a015860e..ec1f264562f 100644 --- a/crates/ink/src/env_access.rs +++ b/crates/ink/src/env_access.rs @@ -16,22 +16,11 @@ use crate::ChainExtensionInstance; use core::marker::PhantomData; use ink_env::{ call::{ - Call, - CallParams, - CallV1, - ConstructorReturnType, - CreateParams, - DelegateCall, - FromAccountId, - LimitParamsV1, - LimitParamsV2, + Call, CallParams, CallV1, ConstructorReturnType, CreateParams, DelegateCall, + FromAccountId, LimitParamsV1, LimitParamsV2, }, - hash::{ - CryptoHash, - HashOutput, - }, - Environment, - Result, + hash::{CryptoHash, HashOutput}, + Environment, Result, }; use pallet_contracts_uapi::ReturnErrorCode; @@ -1178,6 +1167,37 @@ where ink_env::caller_is_origin::() } + /// Checks whether the caller of the current contract is root. + /// + /// # Example + /// + /// ``` + /// # #[ink::contract] + /// # pub mod my_contract { + /// # #[ink(storage)] + /// # pub struct MyContract { } + /// # + /// # impl MyContract { + /// # #[ink(constructor)] + /// # pub fn new() -> Self { + /// # Self {} + /// # } + /// # + /// #[ink(message)] + /// pub fn caller_is_root(&mut self) -> bool { + /// self.env().caller_is_root() + /// } + /// # } + /// # } + /// ``` + /// + /// # Note + /// + /// For more details visit: [`ink_env::caller_is_root`] + pub fn caller_is_root(self) -> bool { + ink_env::caller_is_root::() + } + /// Returns the code hash of the contract at the given `account` id. /// /// # Example diff --git a/crates/ink/src/lib.rs b/crates/ink/src/lib.rs index 01698cd17e7..ac57e1c9797 100644 --- a/crates/ink/src/lib.rs +++ b/crates/ink/src/lib.rs @@ -48,48 +48,20 @@ pub use xcm; pub mod storage { pub mod traits { - pub use ink_macro::{ - Storable, - StorableHint, - StorageKey, - StorageLayout, - }; + pub use ink_macro::{Storable, StorableHint, StorageKey, StorageLayout}; pub use ink_storage::traits::*; } - pub use ink_storage::{ - Lazy, - Mapping, - StorageVec, - }; + pub use ink_storage::{Lazy, Mapping, StorageVec}; } pub use self::{ - chain_extension::{ - ChainExtensionInstance, - IsResultType, - Output, - ValueReturned, - }, + chain_extension::{ChainExtensionInstance, IsResultType, Output, ValueReturned}, contract_ref::ToAccountId, env_access::EnvAccess, prelude::IIP2_WILDCARD_COMPLEMENT_SELECTOR, }; pub use ink_macro::{ - blake2x256, - chain_extension, - contract, - event, - scale_derive, - selector_bytes, - selector_id, - storage_item, - test, - trait_definition, - Event, - EventMetadata, -}; -pub use ink_primitives::{ - ConstructorResult, - LangError, - MessageResult, + blake2x256, chain_extension, contract, event, scale_derive, selector_bytes, + selector_id, storage_item, test, trait_definition, Event, EventMetadata, }; +pub use ink_primitives::{ConstructorResult, LangError, MessageResult}; diff --git a/crates/ink/src/reflect/mod.rs b/crates/ink/src/reflect/mod.rs index 79e7fc596e5..823776097e5 100644 --- a/crates/ink/src/reflect/mod.rs +++ b/crates/ink/src/reflect/mod.rs @@ -30,19 +30,9 @@ mod trait_def; pub use self::{ contract::ContractName, dispatch::{ - ConstructorOutput, - ConstructorOutputValue, - ContractConstructorDecoder, - ContractMessageDecoder, - DecodeDispatch, - DispatchError, - DispatchableConstructorInfo, - DispatchableMessageInfo, - ExecuteDispatchable, - }, - trait_def::{ - TraitDefinitionRegistry, - TraitInfo, - TraitMessageInfo, + ConstructorOutput, ConstructorOutputValue, ContractConstructorDecoder, + ContractMessageDecoder, DecodeDispatch, DispatchError, + DispatchableConstructorInfo, DispatchableMessageInfo, ExecuteDispatchable, }, + trait_def::{TraitDefinitionRegistry, TraitInfo, TraitMessageInfo}, }; diff --git a/crates/ink/src/reflect/trait_def/mod.rs b/crates/ink/src/reflect/trait_def/mod.rs index 5f2410b56b7..fdd5535af52 100644 --- a/crates/ink/src/reflect/trait_def/mod.rs +++ b/crates/ink/src/reflect/trait_def/mod.rs @@ -16,9 +16,6 @@ mod info; mod registry; pub use self::{ - info::{ - TraitInfo, - TraitMessageInfo, - }, + info::{TraitInfo, TraitMessageInfo}, registry::TraitDefinitionRegistry, }; diff --git a/crates/ink/tests/return_type_metadata.rs b/crates/ink/tests/return_type_metadata.rs index 0bca2ffcf26..97e8f7b53a2 100644 --- a/crates/ink/tests/return_type_metadata.rs +++ b/crates/ink/tests/return_type_metadata.rs @@ -41,13 +41,7 @@ mod contract { #[cfg(test)] mod tests { - use scale_info::{ - form::PortableForm, - Type, - TypeDef, - TypeDefPrimitive, - TypeDefTuple, - }; + use scale_info::{form::PortableForm, Type, TypeDef, TypeDefPrimitive, TypeDefTuple}; fn generate_metadata() -> ink_metadata::InkProject { extern "Rust" { diff --git a/crates/metadata/src/layout/mod.rs b/crates/metadata/src/layout/mod.rs index 4c3fb2c4a5b..89581b1f7c8 100644 --- a/crates/metadata/src/layout/mod.rs +++ b/crates/metadata/src/layout/mod.rs @@ -21,37 +21,20 @@ pub use validate::ValidateLayout; use crate::{ serde_hex, - utils::{ - deserialize_from_byte_str, - serialize_as_byte_str, - }, + utils::{deserialize_from_byte_str, serialize_as_byte_str}, }; use derive_more::From; use ink_prelude::collections::btree_map::BTreeMap; use ink_primitives::Key; -use scale::{ - Decode, - Encode, -}; +use scale::{Decode, Encode}; use scale_info::{ - form::{ - Form, - MetaForm, - PortableForm, - }, - meta_type, - IntoPortable, - Registry, - TypeInfo, + form::{Form, MetaForm, PortableForm}, + meta_type, IntoPortable, Registry, TypeInfo, }; use schemars::JsonSchema; use serde::{ - de::{ - DeserializeOwned, - Error, - }, - Deserialize, - Serialize, + de::{DeserializeOwned, Error}, + Deserialize, Serialize, }; /// Represents the static storage layout of an ink! smart contract. diff --git a/crates/metadata/src/layout/validate.rs b/crates/metadata/src/layout/validate.rs index ffdfde8a717..f1656989ed6 100644 --- a/crates/metadata/src/layout/validate.rs +++ b/crates/metadata/src/layout/validate.rs @@ -12,11 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::layout::{ - Layout, - MetadataError, - StructLayout, -}; +use crate::layout::{Layout, MetadataError, StructLayout}; use ink_prelude::collections::HashMap; use ink_primitives::Key; use scale_info::form::MetaForm; @@ -93,14 +89,8 @@ impl ValidateLayout { #[cfg(test)] mod tests { use crate::layout::{ - EnumLayout, - FieldLayout, - Layout, - LeafLayout, - MetadataError, - RootLayout, - StructLayout, - ValidateLayout, + EnumLayout, FieldLayout, Layout, LeafLayout, MetadataError, RootLayout, + StructLayout, ValidateLayout, }; use ink_primitives::Key; use std::collections::BTreeSet; diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index ceaed35db71..0f0e6e14782 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -32,23 +32,10 @@ mod utils; pub use ink_primitives::LangError; pub use self::specs::{ - ConstructorSpec, - ConstructorSpecBuilder, - ContractSpec, - ContractSpecBuilder, - DisplayName, - EnvironmentSpec, - EnvironmentSpecBuilder, - EventParamSpec, - EventParamSpecBuilder, - EventSpec, - EventSpecBuilder, - MessageParamSpec, - MessageParamSpecBuilder, - MessageSpec, - MessageSpecBuilder, - ReturnTypeSpec, - Selector, + ConstructorSpec, ConstructorSpecBuilder, ContractSpec, ContractSpecBuilder, + DisplayName, EnvironmentSpec, EnvironmentSpecBuilder, EventParamSpec, + EventParamSpecBuilder, EventSpec, EventSpecBuilder, MessageParamSpec, + MessageParamSpecBuilder, MessageSpec, MessageSpecBuilder, ReturnTypeSpec, Selector, TypeSpec, }; @@ -59,17 +46,9 @@ pub use linkme; pub use scale_info::TypeInfo; #[cfg(feature = "derive")] -use scale_info::{ - form::PortableForm, - IntoPortable as _, - PortableRegistry, - Registry, -}; +use scale_info::{form::PortableForm, IntoPortable as _, PortableRegistry, Registry}; use schemars::JsonSchema; -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; /// The metadata version of the generated ink! contract. /// diff --git a/crates/metadata/src/specs.rs b/crates/metadata/src/specs.rs index 267a73a5921..47ca0e228ae 100644 --- a/crates/metadata/src/specs.rs +++ b/crates/metadata/src/specs.rs @@ -16,46 +16,19 @@ use crate::{ serde_hex, - utils::{ - deserialize_from_byte_str, - serialize_as_byte_str, - trim_extra_whitespace, - }, + utils::{deserialize_from_byte_str, serialize_as_byte_str, trim_extra_whitespace}, }; #[cfg(not(feature = "std"))] -use alloc::{ - collections::BTreeMap, - format, - string::String, - vec, - vec::Vec, -}; -use core::{ - fmt::Display, - marker::PhantomData, -}; +use alloc::{collections::BTreeMap, format, string::String, vec, vec::Vec}; +use core::{fmt::Display, marker::PhantomData}; use scale_info::{ - form::{ - Form, - MetaForm, - PortableForm, - }, - meta_type, - IntoPortable, - Registry, - TypeInfo, + form::{Form, MetaForm, PortableForm}, + meta_type, IntoPortable, Registry, TypeInfo, }; use schemars::JsonSchema; -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(feature = "std")] -use std::{ - collections::BTreeMap, - hash::Hash, -}; +use std::{collections::BTreeMap, hash::Hash}; /// Describes a contract. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] diff --git a/crates/metadata/src/tests.rs b/crates/metadata/src/tests.rs index e81067221c0..e39821a9b1a 100644 --- a/crates/metadata/src/tests.rs +++ b/crates/metadata/src/tests.rs @@ -14,11 +14,7 @@ use super::*; use pretty_assertions::assert_eq; -use scale_info::{ - IntoPortable, - Path, - Registry, -}; +use scale_info::{IntoPortable, Path, Registry}; use serde_json::json; #[test] diff --git a/crates/metadata/src/utils.rs b/crates/metadata/src/utils.rs index 85a13d55dda..6e877b2efa9 100644 --- a/crates/metadata/src/utils.rs +++ b/crates/metadata/src/utils.rs @@ -22,7 +22,7 @@ where { if bytes.is_empty() { // Return empty string without prepended `0x`. - return serializer.serialize_str("") + return serializer.serialize_str(""); } serde_hex::serialize(bytes, serializer) } diff --git a/crates/primitives/src/key.rs b/crates/primitives/src/key.rs index 0262b194456..d3060d59a6d 100644 --- a/crates/primitives/src/key.rs +++ b/crates/primitives/src/key.rs @@ -52,7 +52,7 @@ impl KeyComposer { /// Returns the storage key from the supplied `bytes`. pub const fn from_bytes(bytes: &[u8]) -> Key { if bytes.is_empty() { - return 0 + return 0; } xxh32(bytes, XXH32_SEED) @@ -77,10 +77,10 @@ impl KeyComposer { field_name: &str, ) -> Result { if struct_name.is_empty() { - return Err(Error::StructNameIsEmpty) + return Err(Error::StructNameIsEmpty); } if field_name.is_empty() { - return Err(Error::FieldNameIsEmpty) + return Err(Error::FieldNameIsEmpty); } let separator = &b"::"[..]; diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index f7832572f6a..3ddd87a66d7 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -32,15 +32,8 @@ mod key; mod types; pub use self::{ - key::{ - Key, - KeyComposer, - }, - types::{ - AccountId, - Clear, - Hash, - }, + key::{Key, KeyComposer}, + types::{AccountId, Clear, Hash}, }; /// An error emitted by the smart contracting language. diff --git a/crates/primitives/src/types.rs b/crates/primitives/src/types.rs index ffb4a073af9..a87f0596d29 100644 --- a/crates/primitives/src/types.rs +++ b/crates/primitives/src/types.rs @@ -14,17 +14,9 @@ use core::array::TryFromSliceError; use derive_more::From; -use scale::{ - Decode, - Encode, - MaxEncodedLen, -}; +use scale::{Decode, Encode, MaxEncodedLen}; #[cfg(feature = "std")] -use { - scale_decode::DecodeAsType, - scale_encode::EncodeAsType, - scale_info::TypeInfo, -}; +use {scale_decode::DecodeAsType, scale_encode::EncodeAsType, scale_info::TypeInfo}; /// The default environment `AccountId` type. /// diff --git a/crates/storage/src/lazy/mapping.rs b/crates/storage/src/lazy/mapping.rs index 80ac5fcff30..6b2c8497b74 100644 --- a/crates/storage/src/lazy/mapping.rs +++ b/crates/storage/src/lazy/mapping.rs @@ -19,21 +19,11 @@ //! This mapping doesn't actually "own" any data. //! Instead it is just a simple wrapper around the contract storage facilities. -use crate::traits::{ - AutoKey, - Packed, - StorableHint, - StorageKey, -}; +use crate::traits::{AutoKey, Packed, StorableHint, StorageKey}; use core::marker::PhantomData; use ink_primitives::Key; use ink_storage_traits::Storable; -use scale::{ - Encode, - Error, - Input, - Output, -}; +use scale::{Encode, Error, Input, Output}; /// A mapping of key-value pairs directly into contract storage. /// @@ -168,13 +158,13 @@ where let key_size = ::encoded_size(&key); if key_size > ink_env::BUFFER_SIZE { - return Err(ink_env::Error::BufferTooSmall) + return Err(ink_env::Error::BufferTooSmall); } let value_size = ::encoded_size(value); if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE { - return Err(ink_env::Error::BufferTooSmall) + return Err(ink_env::Error::BufferTooSmall); } Ok(self.insert(key, value)) @@ -211,7 +201,7 @@ where let key_size = ::encoded_size(&key); if key_size > ink_env::BUFFER_SIZE { - return Some(Err(ink_env::Error::BufferTooSmall)) + return Some(Err(ink_env::Error::BufferTooSmall)); } let value_size: usize = @@ -220,7 +210,7 @@ where .expect("targets of less than 32bit pointer size are not supported; qed"); if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE { - return Some(Err(ink_env::Error::BufferTooSmall)) + return Some(Err(ink_env::Error::BufferTooSmall)); } self.get(key).map(Ok) @@ -271,7 +261,7 @@ where let key_size = ::encoded_size(&key); if key_size > ink_env::BUFFER_SIZE { - return Some(Err(ink_env::Error::BufferTooSmall)) + return Some(Err(ink_env::Error::BufferTooSmall)); } let value_size: usize = @@ -280,7 +270,7 @@ where .expect("targets of less than 32bit pointer size are not supported; qed"); if key_size.saturating_add(value_size) > ink_env::BUFFER_SIZE { - return Some(Err(ink_env::Error::BufferTooSmall)) + return Some(Err(ink_env::Error::BufferTooSmall)); } self.take(key).map(Ok) @@ -358,11 +348,7 @@ where #[cfg(feature = "std")] const _: () = { use crate::traits::StorageLayout; - use ink_metadata::layout::{ - Layout, - LayoutKey, - RootLayout, - }; + use ink_metadata::layout::{Layout, LayoutKey, RootLayout}; impl StorageLayout for Mapping where diff --git a/crates/storage/src/lazy/mod.rs b/crates/storage/src/lazy/mod.rs index e3a170c36eb..1120c6150e1 100644 --- a/crates/storage/src/lazy/mod.rs +++ b/crates/storage/src/lazy/mod.rs @@ -25,19 +25,11 @@ mod vec; pub use self::mapping::Mapping; pub use self::vec::StorageVec; -use crate::traits::{ - AutoKey, - StorableHint, - StorageKey, -}; +use crate::traits::{AutoKey, StorableHint, StorageKey}; use core::marker::PhantomData; use ink_primitives::Key; use ink_storage_traits::Storable; -use scale::{ - Error, - Input, - Output, -}; +use scale::{Error, Input, Output}; /// A simple wrapper around a type to store it in a separate storage cell under its own /// storage key. If you want to update the value, first you need to @@ -256,11 +248,7 @@ where #[cfg(feature = "std")] const _: () = { use crate::traits::StorageLayout; - use ink_metadata::layout::{ - Layout, - LayoutKey, - RootLayout, - }; + use ink_metadata::layout::{Layout, LayoutKey, RootLayout}; impl StorageLayout for Lazy where diff --git a/crates/storage/src/lazy/vec.rs b/crates/storage/src/lazy/vec.rs index 8fd4f404d96..1c0f4c48b35 100644 --- a/crates/storage/src/lazy/vec.rs +++ b/crates/storage/src/lazy/vec.rs @@ -21,20 +21,11 @@ use core::cell::Cell; use ink_primitives::Key; -use ink_storage_traits::{ - AutoKey, - Packed, - Storable, - StorableHint, - StorageKey, -}; +use ink_storage_traits::{AutoKey, Packed, Storable, StorableHint, StorageKey}; use pallet_contracts_uapi::ReturnErrorCode; use scale::EncodeLike; -use crate::{ - Lazy, - Mapping, -}; +use crate::{Lazy, Mapping}; /// A vector of values (elements) directly on contract storage. /// @@ -181,11 +172,7 @@ where #[cfg(feature = "std")] const _: () = { use crate::traits::StorageLayout; - use ink_metadata::layout::{ - Layout, - LayoutKey, - RootLayout, - }; + use ink_metadata::layout::{Layout, LayoutKey, RootLayout}; impl StorageLayout for StorageVec where diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 60846e7ca1b..65bbed2f40e 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -51,8 +51,4 @@ pub use ink_storage_traits as traits; pub(crate) mod lazy; #[doc(inline)] -pub use self::lazy::{ - Lazy, - Mapping, - StorageVec, -}; +pub use self::lazy::{Lazy, Mapping, StorageVec}; diff --git a/crates/storage/traits/src/impls/mod.rs b/crates/storage/traits/src/impls/mod.rs index 754dbf1240a..01fd4e54b7c 100644 --- a/crates/storage/traits/src/impls/mod.rs +++ b/crates/storage/traits/src/impls/mod.rs @@ -12,20 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - AutoStorableHint, - Packed, - StorableHint, - StorageKey, -}; -use core::{ - fmt::Debug, - marker::PhantomData, -}; -use ink_primitives::{ - Key, - KeyComposer, -}; +use crate::{AutoStorableHint, Packed, StorableHint, StorageKey}; +use core::{fmt::Debug, marker::PhantomData}; +use ink_primitives::{Key, KeyComposer}; /// The private trait helping identify the [`AutoKey`] key type. trait KeyType { diff --git a/crates/storage/traits/src/layout/impls.rs b/crates/storage/traits/src/layout/impls.rs index 83ee842d12c..2cb1fc779a6 100644 --- a/crates/storage/traits/src/layout/impls.rs +++ b/crates/storage/traits/src/layout/impls.rs @@ -12,35 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - Packed, - StorageLayout, -}; +use crate::{Packed, StorageLayout}; use ink_metadata::layout::{ - ArrayLayout, - Discriminant, - EnumLayout, - FieldLayout, - Layout, - LayoutKey, - LeafLayout, + ArrayLayout, Discriminant, EnumLayout, FieldLayout, Layout, LayoutKey, LeafLayout, StructLayout, }; use ink_prelude::{ boxed::Box, - collections::{ - BTreeMap, - BTreeSet, - VecDeque, - }, + collections::{BTreeMap, BTreeSet, VecDeque}, string::String, vec::Vec, }; -use ink_primitives::{ - AccountId, - Hash, - Key, -}; +use ink_primitives::{AccountId, Hash, Key}; use scale_info::TypeInfo; macro_rules! impl_storage_layout_for_primitives { diff --git a/crates/storage/traits/src/lib.rs b/crates/storage/traits/src/lib.rs index 589afffe0c5..a4d47e2c58d 100644 --- a/crates/storage/traits/src/lib.rs +++ b/crates/storage/traits/src/lib.rs @@ -41,17 +41,6 @@ mod layout; #[cfg(feature = "std")] pub use self::layout::StorageLayout; pub use self::{ - impls::{ - AutoKey, - ManualKey, - ResolverKey, - }, - storage::{ - decode_all, - AutoStorableHint, - Packed, - Storable, - StorableHint, - StorageKey, - }, + impls::{AutoKey, ManualKey, ResolverKey}, + storage::{decode_all, AutoStorableHint, Packed, Storable, StorableHint, StorageKey}, };