Skip to main content

Example

This page presents a complete simple example of event emission and reception.

Setup

This example requires node.js and completium-cli to be installed.

Run the following to install completium-cli:

npm i -g @completium/completium-cli

If it is already installed, check that the version is at least 0.3.35 with:

completium-cli version

Set completium to work with testnet (Ithaca protocol at the time of writing) with the following command:

$ completium-cli set endpoint https://ithacanet.ecadinfra.com

The following commands init the example project:

$ mkdir event-example
$ cd event-example
$ npm init -y
$ npm i @completium/event-well-crank @completium/completium-cli
$ touch index.mjs emitter.arl

Emitter contract

The emitter contract emits an event when the input natural integer is odd. Copy paste the code below in emitter.arl file:

archetype odd_emitter

event Odd {
val : nat
}

entry isodd(v : nat) {
if v % 2 = 1 then
emit<Odd>({ v })
}

Deploy the contract with the following command:

completium-cli deploy emitter.arl

Receiver app

The receiver program shall:

  • define the Odd event handler function
  • register the event handler
  • start the crank

The Odd event type and register function are generated by completium:

completium-cli generate bindings-js emitter.arl > bindings-emitter.mjs
info

The typescript version is also available with bindings-ts option.

We can then import and use the bindings. Copy paste the code below in index.mjs file:

import { runCrank } from '@completium/event-well-crank'
import { getContract } from '@completium/completium-cli'
import { register_Odd } from './bindings-emitter.mjs'

const handleOdd = e => {
console.log(`Received the odd number ${e.val}`)
}

const runTest = async () => {
const emitter = await getContract('emitter');
register_Odd(emitter.address, handleOdd);
await runCrank({
verbose: true,
endpoint: 'https://ithacanet.ecadinfra.com',
well: 'KT1ReVgfaUqHzWWiNRfPXQxf7TaBLVbxrztw'
})
}

runTest()
info

Options to start the crank with may be found here.

Execute

Start the receiver application with the following command:

node index.mjs
info

In verbose mode, the crank displays indexed blocks' hash in the console.

In another shell, call the emitter contract with the following:

completium-cli call emitter --entry isodd --arg '{ "v" : 43 }'

After a few blocks, the message will appear in the receiver application shell:

Received the odd number 43