Skip to content
This repository has been archived by the owner on Dec 6, 2024. It is now read-only.

feat: created and emitted product registered event #22

Merged
17 changes: 14 additions & 3 deletions onchain/src/product/product.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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, });
}
}
}

32 changes: 31 additions & 1 deletion onchain/tests/test_product.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
Loading