Emitting Events with event::emit
Events allow smart contracts to emit signals that external applications can listen for, making it possible to track blockchain actions in real time.
For the latest RPC URL, please refer to the Supra Network Information page.
event::emit
Events are a way for your contract to communicate that something happened on the blockchain to your app front-end, which can be ‘listening’ for certain events and taking action when they happen.
In order to emit an event, you need to do two things:
- Define the event struct.
- Use
event::emitto emit it
#[event] annotation.Finally, let’s add an event named SpawnDinosaurEvent that contains the new Gendna code, and emit SpawnDinosaurEvent when a Dinosaur is created.
module 0xcafe::dinosaur_nest {
use supra_framework::event;
use std::vector;
struct DinosaurGendna has key {
gendna_digits: u64,
gendna_modulus: u256,
}
struct Dinosaur has store {
gendna: u64,
}
#[event]
struct SpawnDinosaurEvent has drop, store {
gendna: u64,
}
struct DinosaurSwarm has key {
dinosaurs: vector<Dinosaur>,
}
fun init_module(cafe_signer: &signer) {
let gendna_modulus: u256 = 10000000000;
move_to(cafe_signer, DinosaurGendna {
gendna_digits: 10,
gendna_modulus: gendna_modulus,
});
move_to(cafe_signer, DinosaurSwarm {
dinosaurs: vector[],
});
}
public fun spawn_dinosaur(gendna: u64) acquires DinosaurSwarm {
let dinosaur = Dinosaur {
gendna: gendna,
};
let dinosaur_swarm = borrow_global_mut<DinosaurSwarm>(@0xcafe);
vector::push_back(&mut dinosaur_swarm.dinosaurs, dinosaur);
event::emit(SpawnDinosaurEvent {
gendna: gendna,
});
}
public fun get_gendna_digits(): u64 acquires DinosaurGendna {
borrow_global<DinosaurGendna>(@0xcafe).gendna_digits
}
public fun set_gendna_digits(new_gendna_digits: u64) acquires DinosaurGendna {
let dinosaur_gendna = borrow_global_mut<DinosaurGendna>(@0xcafe);
dinosaur_gendna.gendna_digits = new_gendna_digits;
}
public fun get_first_dinosaur_gendna(): u64 acquires DinosaurSwarm {
let dinosaur_swarm = borrow_global<DinosaurSwarm>(@0xcafe);
let first_dinosaur = vector::borrow(&dinosaur_swarm.dinosaurs, 0);
first_dinosaur.gendna
}
}Wrapping Up
Till now you must have gotten a good idea of how things get built and how logic works in Move. Build your own version of the module in a package of your own to get hands-on practice.
Contribution
Feel free to contribute to this project by submitting pull requests or opening issues, all contributions that enhance the functionality or user experience of this project are welcome.