In detail: the counter contract
The remainder of this part of the tutorial examines first the Compact contract and then the TypeScript code for the counter DApp.
The contract behind the counter DApp can be found within the Midnight examples directory at:
examples/counter/contract/src/counter.compact
If you have installed the Visual Studio Code extension for Compact, you might want to open the preceding file in VS Code to follow along.
The counter contract itself is very simple. Here are the entire
contents of counter.compact
:
include "std";
// public state
export ledger round: Counter;
// transition function changing public state
export circuit increment(): Void {
round.increment(1);
}
To make sense of this Compact code, start in the middle, with the
ledger
field declaration. It says that the public state of the contract,
visible on the Midnight blockchain, includes a field
round
. The Midnight ledger supports Counter
as one of its
native types,
so the field is declared to be of that type.
In addition to declaring ledger fields, a contract can
declare the functions that provide the interface to its
private state, each marked with the witness
keyword. The counter
contract has no support for such hidden, off-chain state, so no
witnesses are mentioned.
This contract provides a single public operation (circuit) that its
users can call: increment
. The increment
operation simply
increments the value of the round
counter by 1
.
The only other interesting line of code in this contract is the
include
that makes Compact's standard library ("std"
) available in
this file.
More interesting contracts can declare enumerations and structured types to be used in the ledger, multiple circuits (including unexported ones called only by other circuits in the contract), and the functions that manipulate private, off-chain state. You will learn much more about Midnight contracts in the next major section of this tutorial: the bulletin board example.