diff --git a/onchain/src/product/product.cairo b/onchain/src/product/product.cairo index ddfbcd9..9eb6322 100644 --- a/onchain/src/product/product.cairo +++ b/onchain/src/product/product.cairo @@ -25,9 +25,19 @@ pub mod Product { #[event] #[derive(Drop, starknet::Event)] - enum Event { + pub enum Event { #[flat] OwnableEvent: OwnableComponent::Event, + ProductRegistered: ProductRegistered + } + + /// @notice Emitted when a product is registered + /// @param product_id the ID of the product + /// @param ipfs_hash + #[derive(Drop, starknet::Event)] + pub struct ProductRegistered { + pub product_id: felt252, + pub ipfs_hash: ByteArray } #[constructor] @@ -52,8 +62,9 @@ pub mod Product { fn register_product(ref self: ContractState, product_id: felt252, ipfs_hash: ByteArray) { self.ownable.assert_only_owner(); - self.products.write(product_id, ipfs_hash); + self.products.write(product_id.clone(), ipfs_hash.clone()); + + self.emit(ProductRegistered { product_id, ipfs_hash, }); } } } - diff --git a/onchain/tests/test_product.cairo b/onchain/tests/test_product.cairo index 8d0e511..2573b40 100644 --- a/onchain/tests/test_product.cairo +++ b/onchain/tests/test_product.cairo @@ -5,9 +5,10 @@ use openzeppelin::access::ownable::interface::{IOwnableDispatcher, IOwnableDispa use starknet::ContractAddress; use snforge_std::{ declare, ContractClassTrait, DeclareResultTrait, start_cheat_caller_address, - stop_cheat_caller_address + stop_cheat_caller_address, spy_events, EventSpyAssertionsTrait }; use scanguard::interfaces::IProduct::{IProductsDispatcher, IProductsDispatcherTrait}; +use scanguard::product::product::{Product::Event, Product::ProductRegistered}; const ZERO_ADDR: felt252 = 0x0; @@ -78,6 +79,35 @@ fn test_register_product_() { stop_cheat_caller_address(product_contract_address); } +#[test] +fn test_register_product_event_emission() { + let product_contract_address = __setup__(OWNER_ADDR); + let product_dispatcher = IProductsDispatcher { contract_address: product_contract_address }; + let mut spy = spy_events(); + + start_cheat_caller_address(product_contract_address, OWNER_ADDR.try_into().unwrap()); + + let product_id: felt252 = 1; + let ipfs_hash: ByteArray = "QmVqyWcuoBpHvt5tT5Gw9eJz2qYJyGKw4NY4yEdFcopK69"; + + product_dispatcher.register_product(product_id, ipfs_hash.clone()); + + let verified_product = product_dispatcher.verify(product_id); + assert(ipfs_hash == verified_product.ipfs_hash, 'no products found'); + + stop_cheat_caller_address(product_contract_address); + + spy + .assert_emitted( + @array![ + ( + product_contract_address, + Event::ProductRegistered(ProductRegistered { product_id, ipfs_hash }) + ) + ] + ); +} + #[test] fn test_register_multiple_products() { let product_contract_address = __setup__(OWNER_ADDR);