Skip to content

Commit

Permalink
Merge pull request #1746 from o1-labs/feature/conditional-emit-event
Browse files Browse the repository at this point in the history
Conditional emit event
  • Loading branch information
mitschabaude authored Jul 12, 2024
2 parents 80f3937 + 8064bac commit 744c009
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased](https://github.com/o1-labs/o1js/compare/1c736add...HEAD)

### Added

- `SmartContract.emitEventIf()` to conditionally emit an event https://github.com/o1-labs/o1js/pull/1746

## [1.5.0](https://github.com/o1-labs/o1js/compare/ed198f305...1c736add) - 2024-07-09

### Breaking changes
Expand Down
26 changes: 21 additions & 5 deletions src/lib/mina/zkapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -968,9 +968,15 @@ super.init();

// TODO: not able to type event such that it is inferred correctly so far
/**
* Emits an event. Events will be emitted as a part of the transaction and can be collected by archive nodes.
* Conditionally emits an event.
*
* Events will be emitted as a part of the transaction and can be collected by archive nodes.
*/
emitEvent<K extends keyof this['events']>(type: K, event: any) {
emitEventIf<K extends keyof this['events']>(
condition: Bool,
type: K,
event: any
) {
let accountUpdate = this.self;
let eventTypes: (keyof this['events'])[] = Object.keys(this.events);
if (eventTypes.length === 0)
Expand All @@ -997,12 +1003,22 @@ super.init();
// if there is more than one event type, also store its index, like in an enum, to identify the type later
eventFields = [Field(eventNumber), ...eventType.toFields(event)];
}
accountUpdate.body.events = Events.pushEvent(
accountUpdate.body.events,
eventFields
let newEvents = Events.pushEvent(accountUpdate.body.events, eventFields);
accountUpdate.body.events = Provable.if(
condition,
Events,
newEvents,
accountUpdate.body.events
);
}

/**
* Emits an event. Events will be emitted as a part of the transaction and can be collected by archive nodes.
*/
emitEvent<K extends keyof this['events']>(type: K, event: any) {
this.emitEventIf(Bool(true), type, event);
}

/**
* Asynchronously fetches events emitted by this {@link SmartContract} and returns an array of events with their corresponding types.
* @async
Expand Down

0 comments on commit 744c009

Please sign in to comment.