Solidity programming

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
pragma solidity ^0.6.0; // Any versions of 0.6.X will do.

contract SimpleStorage{

uint256 public favouriteNumber; // This value will be initialised to 0

//----Other types of variables----//
// bool favouriteBool = true;
// string favouriteString = "String";
// int256 favouriteInt = -5;
// address favouriteAddress = 0xBEB40F5Fd51b8E499Ec25Eae84227b65ea84563E;
// bytes32 favouriteBytes = "cat"; // Strings can be converted to bytes

// --- Visibility --- //
// external - Can only be called by something outside of the contract
// public - Anyone can call this value / function
// internal - Can only be called by something inside of the contact, or any contracts deriving from it
// private - Can only be called by within the contract, and NOT by any contacts deriving from it

function store(uint256 _favouriteNumber) public {
favouriteNumber = _favouriteNumber;
}

// --- view, pure --- //
// `view`, `pure` do not cost any transactions.
// They only access the variables, and they do not make any state changes
// `view` lets you read a variable number
// `pure` function lets you do maths operation

function retrieve() public view returns(uint256){
return favouriteNumber;
}

// --- Struct --- //
// Make your new data structure using struct!

struct People {
uint256 favouriteNumber;
string name;
}

People public person = People({favouriteNumber: 777, name: "Hyunggi"});

// --- Arrays --- //
// People[] public people_dynamic_array;
// People[2] public people_static_array;
People[] public people;

// --- mapping --- //
// mapping - very similar to Python Dictionary. Hash table.
mapping(string => uint256) public nameToFavouriteNumber;

// --- memory vs storage --- //
// memory - Data will only be wstored during the execution of the function
// storage - Data will persist even after the execution

function addPerson(string memory _name, uint256 _favouriteNumber) public{
people.push(People(_favouriteNumber, _name));
nameToFavouriteNumber[_name] = _favouriteNumber;
}
}