Lecture 2. Introduction: Ethereum and beyond.

Resources
Diagram codes
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

subgraph users ["Users"]
direction TB
A("Alice")
B("Bob")
N33("Node 3")
end

subgraph state ["Ethereum state (abstractly)"]
ac1("... ...")
ac2("... ...")
s2{{"... ..."}}
s3{{... ...}}
sc{{"Smart contract with locked ETH. \n (7) locked ETH is slashed if \n nodes build conflicting forks \n\n"}}
end


subgraph nodes ["Validators (stakers)"]
	direction TB
	N1("Node 1")
	N2("Node 2")
	N3("Node 3 \n (2) is added to the validator set\n (4) chosen randomly, according \nto how much ETH Node 3 has staked\n\n")
end
subgraph blocks ["Ethereum blockchain"]
	direction RL
	B0("... ...")
	B1("Block N")
	B2("Block N+1")
	B3("Block N+2")
	B4("Block N+3"):::green
	B4 --> B3-->B2 --> B1 -->  B0
end

state:::blue
users:::white
blocks:::blue
nodes:::orange
N1  
N2  
N33  o-----o|"(1) ETH is locked \n(via tx*)\n\n"| sc

blocks -->|"(6) state updated according to new txs in Block N+3 "| state
A -->|"(3) txs"| nodes
B -->|"(3) txs"| nodes
N33 -->|"(0) tx* (to stake ETH)"| nodes
N3 -->|"(5) - build a valid Block N+3; \n - add it to the longest chain + broaddcast it; \n- receive block reward + tip + MEV fees; \n- burn the base fee. \n\n"| blocks
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

subgraph users ["Users"]
direction TB
A("Alice")
B("Bob")
N33("Node 3")
end

subgraph state ["Ethereum state (abstractly)"]
ac1("... ...")
ac2("... ...")
s2{{"... ..."}}
s3{{... ...}}
sc{{"Smart contract with locked ETH. \n (7) locked ETH is slashed if \n nodes build conflicting forks \n\n"}}
end


subgraph nodes ["Validators (stakers)"]
	direction TB
	N1("Node 1")
	N2("Node 2")
	N3("Node 3 \n (2) is added to the validator set\n (4) chosen randomly, according \nto how much ETH Node 3 has staked\n\n")
end
subgraph blocks ["Ethereum blockchain"]
	direction RL
	B0("... ...")
	B1("Block N")
	B2("Block N+1")
	B3("Block N+2")
	B4("Block N+3"):::green
	B4 --> B3-->B2 --> B1 -->  B0
end

state:::blue
users:::white
blocks:::blue
nodes:::orange
N1  
N2  
N33  o-----o|"(1) ETH is locked \n(via tx*)\n\n"| sc

blocks -->|"(6) state updated according to new txs in Block N+3 "| state
A -->|"(3) txs"| nodes
B -->|"(3) txs"| nodes
N33 -->|"(0) tx* (to stake ETH)"| nodes
N3 -->|"(5) - build a valid Block N+3; \n - add it to the longest chain + broaddcast it; \n- receive block reward + tip + MEV fees; \n- burn the base fee. \n\n"| blocks
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

subgraph O["Decentralized oracle"]
OP1("Oracle \n provider 1\n\n")
OP2("Oracle \n provider 2\n\n")
OP3("Oracle \n provider 3\n\n")
end
TradFi:::white -->|ETH price| O:::red -->|ETH price| A{{Aave}}:::blue
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

subgraph O["Decentralized oracle"]
OP1("Oracle \n provider 1\n\n")
OP2("Oracle \n provider 2\n\n")
OP3("Oracle \n provider 3\n\n")
end
TradFi:::white -->|ETH price| O:::red -->|ETH price| A{{Aave}}:::blue
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

TradFi:::white -->|ETH price| O(Oracle):::red -->|ETH price| A{{Aave}}:::blue
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

