Skip to main content
Version: 1.0

Events

Events are special values that can be emitted during the execution of a program.

An event type can be declared with the event keyword.


_10
event FooEvent(x: Int, y: Int)

The syntax of an event declaration is similar to that of a function declaration; events contain named parameters, each of which has an optional argument label.

Event parameters may only have a valid event parameter type. Valid types are boolean, string, integer, arrays and dictionaries of these types, and structures where all fields have a valid event parameter type. Resource types are not allowed, because when a resource is used as an argument, it is moved.

Events can only be declared within a contract body. Events cannot be declared globally or within resource or struct types.


_15
// Invalid: An event cannot be declared globally
_15
//
_15
event GlobalEvent(field: Int)
_15
_15
access(all)
_15
contract Events {
_15
// Event with explicit argument labels
_15
//
_15
event BarEvent(labelA fieldA: Int, labelB fieldB: Int)
_15
_15
// Invalid: A resource type is not allowed to be used
_15
// because it would be moved and lost
_15
//
_15
event ResourceEvent(resourceField: @Vault)
_15
}

Emitting events​

To emit an event from a program, use the emit statement:


_16
access(all)
_16
contract Events {
_16
event FooEvent(x: Int, y: Int)
_16
_16
// Event with argument labels
_16
event BarEvent(labelA fieldA: Int, labelB fieldB: Int)
_16
_16
fun events() {
_16
emit FooEvent(x: 1, y: 2)
_16
_16
// Emit event with explicit argument labels
_16
// Note that the emitted event will only contain the field names,
_16
// not the argument labels used at the invocation site.
_16
emit BarEvent(labelA: 1, labelB: 2)
_16
}
_16
}

Emitting events has the following restrictions:

  • Events can only be invoked in an emit statement.

    This means events cannot be assigned to variables or used as function parameters.

  • Events can only be emitted from the location in which they are declared.