Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

DEEP DIVE INTO SOLIDITY

WELCOME

KEVIN JONES
AGENDA
WHAT IS SOLIDITY?

STANDARDS

EXAMPLES

HOMEWORK

CLOSING Q&A

2
WHAT IS
SOLIDITY?
LET’S DIVE IN

3
SOLIDITY
• Current version is 0.8.17
// SPDX-License-Identifier: GPL-3.0
• Object-oriented, high-level pragma solidity ^0.8.14;
language
• Static typed, Curly-braces
contract a {
• Optimization is important uint256 b;
function c() public {
• Source compiled into lower-level b = 2;
Bytecode }
• ABI is needed to encode contract }
calls and read data from
transactions
EXAMPLE.SOL > EVM BYTECODE > EVM READS AS ASSEMBLY (OPCODES)

pragma solidity ^0.8.14; 608060405234801561001057600080fd5b5 mstore(0x40, 0x80)


061012f806100206000396000f3fe6080604 callvalue
dup1
05260043610601c5760003560e01c806329 iszero
contract a { f4acb0146021575b600080fd5b6027603b5 tag_1
bool foo;
65b6040516032919060e0565b604051809 jumpi
constructor() public { 0x00
foo = true;
10390f35b6000336000806101000a815481
dup1
} 73ffffffffffffffffffffffffffffffffffffffff02191690 revert
uint256 x; 8373ffffffffffffffffffffffffffffffffffffffff160217 tag_1:
function bar() public { 90555060008054906101000a900473ffffffff pop
x = 2; ffffffffffffffffffffffffffffffff16905090565b600 0x01
} 073ffffffffffffffffffffffffffffffffffffffff8216905 0x00
dup1
} 0919050565b600060cc8260a3565b905091 0x0100
9050565b60da8160c3565b82525050565b6 exp
00060208201905060f3600083018460d356 dup2
contract b { sload
5b9291505056fea26469706673582212206
address x; dup2
function echo() public payable 5f62956920c06ca282ef1af06c0259685465 0xff
returns(address y) { b282d73018eb84826a3c7a2142064736f6c mul
x = msg.sender; 634300080e0033 not
return x; and
} swap1
dup4
}
iszero

SOLIDITY COMPILER (SOLC)

$ solc contract.sol --bin


Prints binary output (bytecode)

$ solc contract.sol --abi


Prints the Application Binary Interface

$ solc contract.sol --asm


low level instructions sent to the EVM

$ solc contract.sol --opcodes


alternative way to output opcodes

6
STANDARDS

ERC
PROTOCOL STANDARDS
TOKENS

Ethereum Request for Comment (ERC) is a set of technical


documents containing guidelines on developing a smart
contract.

Some examples…
• ERC-20 (FUNGIBLE TOKEN)
• ERC-721 (NON-FUNGIBLE TOKEN)
• ERC-1155 (SEMI-FUNGIBLE TOKEN)

Look at OpenZeppelin for full examples of each standard.

10
ERC-20 TOKEN STANDARD

• TotalSupply – Used to derive the total token supply of a specific


ERC-20 token

• BalanceOf – Used to derive the token balance in an Ethereum wallet

• Transfer – Allows the user to transfer the ownership of a token to


another

• TransferFrom – Works similarly to transfer function with the added


advantage of allowing contracts to transfer tokens on the user’s behalf

• Approve – Used to set a limit on the number of tokens a smart contract


can withdraw

• Allowance – Grants external addresses the access and permit to spend


the tokens from a certain balance

• Additionally, you might define Token Name, Ticker Symbol (e.g.


WBTC), and Divisibility

11
12
ERC-20 VS ERC-721

fun·gi·ble /ˈfənjəbəl/ ... able to replace or be replaced by


another identical item

FUNGIBLE NON-FUNGIBLE

1 =1

13
ERC-721 VS ERC-1155

ERC-721 ERC-1155

14
15
16
17
EXAMPLES

SOLIDITY
HELLO WORLD

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.13;

// compiler version must be greater than or equal to 0.8.13


and less than 0.9.0

contract HelloWorld {
string public greet = "Hello World!";
}

19
STATE

contract Counter {
uint public count;

function get() public view returns (uint) {


return count;
}

function inc() public {


count += 1;
}

function dec() public {


count -= 1;
}
}

20
STATE

// State variable to store a number

uint public num;

// You need to send a transaction to write to a state variable.


function setNum(uint _num) public {
num = _num;
}

// You can read from a state variable without sending a transaction.


function getNum() public view returns (uint) {
return num;
}

21
FUNCTIONS