TradFi:::white -->|ETH price| O(Oracle):::red -->|ETH price| A{{Aave}}:::blue
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("<b>Alice</b>\n[seeks leverage]\n (0) assets: 10 ETH \n(9) assets: 18 ETH + debt: 12000 USDC\n\n")
aave{{"AAVE money market = lending platform \n - loan-to-value (LTV) ratio = 82.5% \n - ETH price = 15000 USDC% \n (3) balance: 10 ETH, 15000 USDC \n(4) Alice asked for 12000 USDC loan \n\n"}}:::blue
B("<b>Bob</b>\n[seeks yield on USDC]\n\n")
A -->|"(1) 10 ETH"| aave
B -->|"(2) 15000 USDC"| aave
aave -->|"(5)  since 12000 < 82.5%*15000,\nloan 12000 USDC, \nfor 2% APR!\n\n"| A
aave -->|"(6) pay 1% (half) of Alice's APR,\n giving Bob yield on his USDC\n\n"| B
aave -->|"(7) earn 1% (half) of Alice's APR\n\n"| aave
A-->|"(8) swap 12000 USDC for 8 ETH"|u{{"Uniswap"}}:::blue
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("<b>Alice</b>\n[seeks leverage]\n (0) assets: 10 ETH \n(9) assets: 18 ETH + debt: 12000 USDC\n\n")
aave{{"AAVE money market = lending platform \n - loan-to-value (LTV) ratio = 82.5% \n - ETH price = 15000 USDC% \n (3) balance: 10 ETH, 15000 USDC \n(4) Alice asked for 12000 USDC loan \n\n"}}:::blue
B("<b>Bob</b>\n[seeks yield on USDC]\n\n")
A -->|"(1) 10 ETH"| aave
B -->|"(2) 15000 USDC"| aave
aave -->|"(5)  since 12000 < 82.5%*15000,\nloan 12000 USDC, \nfor 2% APR!\n\n"| A
aave -->|"(6) pay 1% (half) of Alice's APR,\n giving Bob yield on his USDC\n\n"| B
aave -->|"(7) earn 1% (half) of Alice's APR\n\n"| aave
A-->|"(8) swap 12000 USDC for 8 ETH"|u{{"Uniswap"}}:::blue

flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A(Alice) -->|tx| RO
B(Bob) -->|tx| RO
RO[["Rollup operator\n- proccesses all txs\n - produces short proof π\n\n"]]:::orange
RO -->|"txs summary \n proof π\n\n"| N("Ethereum nodes \n(miners/validtors) \n- verify the proof\n\n") -->|txs summary \n proof π\n\n|RSC{{Rollup smart contract}}:::orange
subgraph es[Ethereum state]
RSC
end
es:::blue
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A(Alice) -->|tx| RO
B(Bob) -->|tx| RO
RO[["Rollup operator\n- proccesses all txs\n - produces short proof π\n\n"]]:::orange
RO -->|"txs summary \n proof π\n\n"| N("Ethereum nodes \n(miners/validtors) \n- verify the proof\n\n") -->|txs summary \n proof π\n\n|RSC{{Rollup smart contract}}:::orange
subgraph es[Ethereum state]
RSC
end
es:::blue
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("<b>Alice</b>\n[trader]\n\n") -->|"(3) 100 USDC \ntrade starts\n\n"| liq_pool{{"<b>ETH-USDC liquidity pool, 1% fee</b>\n[smart contract] \n(0) balance: 0 \n (2) upd balance: 1500 USDC, 1 ETH \n (6) upd balance: 1599 USDC, 0.938 ETH \n• key point: 1500 x 1 = 1599 x 0.938 \n\n\n"}}
B("<b>Bob</b>\n[liquidity provider =\n= market maker]\n\n"):::orange -->|"(1) 1500 USDC + 1 ETH \n deposit\n\n"| liq_pool:::blue
liq_pool -->|"(4) 1 USDC \n as a fee\n\n"| B
liq_pool -->|"(5) 0.062 ETH \n trade finished \n\n"| A
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("<b>Alice</b>\n[trader]\n\n") -->|"(3) 100 USDC \ntrade starts\n\n"| liq_pool{{"<b>ETH-USDC liquidity pool, 1% fee</b>\n[smart contract] \n(0) balance: 0 \n (2) upd balance: 1500 USDC, 1 ETH \n (6) upd balance: 1599 USDC, 0.938 ETH \n• key point: 1500 x 1 = 1599 x 0.938 \n\n\n"}}
B("<b>Bob</b>\n[liquidity provider =\n= market maker]\n\n"):::orange -->|"(1) 1500 USDC + 1 ETH \n deposit\n\n"| liq_pool:::blue
liq_pool -->|"(4) 1 USDC \n as a fee\n\n"| B
liq_pool -->|"(5) 0.062 ETH \n trade finished \n\n"| A
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("Alice")
B("Bob")
C("Carol")

A --> nodes
A --> RC[["Rollup Operator"]]:::orange
B --> nodes
C -->|txs \n usual fees \n MEV fees\n\n| nodes

nodes ==>|update| state

subgraph nodes ["Ethereum network"]
N1("Node 1")
N2("Node 2")
N3("Node 3")
end



subgraph state ["Ethereum State = dapps \n\n\n"]
RP("Rollup contract"):::orange
NFT("NFTs")
DAO("DAOs")
subgraph defi ["DeFi"]
DEX("DEXs")
MM("Lending protocols")
Stablecoins("Stablecoins")
end
defi:::red
end

RC -->|"txs summary \n zk proof \n (via eth nodes) \n\n"| RP
Oracles --> MM
Oracles --> Stablecoins
TradFi:::white --> Oracles

nodes:::green
state:::blue
flowchart LR
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px
classDef white fill:#ffffff,stroke:#000,stroke-width:2px
classDef orange fill:#FDDCBE,stroke:#000,stroke-width:2px

A("Alice")
B("Bob")
C("Carol")

