Solidity Programing Manual
Introduction to Smart Contracts
A Simple Smart Contract
pragma solidity ^0.4.24;
contract SimpleStorage { uint storedData;
function set(uint x) public {
storedData = x; }
function get() public view returns (uint) {
return storedData; } }
The first line simply tells that the source code is written for Solidity version 0.4.0 or anything
newer that does not break functionality (up to, but not including, version 0.5.0). This is to ensure
that the contract does not suddenly behave differently with a new compiler version. The keyword
pragma is called that way because, in general, pragmas are instructions for the compiler about
how to treat the source code (e.g. pragma once used in c & c++).
Structure of a Contract
Contracts in Solidity are similar to classes in object-oriented languages. Each contract can
contain declarations of State Variables, Functions, Function Modifiers, Events, Struct Types and
Enum Types. Furthermore, contracts can inherit from other contracts.
1.2.1 State Variables
State variables are values which are permanently stored in contract storage.
pragma solidity ^0.4.0;
contract SimpleStorage {
uint storedData; // State variable // ... }
Functions
Functions are the executable units of code within a contract.
pragma solidity ^0.4.0;
contract Test {
function sum() public { // F
unction
// ... } }
Events
Events are convenience interfaces with the EVM logging facilities.
pragma solidity ^0.4.21;
contract SimpleAuction {
event sumtotal(uint value); // Event
function sum() public {
// ... emit sumtotal(value); // Triggering event } }
Struct Types
Structs are custom defined types that can group several variables .
pragma solidity ^0.4.0;
contract Test {
struct Student { // Struct
uint id; string name; uint sex; string address; } }
SMART CONTRACT: SOLIDITY
Types
Solidity is a statically typed language, which means that the type of each variable (state and
local) needs to be specified (or at least known - see Type Deduction below) at compile-time.
Solidity provides several elementary types which can be combined to form complex types.
Value Types
The following types are also called value types because variables of these types will always be
passed by value, i.e. they are always copied when they are used as function arguments or in
assignments.
Booleans
bool: The possible values are constants true and false.
Operators:
o ! (logical negation)
o && (logical conjunction, “and”)
o || (logical disjunction, “or”)
o == (equality)
o != (inequality)
The operators || and && apply the common short-circuiting rules. This means that in the
expression f(x) || g(y), if f(x) evaluates to true, g(y) will not be evaluated even if it may
have side-effects.
Integers
int / uint: Signed and unsigned integers of various sizes. Keywords uint8 to uint256 in
steps of 8 (unsigned of 8 up to 256 bits) and int8 to int256. uint and int are aliases for
uint256 and int256, respectively.
Operators:
o Comparisons: <=, <, ==, !=, >=, > (evaluate to bool)
o Bit operators: &, |, ^ (bitwise exclusive or), ~ (bitwise negation)
o Arithmetic operators: +, -, unary -, unary +, *, /, % (remainder), ** (exponentiation),
<< (left shift), >> (right shift)
Division always truncates (it is just compiled to the DIV opcode of the EVM), but it does
not truncate if both operators are literals (or literal expressions).
Address
address: Holds a 20-byte value (size of an Ethereum address). Address types also have members
and serve as a base for all contracts.
Operators:
o <=, <, ==, !=, >= and >
String Literals
String literals are written with either double or single-quotes ("foo" or 'bar'). They do not imply
trailing zeroes as in C; "foo" represents three bytes not four. As with integer literals, their type
can vary, but they are implicitly convertible to bytes1, ..., bytes32, if they fit, to bytes and to
string.
Mapping
Mapping types are declared as mapping(_KeyType => _ValueType). Here _KeyType can be
almost any type except for a mapping, a dynamically sized array, a contract, an enum and a
struct. _ValueType can actually be any type, including mappings.
Mappings can be seen as hash tables which are virtually initialized such that every possible key
exists and is mapped to a value whose byte-representation is all zeros: a type’s default value. The
similarity ends here, though: The key data is not actually stored in a mapping, only its keccak256
hash used to look up the value.
Because of this, mappings do not have a length, or a concept of a key or value being “set”.
Mappings are only allowed for state variables.
It is possible to mark mappings public and have Solidity create a getter. The _KeyType will
become a required parameter for the getter and it will return _ValueType.
The _ValueType can be a mapping too. The getter will have one parameter for each _KeyType,
recursively.
pragma solidity ^0.4.0;
contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) public {
balances[msg.sender] = newBalance; } function retrieve(address useraddress) public
returns (uint){
return balances[useraddress]; } }
SMART CONTRACT: SOLIDITY
Control Structures
Most of the control structures from JavaScript are available in Solidity except for switch and
goto.
There is:
o if
o else
o while
o do
o for
o break
o continue
o return
o ? :
with the usual semantics known from C or JavaScript.
Program 2 :Set Name and Age
pragma solidity ^0.4.24;
contract MyFirstContract {
string private name;
uint private age;
function s
etName(string newName) public {
name = newName;
}
function getName() public view returns (string) {
return name;
}
function setAge(uint newAge) public {
age = newAge;
}
function getAge() public view returns (uint) {
return age;
}
}
Program 3 Basic Banking
pragma solidity ^0.4.0;
interface Regulator {
function checkValue(uint amount) external returns (bool);
function loan() external returns (bool);
}
contract Bank is Regulator {
uint private value;
constructor(uint amount) public {
value = amount;
}
function deposit(uint amount) public {
value += amount;
}
function withdraw(uint amount) public {
if (checkValue(amount)) {
value -= amount;
}
}
function balance() public view returns (uint) {
return value;
}
function checkValue(uint amount) public returns (bool) {
return value >= amount;
}
function loan() public returns (bool) {
return value > 0;
}
}
contract MyFirstContract is Bank(10) {
string private name;
uint private age;
etName(string newName) public {
function s
name = newName;
}
function getName() public view returns (string) {
return name;
}
function setAge(uint newAge) public {
age = newAge;
}
function getAge() public view returns (uint) {
return age;
}
}
Bonus Program
pragma solidity ^0.4.0;
interface Regulator {
function checkValue(uint amount) external returns (bool);
function loan() external returns (bool);
}
contract Bank is Regulator {
uint private value;
address private owner;
modifier ownerFunc {
require(owner == msg.sender);
_;
}
constructor(uint amount) public {
value = amount;
owner = msg.sender;
}
function deposit(uint amount) public ownerFunc {
value += amount;
}
function withdraw(uint amount) public ownerFunc {
if (checkValue(amount)) {
value -= amount;
}
}
function balance() public view returns (uint) {
return value;
}
function checkValue(uint amount) public returns (bool) {
return value >= amount;
}
function loan() public returns (bool) {
return value > 0;
}
}
contract MyFirstContract is Bank(10) {
string private name;
uint private age;
function s
etName(string newName) public {
name = newName;
}
function getName() public view returns (string) {
return name;
}
function setAge(uint newAge) public {
age = newAge;
}
function getAge() public view returns (uint) {
return age;
}
}
contract TestThrows {
function testAssert() public pure {
assert(1 == 2);
}
function testRequire() public pure {
require(2 == 1);
}
function testRevert() public pure {
revert();
}
function testThrow() public pure {
throw;
}
}