Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- Custom signature topic in Events - #[2031](https://github.com/paritytech/ink/pull/2031)


## Version 5.0.0-rc

Expand Down
43 changes: 28 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ wasm-instrument = { version = "0.4.0" }
which = { version = "5.0.0" }
xxhash-rust = { version = "0.8" }
const_env = { version = "0.1"}
hex = { version = "0.4" }

# Substrate dependencies
pallet-contracts-primitives = { version = "26.0.0", default-features = false }
Expand Down
21 changes: 14 additions & 7 deletions crates/env/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,11 @@ impl EventTopicsAmount for state::NoRemainingTopics {
/// builder.
///
/// Normally this trait should be implemented automatically via `#[derive(ink::Event)`.
pub trait Event: scale::Encode {
pub trait Event: scale::Encode + GetSignatureTopic {
/// Type state indicating how many event topics are to be expected by the topics
/// builder.
type RemainingTopics: EventTopicsAmount;

/// The unique signature topic of the event. `None` for anonymous events.
///
/// Usually this is calculated using the `#[derive(ink::Event)]` derive, which by
/// default calculates this as `blake2b("Event(field1_type,field2_type)")`
const SIGNATURE_TOPIC: Option<[u8; 32]>;

/// Guides event topic serialization using the given topics builder.
fn topics<E, B>(
&self,
Expand All @@ -215,3 +209,16 @@ pub trait Event: scale::Encode {
E: Environment,
B: TopicsBuilderBackend<E>;
}

/// Getter that returns the signature topic for the specific event.
///
/// It can be automatically calculated or manually specified.
///
/// The unique signature topic of the event. `None` for anonymous events.
///
/// Usually this is calculated using the `#[derive(ink::Event)]` derive, which by
/// default calculates this as `blake2b("Event(field1_type,field2_type)")`
pub trait GetSignatureTopic {
/// Retrieve the signature topic
const SIGNATURE_TOPIC: core::option::Option<[u8; 32]>;
}
5 changes: 4 additions & 1 deletion crates/env/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ pub use self::{
Error,
Result,
},
event::Event,
event::{
Event,
GetSignatureTopic,
},
types::{
AccountIdGuard,
DefaultEnvironment,
Expand Down
1 change: 1 addition & 0 deletions crates/ink/codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ blake2 = { workspace = true }
heck = { workspace = true }
scale = { workspace = true }
impl-serde = { workspace = true, default-features = true }
hex = { workspace = true }

serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ impl ContractRef<'_> {
.storage()
.attrs()
.iter()
.cloned()
.filter(syn::Attribute::is_doc_attribute);
.filter(|&x| syn::Attribute::is_doc_attribute(x))
.cloned();
let storage_ident = self.contract.module().storage().ident();
let ref_ident = self.generate_contract_ref_ident();
quote_spanned!(span=>
Expand Down
33 changes: 31 additions & 2 deletions crates/ink/codegen/src/generator/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,57 @@
use crate::GenerateCode;
use derive_more::From;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::spanned::Spanned;

/// Generates code for the storage item.
/// Generates code for the event item.
#[derive(From, Copy, Clone)]
pub struct Event<'a> {
/// The storage item to generate code for.
item: &'a ir::Event,
}

impl GenerateCode for Event<'_> {
/// Generates ink! storage item code.
/// Generates ink! event item code.
fn generate_code(&self) -> TokenStream2 {
let item = self.item.item();
let anonymous = self
.item
.anonymous()
.then(|| quote::quote! { #[ink(anonymous)] });

let signature_topic = self.generate_signature_topic();
let cfg_attrs = self.item.get_cfg_attrs(item.span());

quote::quote! (
#( #cfg_attrs )*
#[cfg_attr(feature = "std", derive(::ink::EventMetadata))]
#[derive(::ink::Event)]
#[::ink::scale_derive(Encode, Decode)]
#signature_topic
#anonymous
#item
)
}
}

impl Event<'_> {
/// Generates the `#[ink::signature_topic]` attribute for the given event.
///
/// # Note
/// If `anonymous` is present, no attribute is generated
/// and the blank implementation is generated by `#derive(Event)`.
fn generate_signature_topic(&self) -> TokenStream2 {
let signature_topic = if let Some(hash) = self.item.signature_topic_hash() {
quote! {
#[::ink::signature_topic(hash = #hash)]
}
} else if self.item.anonymous() {
quote! {}
} else {
quote! { #[::ink::signature_topic] }
};

quote! { #signature_topic }
}
}
2 changes: 2 additions & 0 deletions crates/ink/codegen/src/generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mod ink_test;
mod item_impls;
mod metadata;
mod selector;
mod signature_topic;
mod storage;
mod storage_item;
mod trait_def;
Expand Down Expand Up @@ -67,6 +68,7 @@ pub use self::{
SelectorBytes,
SelectorId,
},
signature_topic::SignatureTopic,
storage::Storage,
storage_item::StorageItem,
trait_def::TraitDefinition,
Expand Down
79 changes: 79 additions & 0 deletions crates/ink/codegen/src/generator/signature_topic.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (C) Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::GenerateCode;
use derive_more::From;
use ir::HexLiteral;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::spanned::Spanned;

/// Generates code to generate signature topic.
#[derive(From, Copy, Clone)]
pub struct SignatureTopic<'a> {
/// The event item to generate code for.
item: &'a ir::SignatureTopic,
}

impl GenerateCode for SignatureTopic<'_> {
/// Generates ink! signature topic item code.
fn generate_code(&self) -> TokenStream2 {
let item = self.item.item();
let signature_topic = self.generate_signature_topic();
let cfg_attrs = self.item.get_cfg_attrs(item.span());

quote::quote! (
#( #cfg_attrs )*
#signature_topic
#item
)
}
}

impl SignatureTopic<'_> {
/// Generates the implementation of `GetSignatureTopic` trait.
fn generate_signature_topic(&self) -> TokenStream2 {
let item_ident = &self.item.item().ident;
let signature_topic = if let Some(bytes) = self.item.signature_topic() {
let hash_bytes = bytes.map(|b| b.hex_padded_suffixed());
quote! { ::core::option::Option::Some([ #( #hash_bytes ),* ]) }
} else {
let calculated_topic = signature_topic(&self.item.item().fields, item_ident);
quote! { ::core::option::Option::Some(#calculated_topic) }
};

quote! {
impl ::ink::env::GetSignatureTopic for #item_ident {
const SIGNATURE_TOPIC: ::core::option::Option<[u8; 32]> = #signature_topic;
}
}
}
}

/// The signature topic of an event variant.
///
/// Calculated with `blake2b("Event(field1_type,field2_type)")`.
fn signature_topic(fields: &syn::Fields, event_ident: &syn::Ident) -> TokenStream2 {
let fields = fields
.iter()
.map(|field| {
quote::ToTokens::to_token_stream(&field.ty)
.to_string()
.replace(' ', "")
})
.collect::<Vec<_>>()
.join(",");
let topic_str = format!("{}({fields})", event_ident);
quote!(::ink::blake2x256!(#topic_str))
}
4 changes: 4 additions & 0 deletions crates/ink/codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ impl<'a> CodeGenerator for &'a ir::Event {
type Generator = generator::Event<'a>;
}

impl<'a> CodeGenerator for &'a ir::SignatureTopic {
type Generator = generator::SignatureTopic<'a>;
}

impl<'a> CodeGenerator for &'a ir::StorageItem {
type Generator = generator::StorageItem<'a>;
}
Expand Down
2 changes: 2 additions & 0 deletions crates/ink/ir/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ proc-macro2 = { workspace = true }
itertools = { workspace = true }
either = { workspace = true }
blake2 = { workspace = true }
hex = { workspace = true }

ink_prelude = { workspace = true }

[features]
Expand Down
Loading