A --> nodes
A --> RC[["Rollup Operator"]]:::orange
B --> nodes
C -->|txs \n usual fees \n MEV fees\n\n| nodes

nodes ==>|update| state

subgraph nodes ["Ethereum network"]
N1("Node 1")
N2("Node 2")
N3("Node 3")
end



subgraph state ["Ethereum State = dapps \n\n\n"]
RP("Rollup contract"):::orange
NFT("NFTs")
DAO("DAOs")
subgraph defi ["DeFi"]
DEX("DEXs")
MM("Lending protocols")
Stablecoins("Stablecoins")
end
defi:::red
end

RC -->|"txs summary \n zk proof \n (via eth nodes) \n\n"| RP
Oracles --> MM
Oracles --> Stablecoins
TradFi:::white --> Oracles

nodes:::green
state:::blue
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

S1(State 1) -->|"tx1"| S2(State 2) -->|"tx2"| S3(State 3) 
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

S1(State 1) -->|"tx1"| S2(State 2) -->|"tx2"| S3(State 3) 
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

A(Alice) -->|2 ETH| R{{<u>Smart contract</u> <br> Code: if X ETH received, <br> send X/2 ETH to Bob and \n send X/2 ETH to Carol \n \n}} -->|1 ETH| C(Carol) & B(Bob)
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

A(Alice) -->|2 ETH| R{{<u>Smart contract</u> <br> Code: if X ETH received, <br> send X/2 ETH to Bob and \n send X/2 ETH to Carol \n \n}} -->|1 ETH| C(Carol) & B(Bob)
Example of a smart contract, which splits funds
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

EOA("<u>Regular account</u> (controlled by private key) \n(or Externally Owned Account = EOA)\n - Public address \n  - Private key \n - Balance  \n - Nonce (number of txs)\n\n\n") 
CA{{"<u>Contract account</u> (controlled by code) \n(or CA = internal account = smart contract = DAPP)\n - Public address \n - Code + storage \n - Balance \n  - Nonce (# of contracts created by the creator)\n\n\n"}}
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

EOA("<u>Regular account</u> (controlled by private key) \n(or Externally Owned Account = EOA)\n - Public address \n  - Private key \n - Balance  \n - Nonce (number of txs)\n\n\n") 
CA{{"<u>Contract account</u> (controlled by code) \n(or CA = internal account = smart contract = DAPP)\n - Public address \n - Code + storage \n - Balance \n  - Nonce (# of contracts created by the creator)\n\n\n"}}
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
A(Alice) -->|"(1) swap 1500 USDC to ETH"| SC1{{"Smart Contract 1: \n Exchange aggregator \n \n"}} 
subgraph  
SC2{{"Smart Contract 2: \n Exchange X \n \n"}} 
SC3{{"Smart Contract 3: \n Exchange Y \n \n"}} 
SC4{{"Smart Contract 4: \n Exchange Z \n \n"}} 
end
SC1 <-->|"(2a) swap 500 USDC \n to 0.5 ETH \n\n"| SC2
SC1 <-->|"(2b) swap 300 USDC \n to 0.32 ETH\n\n"| SC3
SC1 <-->|"(2c) swap 600 USDC \nto 0.6 ETH\n\n"| SC4
SC1 -->|"(3) send 1.42 ETH"| A
flowchart TD
classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
A(Alice) -->|"(1) swap 1500 USDC to ETH"| SC1{{"Smart Contract 1: \n Exchange aggregator \n \n"}} 
subgraph  
SC2{{"Smart Contract 2: \n Exchange X \n \n"}} 
SC3{{"Smart Contract 3: \n Exchange Y \n \n"}} 
SC4{{"Smart Contract 4: \n Exchange Z \n \n"}} 
end
SC1 <-->|"(2a) swap 500 USDC \n to 0.5 ETH \n\n"| SC2
SC1 <-->|"(2b) swap 300 USDC \n to 0.32 ETH\n\n"| SC3
SC1 <-->|"(2c) swap 600 USDC \nto 0.6 ETH\n\n"| SC4
SC1 -->|"(3) send 1.42 ETH"| A
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

A(Alice) --->|"Transaction"| SC1{{"Smart contract"}} --->|"Internal transaction"| SC2{{"Smart contract 2"}}
flowchart LR

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px

A(Alice) --->|"Transaction"| SC1{{"Smart contract"}} --->|"Internal transaction"| SC2{{"Smart contract 2"}}
flowchart TD

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px


n1(Alice):::blue --->|"gasLimit·gasPrice GWEI\n is locked to txEscrow\n\n"| n2(Tx initiation \n <b>remainingGas = gasLimit\n\n) --> n3(<b>remainingGas</b> = 0 or insufficient?)
n3 -->|yes| n4("Tx failed! \n But still included in the blockchain\n and gasLimit·gasPrice GWEI paid as fee\n\n"):::red
n3 -->|no| n5("Execute next operation \n <b>remainingGas = remainingGas - opCost \n\n") --> n6("Are there more operations?")
n6-->|yes| n3
n6-->|no| n7("Tx successful! State changes, and\n remainingGas·gasPrice GWEI is refunded to user\n\n"):::green
 
