Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add auto-generated key methods for Events #1116

Open
wants to merge 15 commits into
base: nightly
Choose a base branch
from
8 changes: 4 additions & 4 deletions examples/demo-rollup/src/test_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use sov_db::ledger_db::{LedgerDB, SlotCommit};
use sov_rollup_interface::mocks::{MockBlock, MockBlockHeader, MockHash};
use sov_rollup_interface::services::da::SlotData;
use sov_rollup_interface::stf::fuzzing::BatchReceiptStrategyArgs;
use sov_rollup_interface::stf::{BatchReceipt, Event, TransactionReceipt};
use sov_rollup_interface::stf::{BatchReceipt, LegacyEvent, TransactionReceipt};
#[cfg(test)]
use sov_stf_runner::RpcConfig;
use tendermint::crypto::Sha256;
Expand Down Expand Up @@ -116,8 +116,8 @@ fn regular_test_helper(payload: serde_json::Value, expected: &serde_json::Value)
tx_hash: ::sha2::Sha256::digest(b"tx2"),
body_to_save: Some(b"tx2 body".to_vec()),
events: vec![
Event::new("event1_key", "event1_value"),
Event::new("event2_key", "event2_value"),
LegacyEvent::new("event1_key", "event1_value"),
LegacyEvent::new("event2_key", "event2_value"),
],
receipt: 1,
},
Expand Down Expand Up @@ -541,7 +541,7 @@ proptest!(

if random_event_num_usize < *end_event_range {
let event_index = random_event_num_usize - *start_event_range;
let event: &Event = tx.events.get(event_index).unwrap();
let event: &LegacyEvent = tx.events.get(event_index).unwrap();
let event_json = json!({
"key": event.key().inner(),
"value": event.value().inner(),
Expand Down
4 changes: 2 additions & 2 deletions examples/demo-rollup/stf/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use sov_modules_api::macros::DefaultRuntime;
use sov_modules_api::macros::{expose_rpc, CliWallet};
#[cfg(feature = "native")]
use sov_modules_api::Spec;
use sov_modules_api::{Context, DispatchCall, Genesis, MessageCodec};
use sov_modules_api::{Context, DispatchCall, Genesis, MessageCodec, RuntimeEvent};
#[cfg(feature = "native")]
use sov_nft_module::{NonFungibleTokenRpcImpl, NonFungibleTokenRpcServer};
use sov_rollup_interface::da::DaSpec;
Expand All @@ -64,7 +64,7 @@ use crate::genesis_config::GenesisPaths;

/// The `demo-stf runtime`.
#[cfg_attr(feature = "native", derive(CliWallet), expose_rpc)]
#[derive(Genesis, DispatchCall, MessageCodec, DefaultRuntime)]
#[derive(Genesis, DispatchCall, RuntimeEvent, MessageCodec, DefaultRuntime)]
#[serialization(borsh::BorshDeserialize, borsh::BorshSerialize)]
#[cfg_attr(
feature = "native",
Expand Down
1 change: 0 additions & 1 deletion examples/simple-nft-module/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,6 @@ Here is some boilerplate for NFT module integration tests:
use simple_nft_module::{CallMessage, NonFungibleToken, NonFungibleTokenConfig, OwnerResponse};
use sov_modules_api::default_context::DefaultContext;
use sov_modules_api::{Address, Context, Module, WorkingSet};
use sov_rollup_interface::stf::Event;
use sov_state::{DefaultStorageSpec, ProverStorage};

pub type C = DefaultContext;
Expand Down
8 changes: 4 additions & 4 deletions examples/simple-nft-module/tests/nft_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use simple_nft_module::{CallMessage, NonFungibleToken, NonFungibleTokenConfig, O
use sov_modules_api::default_context::DefaultContext;
use sov_modules_api::utils::generate_address as gen_addr_generic;
use sov_modules_api::{Address, Context, Module, WorkingSet};
use sov_rollup_interface::stf::Event;
use sov_rollup_interface::stf::LegacyEvent;
use sov_state::{DefaultStorageSpec, ProverStorage};

pub type C = DefaultContext;
Expand Down Expand Up @@ -44,7 +44,7 @@ fn genesis_and_mint() {

assert_eq!(
working_set.events()[0],
Event::new("NFT mint", "A token with id 1 was minted")
LegacyEvent::new("NFT mint", "A token with id 1 was minted")
);
let query3: OwnerResponse<C> = nft.get_owner(1, &mut working_set).unwrap();
assert_eq!(query3.owner, Some(owner2));
Expand Down Expand Up @@ -97,7 +97,7 @@ fn transfer() {

assert_eq!(
working_set.events()[0],
Event::new("NFT transfer", "A token with id 1 was transferred")
LegacyEvent::new("NFT transfer", "A token with id 1 was transferred")
);

let token1_owner = query_token_owner(1, &mut working_set);
Expand Down Expand Up @@ -147,7 +147,7 @@ fn burn() {

assert_eq!(
working_set.events()[0],
Event::new("NFT burn", "A token with id 0 was burned")
LegacyEvent::new("NFT burn", "A token with id 0 was burned")
);
let query: OwnerResponse<C> = nft.get_owner(0, &mut working_set).unwrap();

Expand Down
4 changes: 2 additions & 2 deletions full-node/db/sov-db/src/ledger_db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex};

use serde::Serialize;
use sov_rollup_interface::services::da::SlotData;
use sov_rollup_interface::stf::{BatchReceipt, Event};
use sov_rollup_interface::stf::{BatchReceipt, LegacyEvent};
use sov_schema_db::{Schema, SchemaBatch, SeekKeyEncoder, DB};

use crate::rocks_db_config::gen_rocksdb_options;
Expand Down Expand Up @@ -204,7 +204,7 @@ impl LedgerDB {

fn put_event(
&self,
event: &Event,
event: &LegacyEvent,
event_number: &EventNumber,
tx_number: TxNumber,
schema_batch: &mut SchemaBatch,
Expand Down
6 changes: 3 additions & 3 deletions full-node/db/sov-db/src/ledger_db/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use sov_rollup_interface::rpc::{
LedgerRpcProvider, QueryMode, SlotIdAndOffset, SlotIdentifier, SlotResponse, TxIdAndOffset,
TxIdentifier, TxResponse,
};
use sov_rollup_interface::stf::Event;
use sov_rollup_interface::stf::LegacyEvent;
use tokio::sync::broadcast::Receiver;

use crate::schema::tables::{
Expand Down Expand Up @@ -119,7 +119,7 @@ impl LedgerRpcProvider for LedgerDB {
fn get_events(
&self,
event_ids: &[sov_rollup_interface::rpc::EventIdentifier],
) -> Result<Vec<Option<Event>>, anyhow::Error> {
) -> Result<Vec<Option<LegacyEvent>>, anyhow::Error> {
anyhow::ensure!(
event_ids.len() <= MAX_EVENTS_PER_REQUEST as usize,
"requested too many events. Requested: {}. Max: {}",
Expand Down Expand Up @@ -217,7 +217,7 @@ impl LedgerRpcProvider for LedgerDB {
.map(|mut txs| txs.pop().unwrap_or(None))
}

fn get_event_by_number(&self, number: u64) -> Result<Option<Event>, anyhow::Error> {
fn get_event_by_number(&self, number: u64) -> Result<Option<LegacyEvent>, anyhow::Error> {
self.get_events(&[EventIdentifier::Number(number)])
.map(|mut events| events.pop().unwrap_or(None))
}
Expand Down
4 changes: 2 additions & 2 deletions full-node/db/sov-db/src/schema/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use borsh::{maybestd, BorshDeserialize, BorshSerialize};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use jmt::storage::{Node, NodeKey};
use jmt::Version;
use sov_rollup_interface::stf::{Event, EventKey};
use sov_rollup_interface::stf::{EventKey, LegacyEvent};
use sov_schema_db::schema::{KeyDecoder, KeyEncoder, ValueCodec};
use sov_schema_db::{CodecError, SeekKeyEncoder};

Expand Down Expand Up @@ -246,7 +246,7 @@ define_table_with_default_codec!(

define_table_with_seek_key_codec!(
/// The primary store for event data
(EventByNumber) EventNumber => Event
(EventByNumber) EventNumber => LegacyEvent
);

define_table_with_default_codec!(
Expand Down
4 changes: 2 additions & 2 deletions full-node/db/sov-db/src/schema/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use borsh::{BorshDeserialize, BorshSerialize};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sov_rollup_interface::rpc::{BatchResponse, TxIdentifier, TxResponse};
use sov_rollup_interface::stf::{Event, EventKey, TransactionReceipt};
use sov_rollup_interface::stf::{EventKey, LegacyEvent, TransactionReceipt};

/// A cheaply cloneable bytes abstraction for use within the trust boundary of the node
/// (i.e. when interfacing with the database). Serializes and deserializes more efficiently,
Expand Down Expand Up @@ -122,7 +122,7 @@ impl<R: DeserializeOwned> TryFrom<StoredTransaction> for TxResponse<R> {
pub fn split_tx_for_storage<R: Serialize>(
tx: TransactionReceipt<R>,
event_offset: u64,
) -> (StoredTransaction, Vec<Event>) {
) -> (StoredTransaction, Vec<LegacyEvent>) {
let event_range = EventNumber(event_offset)..EventNumber(event_offset + tx.events.len() as u64);
let tx_for_storage = StoredTransaction {
hash: tx.tx_hash,
Expand Down
9 changes: 6 additions & 3 deletions full-node/sov-ledger-rpc/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use jsonrpsee::proc_macros::rpc;
use sov_rollup_interface::rpc::{
BatchIdentifier, EventIdentifier, QueryMode, SlotIdentifier, TxIdentifier,
};
use sov_rollup_interface::stf::Event;
use sov_rollup_interface::stf::LegacyEvent;

use crate::HexHash;

Expand Down Expand Up @@ -55,7 +55,10 @@ where

/// Gets a list of events by ID. The IDs need not be ordered.
#[method(name = "getEvents")]
async fn get_events(&self, event_ids: Vec<EventIdentifier>) -> RpcResult<Vec<Option<Event>>>;
async fn get_events(
&self,
event_ids: Vec<EventIdentifier>,
) -> RpcResult<Vec<Option<LegacyEvent>>>;

/// Gets a single slot by hash.
#[method(name = "getSlotByHash")]
Expand Down Expand Up @@ -99,7 +102,7 @@ where

/// Gets a single event by number.
#[method(name = "getEventByNumber")]
async fn get_event_by_number(&self, number: u64) -> RpcResult<Option<Event>>;
async fn get_event_by_number(&self, number: u64) -> RpcResult<Option<LegacyEvent>>;

/// Gets a single tx by number.
#[method(name = "getTransactionByNumber")]
Expand Down
8 changes: 4 additions & 4 deletions full-node/sov-ledger-rpc/tests/empty_ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use sov_db::ledger_db::LedgerDB;
use sov_ledger_rpc::client::RpcClient;
use sov_ledger_rpc::server::rpc_module;
use sov_ledger_rpc::HexHash;
use sov_modules_api::Event;
use sov_modules_api::LegacyEvent;
use sov_rollup_interface::rpc::{
BatchResponse, EventIdentifier, QueryMode, SlotResponse, TxIdAndOffset, TxIdentifier,
TxResponse,
Expand Down Expand Up @@ -155,15 +155,15 @@ async fn get_events_patterns() {
.await
.unwrap();
rpc_client
.request::<Vec<Option<Event>>, _>("ledger_getEvents", vec![vec![2]])
.request::<Vec<Option<LegacyEvent>>, _>("ledger_getEvents", vec![vec![2]])
.await
.unwrap();
rpc_client
.request::<Vec<Option<Event>>, _>("ledger_getEvents", vec![2])
.request::<Vec<Option<LegacyEvent>>, _>("ledger_getEvents", vec![2])
.await
.unwrap();
rpc_client
.request::<Vec<Option<Event>>, _>(
.request::<Vec<Option<LegacyEvent>>, _>(
"ledger_getEvents",
vec![EventIdentifier::TxIdAndOffset(TxIdAndOffset {
tx_id: TxIdentifier::Number(1),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt::Debug;
use anyhow::Result;
#[cfg(feature = "native")]
use sov_modules_api::macros::CliWalletArg;
use sov_modules_api::{CallResponse, WorkingSet};
use sov_modules_api::{CallResponse, Event, WorkingSet};
use thiserror::Error;

use super::ValueSetter;
Expand All @@ -25,6 +25,21 @@ pub enum CallMessage {
),
}

/// This enumeration represents the available events that result from interacting with the `sov-value-setter` module.
#[cfg_attr(
feature = "native",
derive(serde::Serialize),
derive(serde::Deserialize)
)]
#[derive(Event, borsh::BorshDeserialize, borsh::BorshSerialize, Debug, PartialEq, Clone)]
pub enum ValueSetterEvent {
/// Value set
ValueSet(
/// new value
u32,
),
}

/// Example of a custom error.
#[derive(Debug, Error)]
enum SetValueError {
Expand All @@ -50,6 +65,7 @@ impl<C: sov_modules_api::Context> ValueSetter<C> {

// This is how we set a new value:
self.value.set(&new_value, working_set);
// TODO: replace add event functionality to be similar to self.event.add()
working_set.add_event("set", &format!("value_set: {new_value:?}"));

Ok(CallResponse::default())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl<C: sov_modules_api::Context> sov_modules_api::Module for ValueSetter<C> {

type CallMessage = call::CallMessage;

type Event = ();
type Event = call::ValueSetterEvent;

fn genesis(&self, config: &Self::Config, working_set: &mut WorkingSet<C>) -> Result<(), Error> {
// The initialization logic
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use sov_modules_api::default_context::{DefaultContext, ZkDefaultContext};
use sov_modules_api::{Address, Context, Event, Module, WorkingSet};
use sov_modules_api::{Address, Context, LegacyEvent, Module, WorkingSet};
use sov_state::{ProverStorage, ZkStorage};

use super::ValueSetter;
Expand Down Expand Up @@ -44,7 +44,7 @@ fn test_value_setter_helper<C: Context>(
{
module.call(call_msg, &context, working_set).unwrap();
let event = &working_set.events()[0];
assert_eq!(event, &Event::new("set", "value_set: 99"));
assert_eq!(event, &LegacyEvent::new("set", "value_set: 99"));
}

// Test query
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use sov_modules_api::default_context::{DefaultContext, ZkDefaultContext};
use sov_modules_api::{Context, Event, Prefix, StateMap, WorkingSet};
use sov_modules_api::{Context, LegacyEvent, Prefix, StateMap, WorkingSet};
use sov_state::{ProverStorage, Storage, ZkStorage};

use super::helpers::module_c;
Expand All @@ -18,11 +18,11 @@ fn nested_module_call_test() {
assert_eq!(
working_set.events(),
&vec![
Event::new("module C", "execute"),
Event::new("module A", "update"),
Event::new("module B", "update"),
Event::new("module A", "update"),
Event::new("module A", "update"),
LegacyEvent::new("module C", "execute"),
LegacyEvent::new("module A", "update"),
LegacyEvent::new("module B", "update"),
LegacyEvent::new("module A", "update"),
LegacyEvent::new("module A", "update"),
]
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use module_template::{CallMessage, ExampleModule, ExampleModuleConfig, Response}
#[cfg(feature = "native")]
use sov_modules_api::default_context::DefaultContext;
use sov_modules_api::default_context::ZkDefaultContext;
use sov_modules_api::{Address, Context, Event, Module, WorkingSet};
use sov_modules_api::{Address, Context, LegacyEvent, Module, WorkingSet};
use sov_state::{DefaultStorageSpec, ProverStorage, ZkStorage};

#[test]
Expand Down Expand Up @@ -48,7 +48,7 @@ fn test_value_setter_helper<C: Context>(
{
module.call(call_msg, &context, working_set).unwrap();
let event = &working_set.events()[0];
assert_eq!(event, &Event::new("set", "value_set: 99"));
assert_eq!(event, &LegacyEvent::new("set", "value_set: 99"));
}

// Test query
Expand Down
21 changes: 19 additions & 2 deletions module-system/sov-modules-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
pub use sov_rollup_interface::da::{BlobReaderTrait, DaSpec};
pub use sov_rollup_interface::services::da::SlotData;
pub use sov_rollup_interface::stf::Event;
pub use sov_rollup_interface::stf::LegacyEvent;
pub use sov_rollup_interface::zk::{
StateTransition, ValidityCondition, ValidityConditionChecker, Zkvm,
};
Expand Down Expand Up @@ -306,7 +306,7 @@ pub trait Module {
type CallMessage: Debug + BorshSerialize + BorshDeserialize;

/// Module defined event resulting from a call method.
type Event: Debug + BorshSerialize + BorshDeserialize;
type Event: Event;

/// Genesis is called when a rollup is deployed and can be used to set initial state values in the module.
fn genesis(
Expand Down Expand Up @@ -340,6 +340,23 @@ pub trait Module {
}
}

impl Event for () {
fn event_key(&self) -> &'static str {
unimplemented!("Event type for this module does not exist.")
}
}
cemozerr marked this conversation as resolved.
Show resolved Hide resolved

/// Every module `Event` has to implement this trait.
///
/// You can use `#[derive(Event)]` to automatically implement the trait. If your `Event` is not an enum,
/// or if your `Event` type is a nested enum and you want to index events based on their nested fields,
/// you will need to implement the trait manually.
pub trait Event: Debug + BorshSerialize + BorshDeserialize {
/// Returns a static string slice that identifies the Event variant.
/// This string slice is primarily used to index Events from the DB.
fn event_key(&self) -> &'static str;
cemozerr marked this conversation as resolved.
Show resolved Hide resolved
}

/// A [`Module`] that has a well-defined and known [JSON
/// Schema](https://json-schema.org/) for its [`Module::CallMessage`].
///
Expand Down
5 changes: 4 additions & 1 deletion module-system/sov-modules-api/src/reexport_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/// type.
#[cfg(feature = "macros")]
pub use sov_modules_macros::DispatchCall;
/// Derives the <runtime_name>Event enum for a given runtime.
/// Derives the Event trait for a given Event enum.
#[cfg(feature = "macros")]
pub use sov_modules_macros::Event;
/// Derives the [`Genesis`](trait.Genesis.html) trait for the underlying runtime
Expand Down Expand Up @@ -80,6 +80,9 @@ pub use sov_modules_macros::ModuleCallJsonSchema;
/// ```
#[cfg(feature = "macros")]
pub use sov_modules_macros::ModuleInfo;
/// Derives the <runtime_name>Event enum for a given runtime.
#[cfg(feature = "macros")]
pub use sov_modules_macros::RuntimeEvent;

/// Procedural macros to assist with creating new modules.
#[cfg(feature = "macros")]
Expand Down
Loading
Loading