9 min read

Solidity

1.0 Solidity overview

Solidity was proposed in 2014, first public version came in 2015. Was created by Gavin Wood (Ethereum co founder) in England and maintained in Switzerland. It was created because Ethereum team needed a language that could write smart contract codes and be familiar to existing developers (C++, Java, JavaScript)

Solidity is a high level, statically typed programming langauge used to write smart contracts - programs that run on blockchains compatible with EVM

Solidity smart contract files use .sol extension
pragma primitive tells which Solidity compiler version is allowed
smart contract is defined using contract keyword

Solidity code is compiled and converted into machine readable bytecode

just like html is DSL for web structures, SQL issa DSL for querying databases, Solidity is a DSL for smart contracts on the EVM

1.1 Solidity data types

primitive data types (stores actual value directly):
a. bool
b. uint
c. int
d. address - stores Ethereum wallet/contract address (20bits)

non primitive data types (stores a reference to the value):
a. bytes - stores raw binary/hexadecimal
b. string - stores text, internally stored as bytes
c. variable - named container that stores data

1.2 Functions

solidity
function functionName(parameters) visibility {
    // code
}


function store(uint256 _favoriteNumber) public {
    favoriteNumber = _favoriteNumber;
}

favoriteNumber → state variable (stored on blockchain)
_favoriteNumber → local function parameter

1.3 Deploying contracts

deploying contract means publishing contract bytecode to blockchain
after deployment, contract gets unique address and becomes accessible to everyone

every smart contract gets a unique blockchain address

a transaction is a blockchain action that modifies state

Gas issa computational fee paid for blockchain operations
more gas for writing storage, heavy computation, larger bytecode

1.4 Visibility Keywords

you can store value but cannot read it externally unless exposed

solidity
uint256 public favoriteNumber; // now this variable is readble externally
  1. public
    accessible inside/outside/other contracts
  2. private
    accessible in current contract only
  3. external
    accessible outside contract only
  4. internal
    accessible current contract and derived/child contracts

1.5 Functions

1. View functions can read state, cannot modify state

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

2. Pure functions - cannot modify state, cannot read state

solidity
function retrieve() public pure returns(uint256) {
    return 7;
}

1.6 Arrays

Solidity arrays are zero-indexed.

solidity
datatype[] arrayName;

uint256[] listOfFavoriteNumbers;

1.7 Struct

custom type combining multiple datatypes

solidity
struct Person {
    string name;
    uint age;
}

1.8 Data locations

data location specifies where a variable lives and how long it exists in the EVM.

temporary data = data only exists while function executes
persistent data = data remains on blockchain

Note: non-primitive data types, would give compile time error if defined without data location
primitive data types can be defined without explicit data location because compiler knows efficient handling

Gas ordering (cheapest to expensive):-
calldata < memory << storage

Solidity supports 6 locations:

1. calldata - temporary read only data location used mainly for external function inputs
cheap gas, input focused, immutable, temporary
used for function parameters when read only stuff needs to happen in functions.
calldata is immutable

solidity
function addPerson(string calldata _name) public {
	// functionality
}

2. memory - is temporary read write storage during function execution
temporary, mutable, destroyed after function ends. used when temporary computation needed

solidity
string memory name = "Pat";

3. storage - persistent blockchain storage, mutable, permanent, expensive
writes are expensive, because it changes blockchain state permenantly

solidity
contract MyContract {
    uint256 favoriteNumber;
}

4. stack

5. code

6. logs

1.9 Mappings

key : value data structure

solidity
mapping(keyType => valueType) visibility name;

mapping(string => uint256) public nameToFavoriteNumber;

gas fees insanely cheap, time complexity is O(1)

1.10 Contract deployment

publishing compiled smart contract bytecode onto a blockchain. after deploying contract becomes live, gets unique address, callable by users/contracts, users can interact via transactions/calls.

sepolia = Ethereum public test network, stable good tooling etherscan support.
deployment requires gas, even on testnet, gas is still required

always deploy to a testnet to check if deployment works, functions behave correctly, gas usage. if the contract has bugs, fund loss/exploit/locked funds/irreversible mistakes

1.10.1 contract address

each deployed contract gets unique permanent address
contract address used for function calls, UI integration, explorers, audits

1.10.2 Block Explorer

