This is a barebones walkthrough for developing a blockchain decentralized app (Dapp) for Etherium (ERC-20) based tokens. Goal is to go through all the steps needed to set up initial environment and build a first contract that compiles, deploys, test, and can interact with via web3.js Javascript in a web browser.
Step 3: Creating Variables and Functions
In this step we will add comments, state variables and functions to our contract. Be sure to complete Step 1 and Step 2 before attempting this step.
1. Comments can be designated in two ways. Use the // for single line and /* */ for multiline comments
// this is a single line comment /* use this for multiline comments */
2. State variables are variables whose values are permanently stored in the blockchain. You can declare a state variable in the body of the contract. Visibility can be public, internal or private for state variables. A public state variable gets an automatically generated “getter” function.
Each statement ends with a semi-colon “;”
Also we will be using the datatype “uint” (not to be confused with ‘unit’) which stands for unsigned integer.
Add the following to the body of your contract.
//contract state variable uint myVariable = 0;
3. Functions are the bits of code that do something.
If the function reads but does not make any changes to the state of the contract it can be declared as a “view” function. If the function only acts on the input and does not read the state of the contract it can be declared as a “pure” function. These designations are important as they can help reduce the cost of Etherium to process the contract.
Visibility can be external, public, internal or private for functions.
Also, a common convention is to add an underscore to function parameters to avoid confusion between state variables at the contract scope and parameters in the function scope.
Add the following two functions to the body of your contract below the constructor.
function setMyVariable(uint _x) public { myVariable = _x; }
function getMyVariable () public view returns (uint) { return myVariable; }
10. Now save the file (in most editors is shortcut keys “Ctrl + s”). Now return to the Command Prompt window and compile your contract.
truffle compile
You should get results like the following. If you get any errors be sure the file is located in the right folder, the code matches, and the file has been saved.