Simple Storage Smart Contract
Note
There is no code installation or command execution required in this section.
This section explains the SimpleStorage smart contract code.
In a Truffe project, all smart
contracts are placed in the contracts directory. If you have cloned from the GitLab project earlier,
git clone https://gitlab.com/gmc123/simple-storage-dapp.git
the smart contract file SimpleStorage.sol is in the contract directory.
ethereum-simple-Storage
|--contracts
| |--SimpleStorage.sol
|--migrations
|--test
|--truffle-config.js
Let us look at the code. With your knowledge of the Solidity language so far, the code should be easily understandable.
Define License and Solidity version
The first line in a Solidity smart contract defines the licence identifier and Solidity version. Without defining the exact Solidity version, we can define a range of Solidity versions.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
Define Contract with Unsigned Integer Value
We define the contract and an unsigned integer uint
attribute to hold the storage value. We use the
contract keyword and contract name
SimpleStorage to define the contract.
We use the constructor keyword to define the constructor of
the smart contract and to pass the constructor arguments. In this smart contract,
we pass the initial value of the storedData attribute as a constructor argument.
contract SimpleStorage {
uint private storedData;
constructor(uint _data) {
storedData = _data;
}
...
}
Getter Function to View “storedData” Value
We define a getter function to view the usigned integer value of the storedData attribute.
The format of the view function as follows.
function <function_name>() <visibility_of_the_function> view returns (<return_type>) {
<function_body>
}
We use the view keyword for getter functions. These functions do not change the smart contract state.
Here is the getter function.:
function get() public view returns (uint) {
return storedData;
}
Setter Function to Change “storedData” Value
We define the setter function to change the storedData value. The structure of the setter function as follows.
function <function_name>(<data_type> <data>) <visibility_of_the_function> {
<function_body>
}
The setter function for the storedData value is as follows.:
function set(uint x) public {
storedData = x;
}
Smart Contract
The entire smart contract is shown below.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract SimpleStorage {
uint private storedData;
constructor(uint _data) {
storedData = _data;
}
function get() public view returns (uint) {
return storedData;
}
function set(uint x) public {
storedData = x;
}
}