Contract events: listener
Focus: one listener contract that subscribes to a publisher event and stores the last payload.
price_listener.slx
const PRICE_EVENT: u64 = 100
const LAST_PRICE_KEY: string = "last_price"
fn on_price(args: any[]) -> u64 {
let storage: Storage = Storage::new()
storage.store(LAST_PRICE_KEY, args)
return 0
}
entry listen_to(oracle_hash: Hash) {
let oracle: Contract = Contract::new(oracle_hash).expect("oracle contract not found")
require(oracle.listen_event(PRICE_EVENT, on_price, 100000), "listen failed")
return 0
}
entry last_price() -> any[] {
let storage: Storage = Storage::new()
return storage.load(LAST_PRICE_KEY).unwrap_or([])
}How it works
PRICE_EVENTmust match the publisher’s event id.on_price(args: any[])is the callback signature for contract event payloads.- The callback stores the raw payload under
LAST_PRICE_KEY. listen_to(oracle_hash)loads the publisher contract and registers the callback with a gas limit.last_price()is a small read entry that stores the last observed payload as a typed exit value, or an empty array when no price was observed.
Run listen_to once with the publisher hash, then invoke publish_price on the publisher.
Last updated on