Skip to content

Commit

Permalink
Merge branch 'master' into at/remove-random
Browse files Browse the repository at this point in the history
  • Loading branch information
athei committed Oct 29, 2022
2 parents 0758443 + 6360098 commit c5329c2
Show file tree
Hide file tree
Showing 25 changed files with 354 additions and 214 deletions.
1 change: 0 additions & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,6 @@ examples-contract-build:
<<: *test-refs
script:
- rustup component add rust-src --toolchain stable
- cargo install cargo-contract --git /~https://github.com/paritytech/cargo-contract --version 2.0.0-alpha.4 --force
- cargo contract -V
- for example in examples/*/; do
if [ "$example" = "examples/upgradeable-contracts/" ]; then continue; fi;
Expand Down
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
- Allows to use `Result<Self, Error>` as a return type in constructors - [#1446](/~https://github.com/paritytech/ink/pull/1446)

- Remove random function from ink!.

Expand All @@ -24,7 +25,7 @@ crate. All existing sub-crates are reexported and should be used via the new `in
- Replace all usages of individual crates with reexports, e.g. `ink_env``ink::env`.

#### Storage Rework
[#1331](/~https://github.com/paritytech/ink/pull/1331) changes the way `ink!` works with contract storage. Storage keys
[#1331](/~https://github.com/paritytech/ink/pull/1331) changes the way `ink!` works with contract storage. Storage keys
are generated at compile-time, and user facing abstractions which determine how contract data is laid out in storage
have changed.

Expand Down
6 changes: 2 additions & 4 deletions crates/e2e/macro/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ static BUILD_ONCE: Once = Once::new();

thread_local! {
// We save a mapping of `contract_manifest_path` to the built `*.contract` files.
// This is necessary so that not each individual `#[ink_e2e::e2e_tests]` starts
// This is necessary so that not each individual `#[ink_e2e::test]` starts
// rebuilding the main contract and possibly specified `additional_contracts` contracts.
pub static ALREADY_BUILT_CONTRACTS: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
}
Expand Down Expand Up @@ -73,7 +73,6 @@ impl InkE2ETest {
};

let ws_url = &self.test.config.ws_url();
let node_log = &self.test.config.node_log();

let mut additional_contracts: Vec<String> =
self.test.config.additional_contracts();
Expand Down Expand Up @@ -144,7 +143,7 @@ impl InkE2ETest {
let mut client = ::ink_e2e::Client::<
::ink_e2e::PolkadotConfig,
ink::env::DefaultEnvironment
>::new(&#ws_url, &#node_log).await;
>::new(&#ws_url).await;

let __ret = {
#block
Expand Down Expand Up @@ -176,7 +175,6 @@ fn build_contract(manifest_path: &str) -> String {
"+stable",
"contract",
"build",
"--skip-linting",
"--output-json",
&format!("--manifest-path={}", manifest_path),
])
Expand Down
27 changes: 1 addition & 26 deletions crates/e2e/macro/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ use ink_ir::{
/// The End-to-End test configuration.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct E2EConfig {
/// The path where the node writes its log.
node_log: Option<syn::LitStr>,
/// The WebSocket URL where to connect with the node.
ws_url: Option<syn::LitStr>,
/// The set of attributes that can be passed to call builder in the codegen.
Expand All @@ -38,25 +36,12 @@ impl TryFrom<ast::AttributeArgs> for E2EConfig {
type Error = syn::Error;

fn try_from(args: ast::AttributeArgs) -> Result<Self, Self::Error> {
let mut node_log: Option<(syn::LitStr, ast::MetaNameValue)> = None;
let mut ws_url: Option<(syn::LitStr, ast::MetaNameValue)> = None;
let mut whitelisted_attributes = WhitelistedAttributes::default();
let mut additional_contracts: Option<(syn::LitStr, ast::MetaNameValue)> = None;

for arg in args.into_iter() {
if arg.name.is_ident("node_log") {
if let Some((_, ast)) = node_log {
return Err(duplicate_config_err(ast, arg, "node_log", "e2e test"))
}
if let ast::PathOrLit::Lit(syn::Lit::Str(lit_str)) = &arg.value {
node_log = Some((lit_str.clone(), arg))
} else {
return Err(format_err_spanned!(
arg,
"expected a path for `node_log` ink! e2e test configuration argument",
))
}
} else if arg.name.is_ident("ws_url") {
if arg.name.is_ident("ws_url") {
if let Some((_, ast)) = ws_url {
return Err(duplicate_config_err(ast, arg, "ws_url", "e2e test"))
}
Expand Down Expand Up @@ -98,7 +83,6 @@ impl TryFrom<ast::AttributeArgs> for E2EConfig {
.map(|(value, _)| value.value().split(' ').map(String::from).collect())
.unwrap_or_else(Vec::new);
Ok(E2EConfig {
node_log: node_log.map(|(value, _)| value),
ws_url: ws_url.map(|(value, _)| value),
additional_contracts,
whitelisted_attributes,
Expand All @@ -107,14 +91,6 @@ impl TryFrom<ast::AttributeArgs> for E2EConfig {
}

impl E2EConfig {
/// Returns the path to the node log if specified.
/// Otherwise returns the default path `/tmp/contracts-node.log`.
pub fn node_log(&self) -> syn::LitStr {
let default_node_log =
syn::LitStr::new("/tmp/contracts-node.log", proc_macro2::Span::call_site());
self.node_log.clone().unwrap_or(default_node_log)
}

/// Returns the WebSocket URL where to connect to the RPC endpoint
/// of the node, if specified. Otherwise returns the default URL
/// `ws://localhost:9944`.
Expand Down Expand Up @@ -199,7 +175,6 @@ mod tests {
keep_attr = "foo, bar"
},
Ok(E2EConfig {
node_log: None,
ws_url: None,
whitelisted_attributes: attrs,
additional_contracts: Vec::new(),
Expand Down
21 changes: 1 addition & 20 deletions crates/e2e/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,25 +63,6 @@ use syn::Result;
///
/// **Default value:** `"ws://localhost:9944"`.
///
/// - `node_log: String`
///
/// The `node_log` denotes the path under which to find the node's log.
///
/// **Usage Example:**
/// ```no_compile
/// # // TODO(#xxx) Remove the `no_compile`.
/// type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
/// #[ink::e2e_test(ws_url = "ws://localhost:9944")]
/// async fn e2e_contract_must_transfer_value_to_sender(
/// mut client: ::ink_e2e::Client<C, E>,
/// ) -> E2EResult<()> {
/// assert!(client.node_log_contains("requested value: 100000000000000\n"));
/// Ok(())
/// }
/// ```
///
/// **Default value:** `"/tmp/contracts-node.log"`.
///
/// # Example
///
/// ```no_compile
Expand Down Expand Up @@ -132,7 +113,7 @@ use syn::Result;
/// );
/// ```
#[proc_macro_attribute]
pub fn e2e_test(attr: TokenStream, item: TokenStream) -> TokenStream {
pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
generate(attr.into(), item.into()).into()
}

Expand Down
49 changes: 1 addition & 48 deletions crates/e2e/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ where
E: Environment,
{
api: ContractsApi<C, E>,
node_log: String,
}

impl<C, E> Client<C, E>
Expand All @@ -278,7 +277,7 @@ where
InstantiateWithCode<E::Balance>: scale::Encode,
{
/// Creates a new [`Client`] instance.
pub async fn new(url: &str, node_log: &str) -> Self {
pub async fn new(url: &str) -> Self {
let client = subxt::OnlineClient::from_url(url)
.await
.unwrap_or_else(|err| {
Expand All @@ -290,7 +289,6 @@ where

Self {
api: ContractsApi::new(client, url).await,
node_log: node_log.to_string(),
}
}

Expand Down Expand Up @@ -365,7 +363,6 @@ where
return Err(Error::InstantiateDryRun(dry_run))
}

self.set_current_nonce(signer).await;
let tx_events = self
.api
.instantiate_with_code(
Expand All @@ -378,7 +375,6 @@ where
signer,
)
.await;
signer.increment_nonce();

let mut account_id = None;
for evt in tx_events.iter() {
Expand Down Expand Up @@ -469,9 +465,7 @@ where
return Err(Error::UploadDryRun(dry_run))
}

self.set_current_nonce(signer).await;
let tx_events = self.api.upload(signer, code, storage_deposit_limit).await;
signer.increment_nonce();

let mut hash = None;
for evt in tx_events.iter() {
Expand Down Expand Up @@ -558,7 +552,6 @@ where
return Err(Error::CallDryRun(dry_run))
}

self.set_current_nonce(signer).await;
let tx_events = self
.api
.call(
Expand All @@ -570,7 +563,6 @@ where
signer,
)
.await;
signer.increment_nonce();

for evt in tx_events.iter() {
let evt = evt.unwrap_or_else(|err| {
Expand Down Expand Up @@ -642,43 +634,4 @@ where
));
Ok(alice_pre.data.free)
}

/// Returns true if the `substrate-contracts-node` log under
/// `/tmp/contracts-node.log` contains `msg`.
/// TODO(#1423) Matches on any log entry currently, even if done
/// by a different test.
pub fn node_log_contains(&self, msg: &str) -> bool {
let output = std::process::Command::new("grep")
.arg("-q")
.arg(msg)
.arg(&self.node_log)
.spawn()
.map_err(|err| {
format!("ERROR while executing `grep` with {:?}: {:?}", msg, err)
})
.expect("failed to execute process")
.wait_with_output()
.expect("failed to receive output");
output.status.success()
}

/// Fetches the next system account index for `signer.account_id()`
/// and sets it as nonce for `signer`.
async fn set_current_nonce(&mut self, signer: &mut Signer<C>) {
let nonce = self
.api
.client
.rpc()
.system_account_next_index(signer.account_id())
.await
.unwrap_or_else(|err| {
panic!(
"error getting next index for {:?}: {:?}",
signer.account_id(),
err
);
});
log_info(&format!("setting signer nonce to {:?}", nonce));
signer.set_nonce(nonce);
}
}
4 changes: 2 additions & 2 deletions crates/e2e/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub use client::{
};
pub use default_accounts::*;
pub use env_logger;
pub use ink_e2e_macro::e2e_test;
pub use ink_e2e_macro::test;
// TODO(#1421) `smart-bench_macro` needs to be forked.
pub use smart_bench_macro;
pub use sp_core::H256;
Expand Down Expand Up @@ -117,7 +117,7 @@ pub static INIT: Once = Once::new();
// of prefixing log entries to make it easier pinning them to tests.
thread_local! {
/// This prefix will be used for log output. It is set by each
/// `#[ink::e2e_test]` with the function name as String.
/// `#[ink_e2e::test]` with the function name as String.
/// This way it is possible to distinguish the lines in stdout
/// and stderr, to still know which line belongs to which test.
pub static LOG_PREFIX: RefCell<String> = RefCell::new(String::from("no prefix set"));
Expand Down
8 changes: 5 additions & 3 deletions crates/ink/codegen/src/generator/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,16 +256,19 @@ impl Dispatch<'_> {
let payable = constructor.is_payable();
let selector_id = constructor.composed_selector().into_be_u32().hex_padded_suffixed();
let selector_bytes = constructor.composed_selector().hex_lits();
let output_tuple_type = constructor.output().map(quote::ToTokens::to_token_stream)
.unwrap_or_else(|| quote! { () });
let input_bindings = generator::input_bindings(constructor.inputs());
let input_tuple_type = generator::input_types_tuple(constructor.inputs());
let input_tuple_bindings = generator::input_bindings_tuple(constructor.inputs());
quote_spanned!(constructor_span=>
impl ::ink::reflect::DispatchableConstructorInfo<#selector_id> for #storage_ident {
type Input = #input_tuple_type;
type Output = #output_tuple_type;
type Storage = #storage_ident;

const CALLABLE: fn(Self::Input) -> Self::Storage = |#input_tuple_bindings| {
#storage_ident::#constructor_ident( #( #input_bindings ),* )
const CALLABLE: fn(Self::Input) -> Self::Output = |#input_tuple_bindings| {
#storage_ident::#constructor_ident(#( #input_bindings ),* )
};
const PAYABLE: ::core::primitive::bool = #payable;
const SELECTOR: [::core::primitive::u8; 4usize] = [ #( #selector_bytes ),* ];
Expand Down Expand Up @@ -559,7 +562,6 @@ impl Dispatch<'_> {
}>>::IDS[#index]
}>>::PAYABLE
);

quote_spanned!(constructor_span=>
Self::#constructor_ident(input) => {
if #any_constructor_accept_payment && #deny_payment {
Expand Down
3 changes: 2 additions & 1 deletion crates/ink/codegen/src/generator/item_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,11 @@ impl ItemImpls<'_> {
let ident = constructor.ident();
let inputs = constructor.inputs();
let statements = constructor.statements();
let output = constructor.output();
quote_spanned!(span =>
#( #attrs )*
#[cfg(not(feature = "__ink_dylint_Constructor"))]
#vis fn #ident( #( #inputs ),* ) -> Self {
#vis fn #ident( #( #inputs ),* ) -> #output {
#( #statements )*
}
)
Expand Down
Loading

0 comments on commit c5329c2

Please sign in to comment.