sepolia etherscan is a blockchain explorer, you can view this blockchain data publicly:
a. transaction data (transaction hash, status, block number, timestamp)
b. account data (sender, contract address, gas fees)
c. contract data (bytecode, input data, interaction history)

2.0 EVM (Ethereum Virtual Machine)

EVM = issa decentralized computational engine that executes smart contracts, kinda like a blockchain computer/runtime
its job is to execute smart contract bytecode/manage storage/track gas usage/ensure deterministic execution

why is it named virtual machine = because it behaves like a software computer running on many physical nodes
each node runs same computation

EVM inputs a bytecode, transaction data, current blockchain state
outputs state changes, logs, return values

EVM compatible chains = what blockchains can understand and run Ethereum smart contracts
Note!: compatible ≠ identical, differences exist in gas fees, speed block time, consensus, bridges, supported opcodes

2.1 Smart contract

a program stored on blockchain that automatically enforces rules when someone interacts with it. the program runs on blockchain instead of AWS/server. The code is public too and state is shared by everyone. execution is deterministic and once deployed, modifying the same code is impossible.

smart contracts doesn’t runs continuously, they are passive, they only execute when someone sends transaction, another contract calls them (they act like API endpoints)

A contract is similar to a class in object-oriented programming.

solidity
contract MyContract {

}
VisibilityAccess
publiceveryone
privatecurrent contract
internalcontract + children
externaloutside only

3.0 Coding examples (example pattern discussed in the lecture)

until now user manually deployed and interacted with a single contract
now we introduce storage factory, it changes infrastructure from single-contract interaction to contract orchestration

core idea: smart contracts can deploy and control other smart contracts

composability = ability of smart contract to interact with other smart contracts permissionlessly

recommended practice = 1 file = 1 contract, you can create multiple contracts too within a file

each contract is a type in Solidity. it stores a reference/address to a deployed contract

solidity
SimpleStorage public simpleStorage;

this line however didnt deployed anything, it only declares a variable

3.1 New keyword

solidity
simpleStorage = new SimpleStorage();

new means deploy a fresh contract instance on blockchain
so this line causes deployment transaction, EVM executes constructor, blockchain assigns new address

some conventions:
1. contract/type names usually PascalCase
SimpleStorage, StorageFactory, …
2. variable names usually camelCase
simpleStorage, favoriteNumber, userBalance, ….

3.2 import statements

solidity
import "./SimpleStorage.sol"; //full import
import { SimpleStorage } from "./SimpleStorage.sol"; //named import
import { SimpleStorage, SimpleStorage1 } from "./SimpleStorage.sol"; //multiple named imports

3.3 ABI (Application Binary interface)

standardized interface describing how to interact with deployed smart contract. ABI specifies:
a. funciton names
b. parameters
c. return values
d. data encoding structure

imagine a vending machine, you dont need to know how it works, you need to know which buttons exist, what input each expects, what comes back, ABI is basically that information for a smart contract

json
[
  {
    "name": "transfer",
    "inputs": [
      {"type":"address"},
      {"type":"uint256"}
    ]
  }
]

3.4 Inheritance

solidity
import {SimpleStorage} from "./SimpleStorage.sol";

contract AddFiveStorage is SimpleStorage {
	// contract definition
}

is keyword establishes parent-child inheritance

child contract gets all accessible parent members: functions, variables, methods
child can define additional functionality

3.4.1 override keyword

if child attempts to define a parent class function with name name, compile time error
must use override keyword to ensure that function overloading is going to happen

solidity
function store(uint256 _newFavNumber) public override {
	//code
}

3.4.2 virtual keyword

for a parent to allow overriding a function, virtual keyword should be used

solidity
function store(uint256 favNumber) public virtual {
	//code
}

4.0 Example code #2

Build a smart contract where users fund money
and owner can withdraw collected funds

4.0.1 payable function

payable function can receive blockchain currency

solidity
function fund() public payable

4.0.1.1 msg.value

solidity
balances[msg.sender] += msg.value;

msg.value = amount of native currency sent with current transaction, expressed in Wei (smallest ETH unit)

4.0.2 require keyword

checks a condition before execution continues

solidity
require(condition, "error message");

require(msg.value > 1 ether, "Didn't send enough ETH");

4.0.3 revert keyword

