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
:
pragma language_version >= 0.14.0;
import CompactStandardLibrary;
// public state
export ledger round: Counter;
// transition function changing public state
export circuit increment(): [] {
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 state
types, and 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
.
There are two other lines of code in this contract, at the top of the file. The
first line is a pragma
that specifies a constraint on the Compact language
version. If the Compact compiler does not support the language versions
specified, it will signal a compile-time error. The second is the import
that
makes Compact's standard library (CompactStandardLibrary
) available in this
file. The standard library includes the ledger type Counter
and so it has to
be imported to make that type available.
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.