first level title
What is Solidity?
Solidity is a contract-oriented high-level programming language for implementing smart contracts. Solidity has been designed for the Ethereum Virtual Machine.
Solidity = = = smart contract.
pragma solidity >=0.5.0 <0.6.0;
contract HelloWorld {
}
In the code above, we provide versions taking into account that our code is compatible with any version b/w 0.5 to 0.6. We also created a contract called "HelloWorld".
first level title
State Variables and Integers
contract Example {
// This will be stored permanently in the blockchain
uint myUnsignedInteger = 100;
string name = "vivek"
}
The Uint data type is an unsigned integer. It should be non-negative.
first level title
type of data
Value type:
Boolean(true/false), Integers(int/uint), Address(Size of Ethereum address), String, enum
Reference type:
first level title
Addition: x + y
Subtraction: x — y,
Multiplication: x * y
Division: x / y
Modulus / remainder: x % y (for example, 13 % 5 is 3, because if you divide 5 into 13, 3 is the remainder)
Exponential Operation uint x = 5 ** 2; // equal to 5² = 25
structure
first level title
struct Person {
uint age;
string name;
array
array
A collection of data is called an array. Two types: fixed array and dynamic array.
// Array with a fixed length of 2 elements:
uint[2] fixedArray;
// another fixed Array, can contain 5
strings: string[5] stringArray;
// a dynamic Array — has no fixed size, can keep growing:
uint[] dynamicArray;
We can combine structs and arrays. Create a struct, then have an array of structs. It's like having an object and an array of objects in an object-oriented paradigm like Java.
pragma solidity >=0.5.0 <0.6.0;
contract StudentFactory {
struct student {
string name;
uint roll; } student[] public students; // creates an array named students of student type objects
first level title
function eatHamburgers(string memory _name, uint _amount) public { }
function declaration
By value and by reference
eatHamburgers(“vitalik”, 100);
first level title
private/public functions
function _eatHamburgers(string memory _name, uint _amount) private {
}
By convention, private functions start with an underscore.
internal/external keywords
text
External is similar to public. This function can be called by all contracts except contacts that declare this function.
first level title
return in function
function sayHi() public view/pure returns (string memory) {
return “Hi”;
}
These functions can be marked as pure/view. We mark a function as pure when we don't even have access to the passed data. If the function does not modify the data, but only views the data, then it will be marked as view.
first level title
event
uint8 a = 5;
uint b = 6;
// line below throws an error because a*b returns a uint, not uint8:
uint8 c = a * b;
// we have to typecast b as a uint8 to make it work:
uint8 c = a * uint8(b);
event
text
// declare the event
event NotifyOnFrontend(uint x);
function add(uint _x, uint _y) public returns (uint) {
uint result = _x + _y;
//fire an event to let the frontend know the function was called
emit NotifyOnFrontend(result);
return result;
}
Our frontend code should already have web3 installed and should listen to the "NotifyOnFrontend" event for this to work. Our JavaScript framework or plain JS will have to listen to this event to receive it:
YourContract.NotifyOnFrontend(function(error, result) {
// do something with result
})
first level title
map
mapping (address => uint) public accountBalance;
This is another way to store organized data such as arrays and structures
This can be used to store multiple objects (data) in the blockchain. An example check is as follows:
example:
contract Example {
struct UserInfo {
unit age; string dob;
}
mapping(string => UserInfo) allusers;
function setUserInfo(string _name, uint _age, string _dob) public {
allusers[_name].age = _age;
allusers[_name].dob = _dob;
}
function getUserInfo(string name) public view returns(uint, string) {
return (allusers[name].age, allusers[_name].dob);
}
}
example:
setuserInfo("Vivek",26, 25/05/1995) setuserInfo("Supu", 23, 01/09/1998)
To get these values, just pass the name:
getUserInfo("Vivek"); // 26 25/05/1995
getuserInfo("Supu"); // 24 01/09/1998
first level title
These variables are available to all functions like msg.sender. Any Solidity program we write should be invoked by the owner. The sender's address is stored in the msg.sender global variable.
require
first level title
function sayHi(string memory name) public returns (string memory) { /Compares if _name equals “Vivek” Throws an error and exits if not true. Solidity doesn’t have native string comparison, so we compare their keccak256 hashes to see if the strings are equaq /
require(keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked(“Vivek”)));
// If it’s true, proceed with the function:
return “Hi!”;
}
sayHi(“Vivek”) // executes successfully
sayHi(“Supu”) // throws an error
Therefore, require is very useful for verifying that certain conditions must be true before running a function.
inherit
Sometimes, instead of making a very long contract, it is better to split the code logic into multiple contracts to organize the code.
contract Animal {
function catchphrase() public returns (string memory) {
return “Animal”;
}
} contract Cat is Animal {
function anotherCatchphrase() public returns (string memory) {
return “Cat is an Animal”;
}
}
import
first level title
This is usually how long codebases are handled in Solidity projects.
first level title
Storage refers to variables that are permanently stored on the blockchain. Memory variables are temporary and are deleted between external function calls to the contract. Think of it like the hard drive and memory of a computer.
first level title
Interact with other contracts in the blockchain network
I will write a separate article on this. Now, keep it short:
contract GetNumber {
function getNum(uint _num) public returns(uint){
return _num;
}
To interact with other contracts, we declare an object-like interface. We create a contract and inside it declare a function that we want to call or use from another contract. A function is just a skeleton, it does not contain a body.
contract NumberInterface {
function getNum(uint _num) public returns(uint);
}
Suppose there is a contract and we want to use the above getNum function. To do this, we will create a contract in our project and declare a getNum function skeleton (without function body).
After a contract is deployed to Ethereum, it becomes immutable, meaning it cannot be modified. The initial code deployed into the contract will stay on the blockchain forever. This is one of the reasons why security is so important in Solidity. If there is a bug in our contract code, there is no way to patch it later. Have to tell our users to start using a different smart contract address with a fix.
first level title
function modifier
This helps to update critical parts of the DApp while preventing other users from breaking our contracts. One use case that I have dealt with is - when we want to validate statement before executing any use case.
gas
Users pay gas fees to run contracts on the Ethereum network. Gas is calculated in ether (the currency on Ethereum). The total gas cost of our function is equal to the total gas cost of all its individual operations.
first level title
More about storage
Storage memory is permanently written into the blockchain. Thousands of nodes around the world need to store this data on their hard drives, and as the blockchain grows, the amount of this data will grow over time. So doing this comes at a price.
Therefore, it is recommended to use the memory type as much as possible so that the data is not stored permanently, thus saving costs. Loops will be cheaper in Solidity than using storage. So use memory in for loop as much as possible. This is the exact opposite of what is done in languages like Java, Python, etc., because for loops are more computationally expensive.
first level title
Syntax is similar to Javascript.
for (uint i = 1; i <= 10; i++) { // body }
Cope with modifiers
text
Payment functions are part of what makes Solidity and Ethereum so cool -- they're a special type of function that can receive Ether. When we call an API function on a normal web server, we can't send dollars at the same time we call the function -- nor can we send bitcoins.
This allows for some very interesting logic, such as paying a fee to a contract in order to execute a function.
Notice:
first level title
Token
So basically, a token is just a contract that records who owns how much tokens, and some functions so that those users can transfer their tokens to other addresses.
first level title
Assert is similar to require and throws an error if false. The difference between assert and require is that require refunds the user's remaining gas when a function fails, while assert does not.
Metamask
This is a browser extension for Chrome and Firefox that allows users to securely manage their Ethereum accounts and private keys, and use those accounts to interact with websites using Web3.js.
first level title
first level title
Web3Js
text
Source:https://medium.com/coinmonks/learn-all-about-solidity-ethereum-45d709c4de77