flowchart TD

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px


n1(Alice):::blue --->|"gasLimit·gasPrice GWEI\n is locked to txEscrow\n\n"| n2(Tx initiation \n <b>remainingGas = gasLimit\n\n) --> n3(<b>remainingGas</b> = 0 or insufficient?)
n3 -->|yes| n4("Tx failed! \n But still included in the blockchain\n and gasLimit·gasPrice GWEI paid as fee\n\n"):::red
n3 -->|no| n5("Execute next operation \n <b>remainingGas = remainingGas - opCost \n\n") --> n6("Are there more operations?")
n6-->|yes| n3
n6-->|no| n7("Tx successful! State changes, and\n remainingGas·gasPrice GWEI is refunded to user\n\n"):::green
 
flowchart TD

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

S1("Self-custody?") --->|no| N1((TradFi)):::red  
S1 -->|yes|S2(Transaction censoring possible?)-->|no|S3(Protocol execution censoring?)--->|no|N2((DeFi)):::green
S2 --->|yes|N3((TradFi intermediary, \n DeFi settlement\n\n)):::blue
S3 -->|yes|N4((DeFi with \nadmin keys\n\n)):::blue
flowchart TD

classDef default fill:#F8ECFB, stroke:#000, stroke-width:2px, text-align:center
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef red fill:#FFA69D,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

S1("Self-custody?") --->|no| N1((TradFi)):::red  
S1 -->|yes|S2(Transaction censoring possible?)-->|no|S3(Protocol execution censoring?)--->|no|N2((DeFi)):::green
S2 --->|yes|N3((TradFi intermediary, \n DeFi settlement\n\n)):::blue
S3 -->|yes|N4((DeFi with \nadmin keys\n\n)):::blue


flowchart LR

classDef default fill:#FAF2FF, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

A(Alice) -->|send tx| R[[Rollup Coordinator</u> <br> - processes all txs <br> - produces short proof π    \n\n ]]:::blue
B(Bob) -->|send tx| R
C(Carol) -->|send tx| R
R:::red --->|txs summary + π| N1(Node 1 <br> - verifies π \n - records tx summary+π\n into rollup smart contract \n\n) & N2(Node 2 <br> - verifies π \n- records tx summary+π\n into rollup smart contract \n\n) & N3(Node 3 <br> - verifies π \n - records tx summary+π\n into rollup smart contract \n\n)


flowchart LR

classDef default fill:#FAF2FF, stroke:#000, stroke-width:2px, text-align:left
classDef green fill:#C5F1AB,stroke:#000,stroke-width:2px
classDef blue fill:#DAF4FF,stroke:#000,stroke-width:2px

A(Alice) -->|send tx| R[[Rollup Coordinator</u> <br> - processes all txs <br> - produces short proof π    \n\n ]]:::blue
B(Bob) -->|send tx| R
C(Carol) -->|send tx| R
R:::red --->|txs summary + π| N1(Node 1 <br> - verifies π \n - records tx summary+π\n into rollup smart contract \n\n) & N2(Node 2 <br> - verifies π \n- records tx summary+π\n into rollup smart contract \n\n) & N3(Node 3 <br> - verifies π \n - records tx summary+π\n into rollup smart contract \n\n)
HW:
  • Basic txs on Ethereum using Goerli testnet:
    1. Go to https://metamask.io/ and get the Metamask Browser extension. Set up a new account and connect to Goerli testnet. Backup the mnemonic phrase of your wallet. (see also the next exercise for this) Go to Goerli Faucet and get some Goerli testnet Ether (gETH).
    2. If you are currently managing Mainnet funds with Metamask, make sure NOT to use the same mnemonic seed for your testnet transactions. In doing so you will put your ETH and tokens at risk.

    3. Create a second account with metamask. Transfer 0.01 gETH from your first account to your second account. Check the transaction details on Goerli Etherscan. Transfer the balance from your second account, back to your first account.
  • Understand Metamask security (read below + google more if needed)
  • Overall what you have is a [metamask wallet] (or [metamask vault]). [metamask wallet] actually consists of many Ethereum accounts: [Ethereum Account 1, Ethereum Account 2 , Ethereum Account 3, ...]. Each Ethereum Account N consists of public and private key: publick address is the thing you may tell everyone, private is the one you keep to sign transactions. Let me summarize in a diagram:

    Overall structure: [metamask wallet] =

    = [ Eth Acc 1 (pub_key1, priv_key1), Eth Acc 2 (pub_key1, priv_key1), Eth Acc 3 (pub_key1, priv_key1), .... ]

    Security structure: 1) [12 word seed phrase] → [metamask wallet] (yes, these 12 wordss contain private keys from all of your metamask Ethereum accounts)

    2) [your metamask password + your google chrome] → [metamask wallet] (yes, your metamask password will not work on any other browser. Re-installation of a brwoser will also delete your metamask. This is why 12 word seed phrase is so important)

    3) [priv_key_from_acc_N] → [Eth Acc N] (thus, in order to back up one Eth address you can only backup one private key, instead of backing up the whole 12 words that give access to all Eth addresses in your metamask wallet)

  • Understand the mathematics of how uniswap v2 works, i.e. understand how the formula x*y=k determines the price. (you can either google or use how-to-defi book from resources (page 87) and then solidify your understanding by reading this blogpost)
  • After this, solve the following problem: Suppose there is 100 ETH and 200k USDC (stablecoin representing USD) in a pool in Uniswap v2 with 0.3% fee. How much does it cost a user to buy 5 ETH from that pool?

