The Counter Contract

​
πŸ“
The Code

Smart contracts are put at the contracts folder. Create the contract folder using:
1
mkdir contracts
Copied!
Placing smart contracts in the contracts folder is a convention of truffle. You can specify a different directory by modifying truffle configuration. Checkout the conracts_directory section in truffles document.
Once created the contracts folder , create the Counter.sol file with contents below:
Counter.sol
1
pragma solidity >=0.5.0 <0.7.0;
2
​
3
contract Counter {
4
uint32 public current_value;
5
​
6
function inc() public {
7
require(current_value < 10000, "Counter: max value");
8
current_value = current_value + 1;
9
}
10
​
11
function dec() public {
12
require(current_value > 0, "Counter: min value");
13
current_value = current_value - 1;
14
}
15
}
Copied!

​
🌟
Explain

The contract code is quite self explain:
  • A state variable current_value which is an unsigned integer.
  • inc() method, which increase the current_value by one.
  • dec() method, which decrease the current_value by one.
  • current_value has a bound of [0, 10000] which was checked in inc and dec methods.

​
πŸš—
Test out

Run command truffle compile, it will find and compiles the Counter contract. you should looks outputs like:
1
Compiling your contracts...
2
===========================
3
> Compiling ./contracts/Counter.sol
4
> Artifacts written to ~/counter-dapp/build/contracts
5
> Compiled successfully using:
6
- solc: 0.5.2+commit.1df8f40c.Emscripten.clang
Copied!
Truffle command will download solidity compiler at the first time. There could be some messages related to the compiler setup. It's normal.
​