if condition is false, transaction reverts
undoes all state changes, mark transaction as failed, return unused gas

on revert, used gas is not refunded after revert

gas limit = maximum gas allowed for transaction

4.0.4 Transaction Fields

every transaction includes:
a. nonce - account transaction count
b. gas price - price per gas unit
c. gas limit - max gas allowed
d. to - recipient address
e. value - amount of crypto sent
f. data - extra payload
g. v,r,s - signature fields

decentralized oracle network
hybrid smart contracts = uses both on chain and off chain data

few chainlink products:
a. data feeds - provides trusted price data
b. VRF - verifiable random function
c. Automation (keepers) - chainlink nodes monitor conditions and auto-trigger actions

4.2 ETH → USD conversion and interfaces

need to convert ETH into USD instead of ETH because ETH price constantly changes
use chainlink price feed to talk to any deployed contract
contract address → where contract lives on blockchain
ABI → how to communicate with it

4.3 Interface

ABI has no compile time safety, like tells stuff but could crash the instance, horrible readability, ABI doesnt express the actual behavior in Solidity syntax.

interface is used when your contract wants to talk to another already deployed contract
you dont need to know contract full code, you only need to know what function does, inputs, outputs

solidity
interface IERC20 {
    function balanceOf(address user)
        external
        view
        returns(uint256);
}
text
ABI = {
  "name": "balanceOf",
  "inputs": [{"type":"address"}],
  "outputs": [{"type":"uint256"}]
}

Solidity has no floating point nubmers → everything uses integers

4.4 safemath

before solana 0.8, devs used safemath to prevent overflow
starting from Solidity 0.8, overflow/underflow checks became built in
when number exceeds overflow and underflow

solidity
for (initialization; condition; increment) {
    // code
}

for (uint256 funderIndex = 0; funderIndex < funders.length; funderIndex++) {
    address funder = funders[funderIndex];
    addressToAmountFunded[funder] = 0;
}

4.5 sending ETH in Solidity

three ways to send ETH

1. transfer
sends ETH, automatically reverts on failure
only forwards 2300 gas

solidity
payable(msg.sender).transfer(amount);

2. send
sends ETH, forwards only 2300 gas, does not auto revert
returns bool

solidity
bool success = payable(msg.sender).send(amount);
require(success, "Send failed");

3. call
sends ETH, forwards all remaining gas by default
returns success boolean, can also call arbitrary functions

solidity
(bool success, ) = payable(msg.sender).call{value: amount}("");
require(success, "Call failed");

4.6 Constructor

special kind of function that is executed once only during deployment
deployment = putting contract on blockchain as a permanent smart contract

solidity
constructor() {}

4.7 Modifiers

reusable pre/post logic attached to functions

solidity
modifier modifierName {
    // logic
    _;
}

modifier onlyOwner {
    _;
    require(msg.sender == owner);
}

//then call over here:-
function withdraw(uint amount) public onlyOwner {
    // withdraw logic
}

4.8 constant keyword

regular state variables are stored in storage
storage is expensive because data is stored on blockchain
constant is used when value is known at compile time
value can never change → no storage slot used, value gets embedded directly into bytecode & cheaper reads/lower deployment gas

4.9 immutable keyword

used when value is not known at compile time
but gets assigned once during deployment

solidity
address public immutable i_owner;

constructor() {
    i_owner = msg.sender;
}

saves gas, value cannot change after constructor and is cheaper than normal storage variable

4.10 Gas Optimizations

error handling can also affect gas cost, require(…, “message”) is more expensive because strings cost storage/bytecode space
error message must be stored in contract bytecode, more bytes = higher deployment gas, longer strings = even more expensive

custom errors introduced in Solidity 0.8.4, more gas efficient, defines a reusable error type

solidity
error NotOwner();

lower gas, cleaner code, can carry params, better for large contracts

4.11 Receive function

triggered when, ETH sent to contract.
or msg.data is empty

requirements: must be external, payable, takes no arguments, returns nothing

4.12 fallback function

triggered when function being called doesn’t exist
or ETH sent with non-empty data
or receive() absent and ETH arrives

solidity
contract FallbackExample {
    uint256 public result;

    receive() external payable {
        result = 1;
    }

    fallback() external payable {
        result = 2;
    }
}