Blockchain, not Bitcoin

Question: what else can be built on top of Bitcoin?

There were many developments, but not as promising (e.g., colored coins). The scripting language (which encodes spending conditions on UTXOs) of Bitcoin is not expressive enough. See this video for more about scripting language, and here are the basics of Bitcoin txs.

An idea came about in 2012-2013 that blockchain itself is a more important invention than Bitcoin, and maybe there could be things built on top of a blockchain, not Bitcoin.

A better question: what else can be built on top of a blockchain protocol? Apart from another cryptocurrency with different parameters, like Litecoin.

Idea: theoretically, we should be able to record “arbitrary states” and perform arbitrary computations via “txs = state transitions” on a blockchain.

🔶
The key question: how to best implement the state transition model?
image
🔷
Stellar answer: use smart contracts = digital vending machines. Regular users can: (1) send txs to each other (as before); (2) deploy smart contracts (onto nodes’ hard drive) that are governed by code; (3) interact with smart contracts.

This idea was pioneered by Nick Szabo [1, 2], and implemented in Ethereum by Vitalik Buterin.

image

Quick intro to Ethereum

Regular accounts and contract accounts are the 2 types of accounts on Ethereum:

image

Public address = 40 hexadecimals Example: 0xd8da6bf26964af9d7eed9e03e53415d37aa96045

This is one of the public addresses of Vitalik Buterin, creator of ethereum. Addresses can be conviniently investigated using etherscan.

Rmk: in hexadecimal notation we use 0-9,A,B,C,D,E,F: 16 symbols; 1 hexadecimal = 4 bits = 2^4 = 16 different things; (1 byte = 2 hexadecimals = 8 bits)

Public address is derived from the public key: you get a public address for your account by taking the last 20 bytes of the Keccak-256 hash of the public key and adding 0x to the beginning.

Transactions

Transactions (external transactions) (or “messages”) come from regular accounts (EOA), initiated by signatures with private key. 3 types:

  • EOA to EOA (ETH transfer)
  • EOA to 0 (contract deployment)
  • EOA to CA (ETH transfer, contract execution = calling functions)

Transaction contains:

  • ETH sent — changes balance of ETH
  • Data — directs the contract deployment / execution

Internal transactions (internal calls) from CA are always triggered by code. Any sequence of internal txs has to be initiated at first by an external tx.

image

