-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tutorial
84 lines (56 loc) · 2.68 KB
/
Tutorial
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
contract Example {
// This is the owner of the contract
address owner;
// This is our counter struct. It will hold necessary information about the counter which are
// number and description
struct Counter {
uint number;
string description;
}
// Here we create an instance of our Counter.
// It is empty for now, but we will initialize it in the constructor.
Counter counter;
// We will use this modidifer with our execute functions.
// This modifiers make sure that the caller of the function is the owner of the contract.
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can increment or decrement the counter");
_;
}
// This is our constructor function. It only runs once when we deploy the contract.
// Since it takes two parameters, initial_value and description, they should be provided
// when we deploy our contract.
constructor(uint initial_value, string memory description) {
owner = msg.sender;
counter = Counter(initial_value, description);
}
// Below, we have two execute functions, increment_counter and decrement_counter
// Since they modify data on chain, they require gas fee.
// They are external functions, meaning they can only be called outside of the contract.
// They also have the onlyOwner modifier which we created above. This make sure that
// only the owner of this contract can call these functions.
// This function gets the number field from the counter struct and increases it by one.
function increment_counter() external onlyOwner {
counter.number += 1;
counter.description = " Increased by 1";
}
// This function is similar the one above, but instead of increasing we deacrease the number by one.
function decrement_counter() external onlyOwner {
counter.number -= 1;
counter.description = "Decreased by 1";
}
// The function below is a query function.
// It does not change any data on the chain. It just rerieves data.
// We use the keyword view to indicate it retrieves data but does not change any.
// Since we are not modifying any data, we do not pay any gas fee.
// This function returns the number field of our counter struct.
// Returning the current state of our counter.
function get_counter_value() external view returns(uint) {
return counter.number;
}
// This function returns the description of the counter
function get_counter_description() external view returns(string memory)
{return counter.description;
}
}