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";
ledger {
// public state
round: Counter;
}
// transition function changing public state
export circuit increment(): Void {
ledger.round.increment(1);
}
To make sense of this Compact code, start in the middle, with the
ledger
declaration. It says that the public state of the contract,
visible on the Midnight blockchain, consists of a single 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 this public ledger
declaration, 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.