BC Chapter 4
BC Chapter 4
1
CJ
The Ethereum Virtual Machine (EVM) is a virtual machine that executes code within the Ethereum
blockchain. It serves as the computational engine of the Ethereum network, processing transactions and
running smart contracts.
❖ Key functions of EVM:
• Transaction processing: The EVM verifies and executes transactions submitted to the Ethereum
network.
• Smart contract execution: It runs the code of smart contracts, which are self-executing contracts
with the terms of the agreement directly written into code.
• State transitions: The EVM updates the state of the Ethereum blockchain by modifying the
balances of accounts and the storage of smart contracts.
• Consensus mechanism: The EVM interacts with the consensus mechanism (Proof-of-Work or
Proof-of-Stake) to ensure the security and integrity of the network.
2
CJ
❖ EVM architecture:
The EVM has a stack-based architecture, meaning it uses a stack to store data and execute
instructions. It also has a memory area for temporary storage and a storage area for persistent data.
❖ EVM bytecode:
Smart contracts are written in high-level languages like Solidity. These contracts are then compiled
into EVM bytecode, which is the machine code that the EVM can understand and execute.
❖ EVM blocks:
The EVM operates on a block-based system. Each block contains a set of transactions and smart
contract executions. Once a block is added to the blockchain, its transactions and smart contract
executions are considered final.
❖ EVM execution model:
The EVM executes instructions sequentially, one at a time. Each instruction can modify the stack,
memory, storage, or other parts of the EVM state. The execution of a transaction or smart contract
continues until it reaches the end of the code or encounters an error.
❖ Importance of EVM:
The EVM is a crucial component of the Ethereum network, enabling the creation and execution of
decentralized applications (dApps). It provides a secure and transparent environment for executing
smart contracts, facilitating trustless interactions between parties.
An Ethereum transaction is a digital record of a transfer of value (ether) or the execution of code (smart
contract) on the Ethereum blockchain. It is a fundamental unit of activity on the Ethereum network.
❖ Key fields of an Ethereum transaction:
• Recipient: The address of the account receiving the ether or executing the smart contract.
• Value: The amount of ether being transferred in the transaction.
• Nonce: A unique number assigned to each transaction by the sender. It prevents replay attacks.
• Signature: A cryptographic signature generated by the sender to authenticate the transaction.
• Data: Optional data field used to carry additional information, such as function calls for smart
contracts.
• GasPrice: The amount of ether paid per unit of gas used to execute the transaction.
• GasLimit: The maximum amount of gas allowed for the transaction.
• maxPriorityFeePerGas: The maximum amount of ether paid per unit of gas to incentivize miners
to prioritize the transaction.
• maxFeePerGas: The maximum total fee per unit of gas, including base fee and priority fee.
3
CJ
❖ Transaction process:
1. Transaction creation: A user (sender) creates a transaction by specifying the recipient, value,
nonce, data, and gas parameters.
2. Transaction signing: The sender signs the transaction with their private key to authenticate it.
3. Transaction broadcasting: The signed transaction is broadcast to the Ethereum network.
4. Transaction validation: Nodes on the network verify the transaction's validity, including the
sender's signature and gas price.
5. Transaction inclusion: If the transaction is valid, it is included in a block by a miner.
6. Transaction execution: The EVM executes the transaction, either transferring ether or executing
smart contract code.
7. State update: The Ethereum state is updated to reflect the changes made by the transaction.
❖ Transaction fees:
Ethereum transactions incur fees, paid in ether, to incentivize miners to include transactions in blocks.
These fees are calculated based on the gas price and gas limit set by the sender.
4
CJ
3. Blockchain Layer:
• This layer is the foundation, where all transactions and smart contract code are recorded.
• Blockchain: This is a distributed ledger that stores all transactions and smart contract code in a
secure and transparent manner.
• Consensus Algorithm (POW): This is the mechanism used to validate transactions and add them
to the blockchain. In Ethereum, the Proof-of-Work (POW) algorithm is currently used, although it
is transitioning to a Proof-of-Stake (POS) algorithm.
• Miner: Miners are nodes on the network that solve complex mathematical problems to validate
transactions and add them to the blockchain. In return, they are rewarded with Ether, the native
cryptocurrency of Ethereum.
• Network: This layer handles the communication between nodes on the Ethereum network. It uses
a peer-to-peer (P2P) network, where each node is connected to multiple other nodes.
4. Base Layer:
• This layer provides the building blocks for the Ethereum network.
• P2P: This protocol allows nodes on the network to communicate with each other directly.
• Crypto: This refers to the cryptographic algorithms used to secure the network, such as
encryption, hashing, and digital signatures.
• HttpClient: This library is used to make HTTP requests to other nodes on the network.
• LevelDB: This is a key-value database used to store data on the blockchain.
• Solidity: This is the programming language used to write smart contracts.
• Math&Number: These libraries provide mathematical functions and number operations used in
smart contracts.
❖ In summary:
The DApp layer interacts with the smart contract layer through Web3.js. The smart contract layer
executes the code of smart contracts on the EVM and communicates with the blockchain layer through
RPC. The blockchain layer records all transactions and smart contract code, and the base layer provides
the underlying infrastructure for the entire network.
6) Explain accounts in Ethereum and its types.
In the Ethereum blockchain, accounts serve as fundamental entities that hold Ether and interact with
smart contracts. There are two primary types of accounts:
1. Externally Owned Accounts (EOAs)
• Control: Controlled by private keys.
• Functionality: Limited to sending transactions and interacting with smart contracts.
• Security: High security due to the need for a private key to authorize transactions.
• Example: Your personal Ethereum wallet is an EOA.
2. Contract Accounts
• Creation: Deployed by transactions initiated by EOAs.
• Functionality: Execute code defined in their bytecode.
• Storage: Can store state data.
• Security: Depends on the code's quality and the security practices of the developer.
• Example: Decentralized applications (dApps) like Uniswap or OpenSea are built on contract
accounts.
5
CJ
6
CJ
3. Click "Send":
o Locate the "Send" button, usually in the middle of the screen.1
4. Enter Recipient's Address:
o Carefully input the Ethereum address of the recipient. Double-check for accuracy to avoid
sending to the wrong address.
5. Specify Amount:
o Enter the amount of Ether you wish to send in the designated field.
6. Set Gas Fee:
o MetaMask will automatically suggest a gas fee.2 You can adjust it if needed, but be mindful of
network congestion and transaction speed. Higher gas fees typically result in faster
transaction confirmation.3
7. Review and Confirm:
o Double-check all details, including the recipient's address, amount, and gas fee.
o Click "Next" to proceed.
8. Sign the Transaction:
o MetaMask will prompt you to sign the transaction using your private key.4
o Confirm the transaction by clicking "Confirm."
9. Wait for Confirmation:
o Your transaction will be broadcast to the Ethereum network and processed by miners.
o The time it takes for confirmation can vary depending on network congestion.5
❖ Important Considerations:
• Network Fees (Gas Fees): Be aware of the gas fees associated with transactions. Higher fees can
expedite the transaction process.6
• Security: Always double-check the recipient's address before sending Ether. Avoid sharing your
private key with anyone.
• Network Congestion: During periods of high network usage, transaction times and fees may
increase.7
• Test Networks: Practice sending Ether on test networks like Kovan or Rinkeby before using the
mainnet. This allows you to familiarize yourself with the process without risking real funds.
7
CJ
8
CJ
o Functions:
▪ placeOrder: Allows customers to place orders by specifying the pizza and paying the
required amount.
▪ fulfillOrder: Allows the owner to fulfill orders and update the order status.
▪ withdrawFunds: Allows the owner to withdraw funds from the smart contract.
2. Write the Solidity Code:
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract PizzaShop {
address public owner;
mapping(string => uint) public menu;
mapping(uint => Order) public orders;
uint public orderCount;
struct Order {
address customer;
string pizza;
uint price;
bool fulfilled;
}
constructor() {
owner = msg.sender;
menu["Margherita"] = 10;
menu["Pepperoni"] = 15;
// Add more pizzas to the menu
}
function placeOrder(string memory _pizza) public payable {
require(menu[_pizza] > 0, "Pizza not available");
require(msg.value >= menu[_pizza], "Insufficient funds");
orderCount++;
orders[orderCount] = Order(msg.sender, _pizza, menu[_pizza], false);
}
function fulfillOrder(uint _orderId) public onlyOwner {
require(orders[_orderId].fulfilled == false, "Order already fulfilled");
orders[_orderId].fulfilled = true;
// Trigger delivery or other actions
}
function withdrawFunds() public onlyOwner {
payable(owner).transfer(address(this).balance);
}
modifier onlyOwner() {
require(msg.sender == owner, "Only owner can call this function");
_;
}
}
9
CJ
An Ethereum block is the fundamental unit of data storage on the Ethereum blockchain. It contains a set
of transactions and smart contract executions, along with metadata about the block itself.
❖ Key fields in an Ethereum block header:
• Timestamp: The time at which the block was created, measured in seconds since the Unix epoch.
• Block Number: A unique identifier for the block, indicating its position in the blockchain.
• Difficulty: A measure of how difficult it was to mine the block. This difficulty level is adjusted to
maintain a target block time.
• mixHash: A hash value used in the proof-of-work mining algorithm.
• parentHash: A hash of the previous block in the chain, ensuring the integrity of the blockchain.
• Beneficiary: The address of the account that receives the block reward for mining the block.
• ExtraData: Additional data that can be included in the block, such as version information or
custom data.
• GasUsed: The total amount of gas used by all transactions included in the block.
• GasLimit: The maximum amount of gas allowed for the block.
10