contract HelloWorld {

string public purpose = "Build unstoppable Apps!!";

function setPurpose(string memory newPurpose) public payable {


purpose = newPurpose;
}

22
VARIABLES

There are 3 types of variables in


Solidity

•local
• declared inside a function
• not stored on the blockchain
•state
• declared outside a function
• stored on the blockchain
•global
•provides information about the
blockchain
23
VARIABLES

contract Variables {

// state variables
// stored on the blockchain.
string public text = "Hello";
uint public num = 123;

function doSomething() public {

// local variables
// not saved to the blockchain
uint i = 456;

// global variables
uint timestamp = block.timestamp; // Current block timestamp
address sender = msg.sender; // address of the caller
}
}
24
FUNCTION MODIFIER

// Modifiers can take inputs. This modifier checks that the


// address passed in is not the zero address.

modifier validAddress(address _addr) {


require(_addr != address(0), "Not valid address");
_;
}

function updateAddress(address _new) public validAddress(_new) {


current = _new;
}

25
DATA VALUE TYPES

• Signed/Unsigned integers - Integer data • Byte arrays - Byte arrays, declared with the
types store whole numbers, with signed keyword “bytes”, is a fixed-size array used to
integers storing both positive and negative store a predefined number of bytes up to 32,
values and unsigned integers storing usually declared along with the keyword
non-negative values. (bytes1, bytes2).

• Booleans - Boolean data type is declared with • Literals - Literals are immutable values such
the bool keyword, and can hold only two as addresses, rationals and integers, strings,
possible constant values, true or false. unicode and hexadecimals,  which can be
stored in a variable.
• Addresses - The address type is used to store
Ethereum wallet or smart contract addresses, • Enums - Enums, short for Enumerable, are a
typically around 20 bytes. An address type user-defined data type, that restrict the value
can be suffixed with the keyword “payable”, of the variable to a particular set of constants
which restricts it to store only wallet defined within the program.
addresses and use the transfer and send
crypto functions.
26
PRIMITIVE DATA TYPES

bool public boo = true;

uint8 public u8 = 1;
uint public u256 = 456;
uint public u = 123;

int8 public i8 = -1;


int public i256 = 456;
int public i = -123;
int public minInt = type(int).min;
int public maxInt = type(int).max;

address public addr = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;

bytes1 a = 0xb5; // [10110101]


bytes1 b = 0x56; // [01010110]

27
DEFAULT VALUES

// default values for data types

bool public defaultBoo; // false


uint public defaultUint; // 0
int public defaultInt; // 0
address public defaultAddr; // 0x0000000000000000000000000000000000000000

28
CONSTANTS

// coding convention to uppercase constant variables

address public constant MY_ADDRESS = 0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc;

uint public constant MY_UINT = 123;

29
IMMUTABLE

// Values can be set inside of the constructor but cannot be modified


afterwards

address public immutable OWNER;


uint public immutable SUPPLY;

constructor(uint _supply) {
OWNER = msg.sender;
SUPPLY = _supply;
}

30
ENUMS

// Enum representing shipping status


enum Status {
OFF,
ON
}

// Default value is the first element listed in


// definition of the type, in this case "OFF"
Status public status;

// Returns uint, OFF = 0, ON = 1


function get() public view returns (Status) {
return status;
}
// Update status by passing uint into input
function set(Status _status) public {
status = _status;
}
// You can update to a specific enum like this
function setON() public {
status = Status.ON;
}
// delete resets the enum to its first value, 0
function reset() public {
delete status;
}
31
REFERENCE TYPES

• Structs - Structs in Solidity are a complex


data type which allow you to create a custom
type containing members of other types,
usually used to group linked data.

• Mappings - Mappings store data in
key-value pairs similar to dictionaries in
other object-oriented languages, with the
key being a value data type, and value being
any type. 

32
MAPPINGS

// Mapping from address to uint


mapping(address => uint) public myMap;

function get(address _addr) public view returns (uint) {


// Mapping always returns a value.
// If the value was never set, it will return the default value.
return myMap[_addr];
}

function set(address _addr, uint _i) public {


// Update the value at this address
myMap[_addr] = _i;
}
function remove(address _addr) public {
// Reset the value to the default value.
delete myMap[_addr];
}

33
STRUCTS

struct Todo {
string text;
bool completed;
}

// An array of 'Todo' structs


Todo[] public todos;

function create(string calldata _text) public {


// 3 ways to initialize a struct
// - calling it like a function
todos.push(Todo(_text, false));
// key value mapping
todos.push(Todo({text: _text, completed: false}));
// initialize an empty struct and then update it
Todo memory todo; todo.text = _text;
// todo.completed initialized to false
todos.push(todo);
}

// Solidity automatically created a getter for 'todos' so


// you don't actually need this function.
function get(uint _index) public view returns (string memory text, bool completed) {
Todo storage todo = todos[_index];
return (todo.text, todo.completed);
}
// update text function updateText(uint _index, string calldata _text) public {
Todo storage todo = todos[_index];
todo.text = _text;
}
// update completed function toggleCompleted(uint _index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
} 34
IMPORT

// import Foo.sol from current directory


import "./Foo.sol";

// import {symbol1 as alias, symbol2} from "filename";


import {Unauthorized, add as func, Point} from "./Foo.sol";

contract Import {
// Initialize Foo.sol
Foo public foo = new Foo();

// Test Foo.sol by getting it's name.


function getFooName() public view returns (string memory) {
return foo.name();
}
}

35
INHERRITENCE

// import remotely
import "https://github.com/owner/repo/blob/branch/path/to/Contract.sol";

contract Import is Contract { ... }

36
OTHER FUNCTIONALITY

• If / Else
• For and While
Loops
• Array

37
HOMEWORK
KEEP GOING!

38
BOOKMARK AND READ…

39
BOOKMARK AND WATCH…

40
THANK YOU

kevin@kevinjonescreates.com

You might also like