Skip to content

Commit

Permalink
Change the events contract to be an adaption of the increment example (
Browse files Browse the repository at this point in the history
  • Loading branch information
leighmcculloch authored Oct 8, 2022
1 parent 395d839 commit 2b29013
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 12 deletions.
37 changes: 29 additions & 8 deletions events/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
#![no_std]
use soroban_sdk::{contractimpl, map, symbol, Env, Symbol};
use soroban_sdk::{contractimpl, symbol, Env, Symbol};

pub struct EventsContract;
const COUNTER: Symbol = symbol!("COUNTER");

pub struct IncrementContract;

#[contractimpl]
impl EventsContract {
pub fn hello(env: Env, to: Symbol) -> () {
let events = env.events();
let topics = (symbol!("Hello"), to);
let data = map![&env, (1u32, 2u32)];
events.publish(topics, data);
impl IncrementContract {
/// Increment increments an internal counter, and returns the value.
pub fn increment(env: Env) -> u32 {
// Get the current count.
let mut count: u32 = env
.data()
.get(COUNTER)
.unwrap_or(Ok(0)) // If no value set, assume 0.
.unwrap(); // Panic if the value of COUNTER is not u32.

// Increment the count.
count += 1;

// Save the count.
env.data().set(COUNTER, count);

// Publish an event about the increment occuring.
// The event has two topics:
// - The "COUNTER" symbol.
// - The "increment" symbol.
// The event data is the count.
env.events().publish((COUNTER, symbol!("increment")), count);

// Return the count to the caller.
count
}
}

Expand Down
32 changes: 28 additions & 4 deletions events/src/test.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
#![cfg(test)]

use super::*;
use soroban_sdk::{symbol, Env};
use soroban_sdk::{testutils::Events, vec, Env, IntoVal};

#[test]
fn test() {
let env = Env::default();
let contract_id = env.register_contract(None, EventsContract);
let client = EventsContractClient::new(&env, &contract_id);
let contract_id = env.register_contract(None, IncrementContract);
let client = IncrementContractClient::new(&env, &contract_id);

client.hello(&symbol!("Dev"));
assert_eq!(client.increment(), 1);
assert_eq!(client.increment(), 2);
assert_eq!(client.increment(), 3);

assert_eq!(
env.events().all(),
vec![
&env,
(
contract_id.clone(),
(symbol!("COUNTER"), symbol!("increment")).into_val(&env),
1u32.into_val(&env)
),
(
contract_id.clone(),
(symbol!("COUNTER"), symbol!("increment")).into_val(&env),
2u32.into_val(&env)
),
(
contract_id.clone(),
(symbol!("COUNTER"), symbol!("increment")).into_val(&env),
3u32.into_val(&env)
),
]
);
}

0 comments on commit 2b29013

Please sign in to comment.