Composibility idea: smart contracts can talk to each other! They can quote prices to each other, they can request things, etc. Example below shows how an aggregator on ethereum (e.g. https://matcha.xyz/) directs 1 trade to various decentralized excghanges (DEXs) to achieve the best price.

image

EVM (Ethereum Virtual Machine) Run by nodes, is needed to compute all the state transitions.

Gas

  • Halting problem: In 1936, Alan Turing has shown that a (turing) machine cannot tell if a script will halt or run forever, before execution.
  • ⇒ Infinite loops or resource intensive scripts are a potential attack vector

  • Bitcoin and Ethereum deal with this problem in different ways:
    • Bitcoin Script is a deliberately limited scripting language.
    • Ethereum has a Turing complete instruction set. It charges a fee for each minimal computation step (gas).
  • All EVM operation sconsumes a pre-defined amount of gas. (Addition → 3 gas units, Multiplication → 5 gas units, Store 256 bits → 20k gas units)
  • Every transaction has a user-specified gas limit, i.e. the maximum number of gas units that can be triggered by this transaction.
  • Simple “send ETH” txs require 21000 gas units. More complicated contract executions vary.

  • Every transaction has a certain gas price = “price of gwei-per-gas” that the sender is willing to pay.
  • Rmk: 10^9 gwei = eth; gwei = 10^9 wei.

  • Execution of tx based on gasLimit and gasPrice is shown below. The upshot is that miners get paid for every operation they perform (even if the tx is invalid!)
  • image

Fees

  • Protect Ethereum from DoS attacks and infinite loops in the code
  • Give a great mechanism to determine which tx to prioritize
  • [mechanics before eip1559] first-price auction, everything goes to miners
  • [mechanics after eip1559] base fee (in gwei-per-gas) is dynamically quoted to you by Ethereum network = the gas price under which ethereum will include your tx. This fee is burnt. Miners/validators receive a small tip + MEV (see later)
  • More details:
    • priority fee (= tip) is set by the user to give the miner an incentive to include the transaction in the block. Miner receives the priority fees of all included transactions. It is usually equal to ~2 gwei.
    • when blocks are full (30mil gas), the system reverts to first-price auction via priority fee & increases base fee exponentially. When blocks are empty (<15mil gas), the base fee decreases.
    • max fee is set by the user and corresponds to the maximum gwei-per-gas price. Transaction remains pending if baseFee > maxFee.
    • refund = max (0, maxFee − (baseFee + maxPriorityFee)) is refunded to the user after transaction execution.
    • More in great video of Tim Roughgarden on eip1559
  • Essential tools for dertermining fees (usually these are automatically set by your wallet though):

Ethereum ecosystem

image

Key point:

🔷
Ethereum programs money & business logic ⇒ programs incentives ⇒ ⇒ programs human coordination

Example of a smart contracts on Ethereum: a different currency, ERC-20 token

ERC20 token
variables: - name - symbol - totalSupply - balance(address => int)
functions: - totalSupply() - balanceOf(address) - transferTo(address, int)
constructor: - name = … - symbol = … - totalSupply = … - balance[addr_Alice] = … - balance[addr_Bob] = …

Decentralized Finance (DeFi)

DeFi = open, permissionless, and highly interoperable financial infrastructure built on a public smart contract platform.

DeFi primitives = the most important DeFi protocols: (for links and resources see the topics page)

  • DEXs (e.g. uniswap)
    • Centralized exchanges use the “order book” design for trading
    • Decentralized exchanges, restricted by blockchain constraints, predominantly use the AMM (automated market maker) design:
    • image

      On the left you see (1)-(6) steps on how uniswap works.

      Key point is that the product of two quantities doesn’t change after the trade: 1550 \cdot 1 = 1599 \cdot 0.938

    • Order book design becomes feasible again on L2 (see scaling discussion below)
  • Money markets (e.g. aave, compound)
  • See the diagram below for the step-by-step description.

    VERY IMPORTANT addition to the diagram: if Alice’s LTV spikes to >85%, she get’s liquidated: her ETH is sold to liquidators (usually bots that monitor this stuff) for 5% discount, and the loan is cancelled.

    image
  • Oracles (e.g. chainlink)
  • How does AAVE know the price of ETH? It can look at uniswap, but in practice it uses an oracle.

    image

    The oracle problem: in this architeccture, the decentralized protocol (aave) relies on a centralized source coming from TradFi.

    ⇒ need to decentralized oracle. Most popular solution: chainlink

    image
  • Stablecoins
    1. It is an ERC-20 token that is pegged to 1 dollar.

      The pegging mechanism is the heart of the stablecoin. Three types:

    2. Fiat-backed: USDC, USDT […]
    3. Crypto-backed: DAI, LUSD, RAI (this one is free-floar, i.e. pegged only loosely) […]
    4. Algorithmic: FRAX, UST (collapsed) […]

Many of these projects / protocols have their own tokens.

  1. Tokens carry governance rights (this benefits holders AND the protocol)
  2. Sometimes have value accrual mechanisms (e.g. fees directed to holders)
  3. Have a speculative premium (⇒ ability to “invest into projects”; this matters a lot)
  4. Are used to incentivize participants (e.g. COMP), supercharging network effects of Web 3 projects.

Rmk. It is important to acknowledge that cryptocurrencies / tokens are a good form of coordination when used as a reward / value accrual / coordination mechanism, but not as a means of voting power, because of bribery attacks.

Key reason for a token — decentralization of the protocol into a DAO. The mechanics of it are still very much evolving. (e.g. how uniswap retroactively rewarded users with tokens, as if uber would airdrop their stocks to all of their drivers and passengers, in order to achieve a shared ownership of the protocol. This is hard to repeat though, because of sybil attacks.)

Quick digression into DAOs. DAOs are:

  • multi-sigs
  • bigger decentralized capital formations (e.g. molochDao)
  • decentralized organizations that govern DeFi projects (makerdao, aave, etc), require token
  • token/nft-gated communities
  • etc

Traction of DeFi:

Key gamechangers for why DeFi >> TradFi:

  • Automation & programmability [logic of financial contracts is enforced by Ethereum EVM, as opposed to being enforced by the US laws in TradFi]
  • ⇒ rent-extracting intermediaries removed ⇒ systems are much more efficient

  • Open access for scrutiny
  • ⇒ systems are much more secure than TradFi

  • Decentralization (this is a spectrum! Some protocols are more decentralized than others)
  • ⇒ no collusion

    ⇒ open access for usage (censorship resistance)

    ⇒ self-custody [this is good and bad; good because you own your assets ⇒ less collusion; bad because of security issues, this is currently being solved by things like social recovery of wallets]

    Rmk: DeFi currently is not accessible to all due to high fees, but will be in 2 years — see scaling discussion below.

  • Open-source code ⇒ insanely fast development
  • Composability ⇒ systems interoperate smoothly. Decentralization (⇒no collusion) helps to remove the incentive to verticalize the system.
  • Atomic composability: flash loans
More info:

Spectrum of DeFi:

image

Comparison of TradFi vs DeFi:

TradFi

Permissioned

  • Closed-source system, built on top of centralized databases
  • Needs approval & agreement for third-party to use & build on

Custodial

  • Assets are custodied by licensed third-parties

Centralized trust & governance

  • Single entity responsible for upgrade decisions & admin privileges

Real identity

  • Users register with real identity, e.g., for KYC/AML compliance

DeFi

Permissionless

  • Open-source system; built on top of permissionless blockchains
  • Anyone can use / scrutinize / build on top

Non-custodial

  • Assets are not custodied by a single third-party

Decentralized trust & governance

  • No single entity responsible for upgrade decisions & admin privileges (many exclusions! This is a spectrum)

Pseudonymous

  • Users usually do not provide real identities

What else is interesting in blockchains? (overview of other special topics)

NFTs

NFT = certificate on a blockchain asserting that someone posesses a certain unique digital asset

Key innovation: art is an uncopyable NFT ⇒ can sell art digitally ⇒ 1000x distribution for artists

Why NFTs have value? Counter-question: why do people buy physical art and display it in their houses? Its not because the piece itself has value — the real value is in showing other people that you “bought and have” this original piece. Same thing happens digitally.

Various types of NFTs: [sold/bought on special marketplaces: https://opensea.io/, https://x2y2.io/, https://sudoswap.xyz/]

  • on-chain art:
  • 10k profile picture collections (cryptopunks, bored apes, nouns, and many many more)
    • kind of similar to physical collectibles
    • enable investing into “brand” and “culture”
    • ongoing progress on lisensing IP rights
  • game items
  • ENS
  • music NFTs (example 1, 2)
  • specific financial instruments (e.g. LP certificates in uniswap V3)

Scaling approaches

🔶
Problem 1. All of the above resulted in a huge demand for blockspace ⇒ need to scale blockchains.
  • Bitcoin: ~5 txs / sec Ethereum: ~20 txs / sec Visa: 24000 txs / sec
  • Tx fees on Ethereum fluctuate from 0.5$ to 30$ for a simple transfer.
  • Bottleneck for scalability = not the compute/consensus part, but rather the storage part, namely the growth of state size of Ethereum
  • [Scaling<———>Decentralization] tradeoff (block size debate in Bitcoin)

Payment channels (a strategy for scaling)

  • Uni-directional payment channel description: [Alice] ———[PAYMENT CHANNEL 100$]———> [Bob]
    1. Alice sets up a payment channel with 100$, onchain. HTLC (Hashed TimeLock Contract) logic of the payment channel:
      1. Money can be withdrawn with Alice’s sig, but only 30 days after deployment of the channel
      2. Money can be withdrawn with Alice’s sig AND Bob’s sig at any moment
    2. Alice pays 5$ to Bob for coffee by signing the following tx, offchain!
    3. (“distribute funds: 95$ → Alice, 5$ → Bob”, sigAlicesig_{Alice})

    4. Alice pays another 5$ to Bob by signing the following tx, offchain again:
    5. (“distribute funds: 90$ → Alice, 10$ → Bob”, sigAlicesig_{Alice})

    6. 29 days after the payment channel was initiated, Bob signs the last tx of Alice and gets all the payments by closing the payment channel onchain.
  • Bi-directional payment channel: article, original paper
  • Lightning network

Rollups (the scaling strategy now for Ethereum, 2nd strategy for scaling).

Two kinds:

  • zk rollups (e.g. zk-hermez, zk-sync, starknet)
  • Use SNARKs (or STARKS) to compress computation

    image
    SNARK high-level description: (extremely cool)
    • C: a program that always terminates in ≤B steps x: public input to C w: private input to C (witness)
    • PROVER knows (C, x, w); VERIFIER knows (C, x)
    • PROVER wants to prove to VERIFIER that he knows such w that C(x, w)=1, without sending w
    • PROVER ———[short proof π\pi]———> VERIFIER ⇒ VERIFIER is convinced C(x,w)=1, without knowing w and therefore without actually computing C(x,w) [⇒ this tech is useful for privacy]
    • VERIFIER’s running time for checking π\pi is much less than running the program C [⇒ this tech is useful for scaling]
    zkRollup simplified details:
    • Rollup operator (RO) stores balances of users in Merkle tree
    • RO publishes the Merkle root on Layer 1
    • When Alice sends her tx [A→B, 2ETH], sigAsig_A, and others also send their txs, RO processes txs, updates balances, and publishes (new root + txs summary (without sigs ⇒ short!) + SNARK of the correct transition)
    • Producing SNARK is the hard part ⇒ RO will collect some fees. RO’s SNARK proves [old root] ———(applying valid txs)———>[new root] is correct
    • In more detail: Public input to program C is x = old root + new root + txs summary Private input to program C is w = old account balances + updated account balances + signatures of users Program C(x, w) will process txs: will check signatures and balances, will process according to txs summary, and output 1 if all good or 0 if things don’t add up

    • Nodes simply verify the SNARK

    Remarks:

    • Txs within rollups are easy, thanks to batch settlement on L1
    • Moving funds L1 → L2 and back is more difficult: requires posting more data to L1 ⇒ higher tx fees. This is because tx of type [RC → Alice: 2 ETH] need to be processed directly on L1.
    • Rollup → rollup can be done via L1 (expensive, more secure), or via a direct L2 ←→ L2 bridge (cheaper, less secure)
  • optimistic rollups (e.g. arbitrum, optimism)
  • Rest on economic incentive design: similar to zk-rollups but proofs are not posted at all, but if there is a malicious behavior, fraud proofs are posted by “watchers” and rollup operator is slashed.

Sharding (long-term scaling strategy)

Key idea is that not everyone processes everything, light-clients by default. This is much further down the road for Ethereum, 2-5 years, cryptography heavy.

Rmk 1. Blockchain architecture nowadays:

App layers (DeFi, NFTs, DAOs, etc)
Layer 2 (rollups, scaled systems on top of blockchains)
Layer 1 (consensus / execution / data availability)
Layer 0 (internet communication, social layer)

Rmk 2: scaling is in process, and will enable fundamentally new dapps (payments most importantly, by ETH and USDC) ⇒ more innovation coming on the app layer

Proof of stake

🔶
Problem 2. Mining consumes a lot of energy. (On the order of a middle size country like Argentina)
  • Another direction where Ethereum is innovating: transition from proof-of-work to to proof-of-stake (on Thursday night around 3am), see this intro video for more details).
  • How PoS works, in three lines:
    • miners are now called validators, and they stake eth = lock eth in a certain smart contract
    • leader selection is done randomly (as opposed to according to mining), proportionally to how much validators have staked
    • malicious behavour ⇒ stake is getting slashed
image
  • Main idea: incentive to “not to waste your energy on the wrong fork” is getting substituted with incetive to “not to build on the wrong fork cause my ETH will be shashed
  • The transition will reduce 99% energy consumption of Ethereum ⇒
  • ⇒ no electricity bills for miners (now called validators) ⇒

    ⇒ no need to pay huge block rewards to validators ⇒

    ⇒ massive reduction in inflation (this is costs for a blockchain) ⇒

    ⇒ much more economic efficiency of the blockchain (more security for dollars spent)

    (see 2:10 timestamp in this video for a quick breakdown of benefits of PoS)

  • Ethereum actually becomes the first productive blockchain

Rmk. The actual details of Ethereum PoS are very complex; the above is a drastic simplification. We might dig deeper into PoS later in the course.

Privacy

🔶
Problem 3. People like to have their financial privacy.
  • zk technology allows to process txs while keeping them secret
zk SNARK high-level description: (extremely cool tech)
  • C: a program that always terminates in ≤B steps x: public input to C w: private input to C (witness)
  • PROVER knows (C, x, w); VERIFIER knows (C, x)
  • PROVER wants to prove to VERIFIER that he knows such w that C(x, w)=1, without sending w
  • PROVER ———[short proof π\pi]———> VERIFIER ⇒ VERIFIER is convinced C(x,w)=1, without knowing w and therefore without actually computing C(x,w)
  • VERIFIER’s running time for checking π\pi is much less than running the program C
  • These are being implemented on the L1 level (e.g. zcash), on the L2 level (e.g. aztec), and on the app layer (e.g. tornado cash; use vpn for this)

MEV

🔶
Problem 4. Financialization of blockchains means that certain transactions (arbitrage, liquidations, etc) are worth much more than the others.
  • All user pay fees to get their txs included in blockchain.
  • Certain users pay extra fees to order txs in a particular order (to be first to execute arbitrage, liquidations, frontrunning, etc) – these extra fees are called MEV (Maximal Extractable Value). It is bad because frequently sophisticated users take advantage of retail users [to be clear, there is “fair” MEV (like liquidations and arbitrage), and there is “parasitic” MEV (like frontrunning and sandwiching); these notions are loose though]
  • Ethereum tackles the MEV problem by introducing a separate market for “searchers”: people who bundle transactions, and then participate in auction for these bundles to get included. Flashbots is the current short-term implementation of this = a certain program (”mev boost” to be precise) that validators run alongside their nodes, through which searchers can send their bundles.
  • Proposer-builder separation is the mid-term (2 years) protocol level solution in Ethereum for MEV = essentially embedding this separate economic market into the Ethereum protocol