0% found this document useful (0 votes)
13 views29 pages

Unit 2

This document provides an overview of programming smart contracts on Ethereum, detailing their features, development process, and various account types. It explains the concept of gas, its significance in transactions, and how to access and interact with smart contracts using tools like Web3.js and Ethers.js. Additionally, it covers advantages, challenges, and real-world use cases of smart contracts in various sectors.

Uploaded by

vishnuprya2915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views29 pages

Unit 2

This document provides an overview of programming smart contracts on Ethereum, detailing their features, development process, and various account types. It explains the concept of gas, its significance in transactions, and how to access and interact with smart contracts using tools like Web3.js and Ethers.js. Additionally, it covers advantages, challenges, and real-world use cases of smart contracts in various sectors.

Uploaded by

vishnuprya2915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

SMART CONTRACTS AND APPLICATION DEVELOPMENT

UNIT II: Introduction to Programming Smart Contracts, A Simple Smart Contract, Account
Types, Gas, and Transactions, Accessing Contracts and Transactions, Mix, Dapps, Developer
Tools, Ethereum Tests,Web3 Base Layer Services, Installing, Building, Testing, & Deploying
Ethereum nodes.

INTRODUCTION TO PROGRAMMING SMART CONTRACTS

1. What is a Smart Contract?


A smart contract is a self-executing computer program stored on a blockchain that
automatically enforces agreements and executes predefined logic without intermediaries. It
ensures trust, transparency, and security in digital transactions.

Key Features of Smart Contracts:

✔ Decentralization – No single authority controls the contract.


✔ Immutability – Once deployed, the contract code cannot be altered.
✔ Transparency – Contract code and transactions are publicly visible.
✔ Automation – Executes actions automatically when conditions are met.
✔ Security – Transactions are cryptographically secure.

How Smart Contracts Work:

1. A developer writes the smart contract using a programming language (e.g., Solidity for
Ethereum).
2. The contract is compiled into bytecode and deployed on the Ethereum Virtual
Machine (EVM).
3. Users interact with the contract by sending transactions.
4. The contract executes functions based on pre-defined conditions.
� Example Use Cases:

 Decentralized Finance (DeFi) – Automated lending, borrowing, and trading.


 Supply Chain Management – Tracking goods through blockchain.
 NFT Marketplaces – Secure digital ownership and transactions.

2. Smart Contract Development Process


Step 1: Writing a Smart Contract

Smart contracts on Ethereum are written in Solidity, a high-level language similar to JavaScript
and Python.

Example: A Simple Solidity Smart Contract

solidity
CopyEdit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract HelloWorld {
string public message;

constructor(string memory _message) {


message = _message;
}

function updateMessage(string memory _newMessage) public {


message = _newMessage;
}
}

Explanation of the Code:

✔ State Variable (message) – Stores contract data.


✔ Constructor – Initializes the contract when deployed.
✔ Function (updateMessage) – Allows updating the stored message.

Step 2: Compiling the Smart Contract

Before deployment, the Solidity code must be converted into bytecode that can be understood by
the Ethereum Virtual Machine (EVM). This is done using tools like:
✔ Remix IDE (Web-based Solidity compiler).
✔ Truffle & Hardhat (Development frameworks).
✔ Solc (Solidity Compiler).

� Example: Compiling using Remix IDE:

1. Open Remix.
2. Paste the Solidity code.
3. Click Compile (check for errors).

Step 3: Deploying the Smart Contract

After compilation, the smart contract is deployed to the Ethereum blockchain. Deployment
requires gas fees, paid in Ether (ETH).

� Deployment Steps in Remix IDE:

1. Select Injected Web3 and connect MetaMask.


2. Click Deploy (requires ETH for gas fees).
3. Contract gets assigned a unique address on Ethereum.

✔ Alternative Tools: Hardhat, Truffle, Ganache (for local testing).

Step 4: Interacting with the Smart Contract

Once deployed, users can call functions and send transactions using:
✔ Etherscan – View contract details and transactions.
✔ Web3.js / Ethers.js – JavaScript libraries for interacting with Ethereum.
✔ MetaMask – Wallet for executing contract functions.

� Example: Calling a Smart Contract Using Web3.js

javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

const contractAddress = "0x123456789...";


const contractABI = [/* ABI JSON here */];

const contract = new web3.eth.Contract(contractABI, contractAddress);


contract.methods.message().call().then(console.log);

✔ Retrieves the current message stored in the contract.

3. Advantages of Smart Contracts


✔ Eliminates Intermediaries – Reduces costs and improves efficiency.
✔ Enhanced Security – Cryptographically secured, reducing fraud.
✔ Speed & Efficiency – Automates transactions, eliminating delays.
✔ Transparency – Publicly accessible on the blockchain.

4. Challenges of Smart Contracts


� Immutable Code – Bugs in deployed contracts cannot be fixed.
� High Gas Fees – Transactions can be costly during network congestion.
� Security Risks – Vulnerable to hacking if not properly written.
5. Real-World Use Cases
✔ Decentralized Finance (DeFi): Platforms like Uniswap, Aave automate financial services.
✔ Supply Chain: Companies like IBM use blockchain for logistics tracking.
✔ NFT Marketplaces: Platforms like OpenSea facilitate digital asset sales.
✔ Voting Systems: Blockchain-based voting ensures tamper-proof elections.

ACCOUNT TYPES

1. Ethereum Account Types


Ethereum has two types of accounts, both identified by a unique 20-byte address:

⃣ Externally Owned Accounts (EOAs)

✔ Controlled by private keys (human users or applications).


✔ Can send transactions and trigger smart contracts.
✔ Used for holding, sending ETH, and interacting with contracts.

� Example: A MetaMask wallet is an EOA that users control with a private key.

� EOA Transaction Example (Sending ETH)

solidity
CopyEdit
address payable recipient = 0x123...abc;
recipient.transfer(1 ether);

⃣ Contract Accounts

✔ Controlled by smart contract code (not private keys).


✔ Cannot initiate transactions but can respond when called.
✔ Have persistent storage (store state variables).
✔ Governed by predefined logic in Solidity code.

� Example: A decentralized exchange (DEX) contract that holds and transfers funds when
users interact with it.

� Contract Transaction Example

solidity
CopyEdit
contract Fund {
function deposit() public payable {} // Allows users to send ETH
}
Key Difference Between EOA and Contract Account

Feature Externally Owned Account (EOA) Contract Account


Controlled By Private Key Smart Contract Code
Transaction Initiation Yes No (Only responds)
Storage No Yes
Can Call Other Contracts? Yes Yes

GAS IN ETHEREUM

Definition:

Gas is a unit that measures the amount of computational effort required to execute transactions
and smart contracts in Ethereum.

Purpose of Gas:

✔ Prevents network spam – Users must pay fees, discouraging unnecessary transactions.
✔ Incentivizes miners/validators – Gas fees reward those who process transactions.
✔ Enables a flexible fee structure – Users can adjust gas price to prioritize transactions.

Gas Units and Gwei

Gas is measured in gas units, while the price of gas is denominated in Gwei.

1 Gwei = 0.000000001 ETH (1 billion Gwei = 1 ETH).

� Example:

 A simple ETH transfer costs 21,000 gas.


 Calling a complex smart contract function may cost over 100,000 gas.

1. How Gas Works in Ethereum Transactions


A transaction sender specifies:
�⃣ Gas Limit – The maximum amount of gas they are willing to spend.
�⃣ Gas Price – The price per unit of gas (in Gwei).
�⃣ Total Gas Fee = Gas Used × Gas Price.

Gas Fee Calculation Example:

Imagine Alice sends 1 ETH to Bob with:

 Gas Limit = 21,000


 Gas Price = 50 Gwei
� Total Gas Fee:

21,000×50=1,050,000 Gwei=0.00105 ETH21,000 \times 50 = 1,050,000 \text{ Gwei} = 0.00105


\text{ ETH}21,000×50=1,050,000 Gwei=0.00105 ETH

Alice must have 1.00105 ETH in her wallet for the transaction to succeed.

2. Types of Transactions in Ethereum


Ethereum supports three main types of transactions:

A. Regular Transactions (ETH Transfers)

✔ Sending ETH from one EOA to another.


✔ Uses 21,000 gas (minimum).

� Example in Solidity:

solidity
CopyEdit
address payable receiver = payable(0x123...);
receiver.transfer(1 ether);

� Example Using Web3.js:

javascript
CopyEdit
const tx = {
from: senderAddress,
to: receiverAddress,
value: web3.utils.toWei('1', 'ether'),
gas: 21000,
gasPrice: web3.utils.toWei('50', 'gwei')
};

web3.eth.sendTransaction(tx);

B. Contract Deployment Transactions

✔ Deploying a new smart contract on Ethereum.


✔ Requires more gas than regular transactions.

� Gas Consumption Example:


Deploying a basic ERC-20 token contract might cost 1,000,000+ gas.

� Example of a Deployment Transaction:

solidity
CopyEdit
pragma solidity ^0.8.0;

contract MyContract {
uint256 public value;
function setValue(uint256 _value) public {
value = _value;
}
}

C. Contract Interaction Transactions

✔ Calling functions inside a deployed smart contract.


✔ Gas cost depends on the computational complexity.

� Example: Calling a Contract Function

solidity
CopyEdit
contract GasExample {
uint256 public count;

function increment() public {


count += 1; // This operation costs gas
}
}

3. Gas Optimization Techniques


Gas fees can be high if smart contracts are inefficient. Developers use various optimization
techniques to reduce gas costs.

Avoid Expensive Storage Operations

✔ Storage (sstore, sload) is expensive in Ethereum.


✔ Use memory instead of storage for temporary variables.

Expensive Code:

solidity
CopyEdit
contract Expensive {
uint256 public data;

function setData(uint256 _data) public {


data = _data; // Writing to storage is costly
}
}

Optimized Code:

solidity
CopyEdit
contract Optimized {
function process(uint256 _data) public pure returns (uint256) {
uint256 temp = _data * 2; // Uses memory, cheaper
return temp;
}
}

Batch Processing

Instead of processing transactions one by one, batch multiple operations in a single transaction.

Gas-Heavy Approach:

solidity
CopyEdit
function processItems(uint256[] memory items) public {
for (uint256 i = 0; i < items.length; i++) {
data[i] = items[i]; // Costs more gas
}
}

Optimized Batch Processing:

solidity
CopyEdit
function processBatch(uint256[] memory items) public {
require(items.length <= 10, "Limit batch size"); // Limits gas usage
for (uint256 i = 0; i < items.length; i++) {
processItem(items[i]);
}
}

Avoid Loops That Grow Uncontrollably

Loops that iterate over large datasets increase gas consumption. Instead, paginate data and
process in chunks.

4. Gas Refund and EIP-1559 Mechanism


Ethereum’s EIP-1559 update changed the way gas fees work.

Gas Fee Structure (EIP-1559)

�⃣ Base Fee – The minimum fee required for a transaction (burned).


�⃣ Priority Fee (Tip) – Extra incentive for miners/validators.
�⃣ Max Fee – The maximum gas price the sender is willing to pay.

� Formula for Total Fee:

Total Fee=Base Fee+Priority Fee\text{Total Fee} = \text{Base Fee} + \text{Priority


Fee}Total Fee=Base Fee+Priority Fee

� Example:
If the Base Fee = 30 Gwei and the Tip = 5 Gwei, the sender pays 35 Gwei per gas unit.
5. Common Gas-Related Errors
Out of Gas Error

✔ Happens when Gas Limit is set too low.


✔ The transaction fails but still costs gas.
✔ Solution: Set a higher Gas Limit when executing transactions.

Gas Price Too Low

✔ If the gas price is too low, miners might ignore the transaction.
✔ Solution: Use tools like Etherscan Gas Tracker to check the current gas price.

ACCESSING CONTRACTS AND TRANSACTIONS IN ETHEREUM

Ethereum provides multiple ways to access and interact with smart contracts and
transactions. This includes using Web3 libraries, Ethereum wallets, and blockchain
explorers.

⃣ Accessing Ethereum Smart Contracts


A smart contract is deployed on the Ethereum blockchain and can be accessed using:
✔ Ethereum Node (Infura, Alchemy, or Local Node)
✔ Web3.js or Ethers.js (JavaScript libraries for Ethereum)
✔ Ethereum Wallets (MetaMask, MyEtherWallet, etc.)
✔ Command Line Interfaces (geth, Hardhat, Truffle console)

Steps to Access a Smart Contract:

�⃣ Connect to an Ethereum Node


�⃣ Get the Smart Contract Address
�⃣ Use the Contract’s ABI (Application Binary Interface)
�⃣ Read & Write Data to the Contract

A. Accessing Smart Contracts Using Web3.js

� Example: Connecting to an Ethereum Node with Web3.js

javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

� Example: Loading a Smart Contract in Web3.js

javascript
CopyEdit
const contractABI = [...] // Replace with actual contract ABI
const contractAddress = "0x123..."; // Smart contract address

const contract = new web3.eth.Contract(contractABI, contractAddress);

B. Accessing Smart Contracts Using Ethers.js

Ethers.js is a lightweight alternative to Web3.js for interacting with Ethereum.

� Example: Connecting to an Ethereum Node with Ethers.js

javascript
CopyEdit
const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");

� Example: Interacting with a Contract in Ethers.js

javascript
CopyEdit
const contract = new ethers.Contract(contractAddress, contractABI, provider);

C. Accessing Contracts Using MetaMask

✔ MetaMask allows users to interact with contracts directly from their browser.
✔ DApps integrate with MetaMask using Ethereum Provider API.

� Example: Requesting Access to MetaMask from a Website

javascript
CopyEdit
if (window.ethereum) {
window.ethereum.request({ method: 'eth_requestAccounts' })
.then(accounts => console.log("Connected account:", accounts[0]))
.catch(err => console.error(err));
}

⃣ Accessing Ethereum Transactions


Ethereum transactions change the state of the blockchain and can be accessed using:
✔ Blockchain Explorers (Etherscan, Blockchair, etc.)
✔ Web3.js / Ethers.js
✔ Ethereum JSON-RPC API

A.Fetching Transaction Details Using Web3.js


� Example: Get Transaction Details

javascript
CopyEdit
const txHash = "0xabc123..."; // Transaction hash
web3.eth.getTransaction(txHash)
.then(tx => console.log(tx))
.catch(err => console.error(err));

� Transaction Data Example Output:

json
CopyEdit
{
"blockHash": "0x...",
"blockNumber": 1234567,
"from": "0xSenderAddress",
"to": "0xReceiverAddress",
"gas": 21000,
"gasPrice": "50000000000",
"value": "1000000000000000000"
}

B. Fetching Transaction Details Using Ethers.js

� Example: Get Transaction Details

javascript
CopyEdit
const transactionHash = "0xabc123...";
provider.getTransaction(transactionHash)
.then(tx => console.log(tx))
.catch(err => console.error(err));

C. Checking Transaction Status

Ethereum transactions can have three statuses:


✔ Pending – The transaction is waiting for confirmation.
✔ Successful – The transaction is mined and executed successfully.
✔ Failed – The transaction ran out of gas or was reverted.

� Example: Checking Transaction Receipt in Web3.js

javascript
CopyEdit
web3.eth.getTransactionReceipt(txHash)
.then(receipt => console.log(receipt))
.catch(err => console.error(err));

� Transaction Receipt Example Output:

json
CopyEdit
{
"transactionHash": "0x...",
"blockNumber": 1234567,
"status": true,
"gasUsed": 21000
}

✔ status: true → Transaction was successful


✔ status: false → Transaction failed

⃣ Sending Transactions to a Smart Contract


A. Sending ETH from One Account to Another

� Example: Sending ETH Using Web3.js

javascript
CopyEdit
web3.eth.sendTransaction({
from: "0xSenderAddress",
to: "0xReceiverAddress",
value: web3.utils.toWei("1", "ether"),
gas: 21000,
gasPrice: web3.utils.toWei("50", "gwei")
});

B. Calling a Smart Contract Function (Write Operation)

✔ Writing data to a contract requires gas.


✔ Example: Updating a variable in a smart contract.

� Example: Sending a Transaction to a Contract Function

javascript
CopyEdit
const contract = new web3.eth.Contract(contractABI, contractAddress);
contract.methods.setValue(100).send({ from: senderAddress, gas: 50000 });

C. Reading Data from a Smart Contract (Read Operation)

✔ Reading does not require gas.


✔ Example: Fetching a stored value from a contract.

� Example: Fetching Data Using Web3.js

javascript
CopyEdit
contract.methods.getValue().call()
.then(value => console.log("Stored Value:", value));
⃣ Monitoring Transactions Using Etherscan
Users can track Ethereum transactions using Etherscan:
✔ Enter the Transaction Hash (TXID).
✔ Check Block Number, Gas Used, Sender, Receiver, Status.
✔ View internal transactions (contract calls within a transaction).

� Etherscan Example:
� https://etherscan.io/

DAPP

A Decentralized Application (DApp) is a blockchain-powered application that operates


without a central authority. Unlike traditional apps that rely on centralized servers, DApps
use Ethereum smart contracts to execute transactions and store data securely on the
blockchain.

⃣ Key Components of DApp Architecture


A typical DApp consists of three main layers:

1. Smart Contract Layer (Ethereum Blockchain) – Backend

✔ Smart contracts are self-executing programs written in Solidity.


✔ Stores business logic and processes user transactions.
✔ Deployed on Ethereum blockchain – immutable and secure.

2. Frontend Layer – User Interface (UI)

✔ The frontend is the web or mobile interface used to interact with the DApp.
✔ Built using React.js, Angular, or Vue.js.
✔ Communicates with smart contracts using Web3.js or Ethers.js.

3. Storage Layer – Decentralized Data Storage

✔ DApps require decentralized storage to store data.


✔ Common storage solutions:
� IPFS (InterPlanetary File System) – Stores files in a distributed network.
� Arweave – Permanent, blockchain-based file storage.
� Ethereum Blockchain – Stores critical transactional data (but expensive).
3 ⃣ How a DApp Works
� Step 1: User Accesses the DApp

 The user opens the DApp through a web browser.


 The frontend is hosted on IPFS or Arweave instead of a centralized server.

� Step 2: User Connects Wallet

 The user connects their Ethereum wallet (MetaMask, WalletConnect).


 The wallet enables secure signing of transactions.

� Step 3: Smart Contract Execution

 The user initiates an action (e.g., swapping tokens, voting, sending funds).
 The smart contract processes the transaction and updates the blockchain.

� Step 4: Data Storage

 Transaction data is stored on Ethereum.


 Large files (e.g., NFTs, images) are stored in IPFS/Arweave.

� Step 5: User Receives Confirmation

 The smart contract emits an event, notifying the frontend.


 The user sees an updated balance or confirmation message.
⃣ DApp vs Traditional Web App
Feature Traditional Web App Decentralized App (DApp)
Backend Centralized server Smart contracts on Ethereum
Database SQL, NoSQL (e.g., Firebase) Blockchain (Immutable ledger)
Frontend HTML, CSS, JS (React, Angular) Same as Web App
Security Vulnerable to hacks Decentralized and tamper-proof
Data Storage Centralized cloud storage Decentralized (IPFS, Arweave)
Control Owned by a company Community-governed (DAOs)

⃣ Examples of DApps
� Uniswap (DeFi) – Decentralized Exchange (DEX) for token swaps.
� Aave (Lending/Borrowing) – Users can lend/borrow crypto assets.
� Decentraland (Virtual World) – Blockchain-powered metaverse.
� OpenSea (NFT Marketplace) – Buy, sell, and trade NFTs securely.

MIX (ETHEREUM IDE)


Mix was an Integrated Development Environment (IDE) provided by Ethereum for smart
contract development. However, it is now deprecated, and developers use alternatives like
Remix, Hardhat, and Truffle.

Features of Mix (Before Deprecation)

✔ Graphical UI for writing and testing Solidity contracts.


✔ Supports debugging and deployment.
✔ Provides a simulator for testing transactions.

Alternatives to Mix

 Remix IDE (Web-based Solidity editor)


 Hardhat (JavaScript-based development environment)
 Truffle Suite (Comprehensive Ethereum development framework

DEVELOPER TOOLS FOR ETHEREUM

Ethereum provides various developer tools to help in writing, testing, debugging, and
deploying smart contracts and decentralized applications (DApps). These tools simplify
blockchain interactions, ensure security, and optimize gas usage.
⃣ Categories of Ethereum Developer Tools
Ethereum development involves multiple tools categorized into:

Category Examples
Smart Contract Development Remix, Hardhat, Truffle
Blockchain Simulation & Testing Ganache, Foundry, Anvil
Wallets & Blockchain Interaction MetaMask, WalletConnect, Ledger
Node & API Services Infura, Alchemy, QuickNode
Security & Auditing OpenZeppelin, MythX, Slither
Storage Solutions IPFS, Arweave, Filecoin

⃣ Smart Contract Development Tools


A. Remix IDE

� What is Remix?
✔ A web-based IDE for writing, testing, and deploying Solidity smart contracts.
✔ Supports Solidity debugging, contract interaction, and plugins.

� Features
✔ Solidity compiler with multiple versions.
✔ Built-in deployment to Ethereum testnets.
✔ Web3 integration for blockchain transactions.

� Example: Writing a Simple Contract in Remix

solidity
CopyEdit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
string public message;

function setMessage(string memory _message) public {


message = _message;
}
}

✔ This contract allows users to store a message on the blockchain.

B. Hardhat

� What is Hardhat?
✔ A JavaScript-based Ethereum development framework for testing and deploying
contracts.
✔ Offers a local Ethereum network for contract execution.

� Features
✔ Fast Solidity compilation and testing.
✔ Debugging tools with stack traces & console.log.
✔ Custom scripts for deployment.

� Example: Hardhat Project Setup

sh
CopyEdit
# Install Hardhat
npm install --save-dev hardhat

# Create a new project


npx hardhat

C. Truffle

� What is Truffle?
✔ A full-stack Ethereum development framework that provides contract compilation,
migration, and testing.

� Features
✔ Contract testing with Mocha & Chai.
✔ Built-in Ganache for local blockchain testing.
✔ Deployment automation.

� Example: Deploying a Contract with Truffle

sh
CopyEdit
truffle compile
truffle migrate --network ropsten
truffle test

⃣ Blockchain Simulation & Testing Tools


A. Ganache

✔ A local Ethereum blockchain for testing smart contracts.


✔ Provides instant transactions and gas fee simulations.
✔ Works with Truffle & Hardhat.

� Starting Ganache for Testing

sh
CopyEdit
ganache-cli -p 8545
B. Foundry & Anvil

✔ Foundry is a fast Ethereum development tool built in Rust.


✔ Anvil is a high-performance local Ethereum node.
✔ Ideal for advanced Solidity testing.

� Installing Foundry

sh
CopyEdit
curl -L https://foundry.paradigm.xyz | bash

⃣ Wallets & Blockchain Interaction


A. MetaMask

✔ A browser-based Ethereum wallet for interacting with DApps.


✔ Supports ETH transactions and smart contract interactions.

� Web3.js Example: Sending ETH from MetaMask

javascript
CopyEdit
const Web3 = require("web3");
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");

const account = "0xYourWalletAddress";


web3.eth.getBalance(account).then(console.log);

⃣ Node & API Services


A. Infura

✔ A cloud-based Ethereum API provider.


✔ Allows DApps to connect to Ethereum without running a full node.

� Connecting to Ethereum via Infura

javascript
CopyEdit
const Web3 = require("web3");
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");
⃣ Security & Auditing Tools
A. OpenZeppelin

✔ A library of secure smart contract templates (ERC-20, ERC-721).


✔ Ensures safe contract implementation.

� Example: Creating an ERC-20 Token

solidity
CopyEdit
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {


constructor() ERC20("MyToken", "MTK") {
_mint(msg.sender, 1000 * 10 ** decimals());
}
}

B. MythX & Slither

✔ MythX – Smart contract security scanner.


✔ Slither – Static analysis tool for Solidity contracts.

� Running Slither on a Contract

sh
CopyEdit
slither MyContract.sol

⃣ Storage Solutions
A. IPFS (InterPlanetary File System)

✔ A decentralized storage protocol for saving large files.


✔Ensures DApp data persistence.

� Uploading a File to IPFS

sh
CopyEdit
ipfs add myfile.txt
ETHEREUM TESTING FRAMEWORKS
Testing is critical in Ethereum development to ensure smart contracts work as expected and
are secure from vulnerabilities.

Types of Ethereum Tests

✔Unit Testing – Testing individual functions.


✔Integration Testing – Testing contract interaction with other services.
✔End-to-End Testing – Simulating real-world use cases.

Ethereum Testing Tools

Tool Description
Hardhat Provides a local Ethereum environment for debugging
Truffle Tests Built-in testing suite using JavaScript
Ganache Local blockchain for contract testing
Ethers.js & Web3.js Used for writing test scripts

� Example: Writing a Simple Solidity Test in Hardhat

solidity
CopyEdit
const { expect } = require("chai");

describe("MyContract", function () {
it("Should return the correct value", async function () {
const MyContract = await ethers.getContractFactory("MyContract");
const contract = await MyContract.deploy();
await contract.deployed();

expect(await contract.getValue()).to.equal(100);
});
});

WEB3 BASE LAYER SERVICES

⃣ Introduction to Web3 Base Layer Services


Web3 is the next evolution of the internet, focusing on decentralization, blockchain-based
security, and user ownership of data. The Base Layer Services of Web3 are the fundamental
infrastructure components that power decentralized applications (DApps) and blockchain
interactions.

Key Features of Web3 Base Layer Services

✔Decentralization – No central authority controls data or transactions.


✔Blockchain Integration – Uses smart contracts for execution and verification.
✔Trustless Transactions – Users interact without intermediaries.
✔Enhanced Security – Data is stored on decentralized networks, reducing hacks.
⃣ Key Components of Web3 Base Layer Services
A. Blockchain Networks (Layer 1 & Layer 2 Solutions)

Blockchain networks form the foundation of Web3.

✔Layer 1 Networks (Main Blockchains)

 Ethereum (Smart Contracts, DeFi, DApps)


 Bitcoin (Store of Value, Security)
 Solana, Polkadot, Avalanche

✔Layer 2 Networks (Scalability Solutions)

 Polygon (Ethereum scaling)


 Arbitrum, Optimism (Rollups for faster transactions)
 zkSync (Zero-Knowledge Rollups)

� Example: Ethereum Smart Contract on Layer 1

solidity
CopyEdit
pragma solidity ^0.8.0;

contract HelloWeb3 {
string public message = "Welcome to Web3!";
}

B. Decentralized Storage Solutions

Web3 applications need decentralized storage instead of centralized cloud providers like Google
Drive or AWS.

✔IPFS (InterPlanetary File System) – A peer-to-peer protocol for storing files.


✔Arweave – Permanent, blockchain-based storage.
✔Filecoin – Incentivized decentralized storage.

� Example: Uploading a File to IPFS

sh
CopyEdit
ipfs add myfile.txt

C. Decentralized Identity & Authentication (Self-Sovereign Identity - SSI)

✔Ethereum Name Service (ENS) – Converts Ethereum addresses into human-readable names
(e.g., myname.eth).
✔DID (Decentralized Identifiers) – Secure login without passwords.
✔Polygon ID, SpruceID – Identity verification without third parties.
� Example: Resolving an ENS Name

javascript
CopyEdit
const ens = await provider.lookupAddress("myname.eth");
console.log(ens);

D. Smart Contracts & Decentralized Computation

✔Ethereum Virtual Machine (EVM) – Runs smart contracts securely.


✔WASM (WebAssembly) – Used in Polkadot, Near, and Cosmos.
✔Chainlink (Oracles) – Connects smart contracts with real-world data.

� Example: Chainlink Price Feed in a Smart Contract

solidity
CopyEdit
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceOracle {
AggregatorV3Interface internal priceFeed;

constructor() {
priceFeed = AggregatorV3Interface(0xSomeChainlinkOracleAddress);
}
}

E. Decentralized Finance (DeFi) Protocols

✔Uniswap – Decentralized Exchange (DEX).


✔Aave, Compound – Lending and borrowing platforms.
✔MakerDAO – Stablecoin creation (DAI).

� Example: Swapping Tokens on Uniswap Using Web3.js

javascript
CopyEdit
const tx = await uniswap.swapExactTokensForTokens(amountIn, amountOutMin, path, account, deadline);
await tx.wait();

F. Decentralized Governance & DAOs

✔Decentralized Autonomous Organizations (DAOs) – Blockchain-based governance.


✔Snapshot, Aragon, Gnosis Safe – Voting and proposal management.

� Example: DAO Voting Smart Contract

solidity
CopyEdit
mapping(address => bool) public hasVoted;
function vote() public {
require(!hasVoted[msg.sender], "Already voted");
hasVoted[msg.sender] = true;
}
How Web3 Base Layer Services Work Together
� Blockchain Layer – Ethereum, Solana, or other Layer 1s process transactions.
� Storage Layer – IPFS/Filecoin stores decentralized data.
� Identity Layer – ENS & DIDs authenticate users.
� Smart Contract Layer – Automates execution and business logic.
� DeFi Layer – Financial transactions occur trustlessly.
� Governance Layer – DAOs allow decentralized decision-making.

INSTALLING, BUILDING, TESTING & DEPLOYING ETHEREUM


NODES

⃣ Introduction to Ethereum Nodes


An Ethereum node is software that connects to the Ethereum blockchain network, allowing
users to interact with smart contracts, validate transactions, and maintain a copy of the
blockchain ledger. Nodes are essential for decentralization and security in Ethereum.

Types of Ethereum Nodes

Node Type Description Examples


Full Node Stores the entire blockchain & verifies transactions Geth, Besu, Nethermind
Stores only recent block headers & relies on full
Light Node Geth (light mode)
nodes
Archive Node Stores full blockchain history, including past states Geth (archive mode)
Validator Prysm, Lighthouse,
Participates in Ethereum staking (Proof-of-Stake)
Node Teku
⃣ Installing an Ethereum Node
Ethereum nodes can be installed using different clients like Geth, Besu, and Nethermind. The
most widely used is Geth (Go-Ethereum).

A. Installing Geth (Go-Ethereum)

Install Geth on Ubuntu/Linux

sh
CopyEdit
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt update
sudo apt install ethereum

Install Geth on macOS

sh
CopyEdit
brew tap ethereum/ethereum
brew install ethereum

Verify Installation

sh
CopyEdit
geth version

✔This will display the installed Geth version.

Building an Ethereum Node


After installing Geth, configure and start the node.

A. Running a Full Ethereum Node

� Start a Full Node (Mainnet)

sh
CopyEdit
geth --syncmode full --http

✔This starts syncing with the Ethereum mainnet.


✔The --http flag enables an API for blockchain interaction.

� Start a Light Node (Faster Syncing)

sh
CopyEdit
geth --syncmode light --http
B. Running an Ethereum Testnet Node

Ethereum testnets (Goerli, Sepolia) allow developers to test smart contracts.

� Start a Node on Goerli Testnet

sh
CopyEdit
geth --goerli --http

� Check Node Syncing Status

sh
CopyEdit
geth attach --exec "eth.syncing" http://127.0.0.1:8545

✔Returns false when the node is fully synced.

Testing an Ethereum Node


Ethereum nodes allow developers to interact with the blockchain using Web3.js, Ethers.js, or
JSON-RPC calls.

A. Connecting to the Node Using Web3.js

Install Web3.js

sh
CopyEdit
npm install web3

Connect to a Local Ethereum Node

javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3("http://localhost:8545");

web3.eth.getBlockNumber().then(console.log);

✔Fetches the latest block number from the blockchain.

B. Sending a Test Transaction

Example: Sending ETH Between Accounts

javascript
CopyEdit
const sender = "0xYourSenderAddress";
const receiver = "0xReceiverAddress";
const amount = web3.utils.toWei("0.1", "ether");

web3.eth.sendTransaction({from: sender, to: receiver, value: amount})


.then(receipt => console.log(receipt));
✔Sends 0.1 ETH from sender to receiver.

DEPLOYING AN ETHEREUM NODE

⃣ Introduction to Ethereum Node Deployment


Deploying an Ethereum node allows developers, businesses, and validators to interact with the
Ethereum blockchain. A node helps in transaction validation, smart contract execution, and
blockchain data storage.

Why Deploy an Ethereum Node?

✔Run Decentralized Applications (DApps)


✔Validate Transactions & Blocks
✔Enhance Network Security & Decentralization
✔Interact with the Blockchain via Web3 APIs

⃣ Types of Ethereum Nodes for Deployment


Node Type Purpose Example Clients
Full Node Stores the entire blockchain & verifies transactions Geth, Besu, Nethermind
Light Node Stores only block headers, relies on full nodes Geth (light mode)
Archive Node Stores full blockchain history Geth (archive mode)
Validator Node Participates in staking (Proof-of-Stake) Prysm, Lighthouse, Teku

⃣ Steps to Deploy an Ethereum Node


Ethereum nodes can be deployed locally or on cloud platforms like AWS, Google Cloud, and
Azure.

A. Deploying an Ethereum Node Locally

A local deployment is useful for development and testing.

Step 1: Install an Ethereum Client (Geth, Besu, or Nethermind)

✔Geth (Go-Ethereum) is the most popular Ethereum client.

� Install Geth on Ubuntu/Linux

sh
CopyEdit
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt update
sudo apt install ethereum

� Install Geth on macOS


sh
CopyEdit
brew tap ethereum/ethereum
brew install ethereum

� Verify Installation

sh
CopyEdit
geth version

Step 2: Initialize and Sync the Node

✔Start a full Ethereum node to sync with the mainnet.

sh
CopyEdit
geth --syncmode full --http

✔ If you only need testnet, run:

sh
CopyEdit
geth --goerli --http

� Check Sync Status:

sh
CopyEdit
geth attach --exec "eth.syncing" http://127.0.0.1:8545

✔Returns false when fully synced.

B. Deploying an Ethereum Node on AWS

Cloud deployment ensures scalability, uptime, and high availability.

Step 1: Set Up an AWS EC2 Instance

�⃣ Login to AWS and create a new EC2 instance


�⃣ Choose Ubuntu 20.04 as the operating system
�⃣ Select an instance type (t2.medium or higher)
�⃣ Configure security groups to allow ports 30303 (P2P) and 8545 (RPC API)
�⃣ Download and save the SSH key pair for later use

Step 2: Connect to the Instance

� Use SSH to connect:

sh
CopyEdit
ssh -i my-key.pem ubuntu@your-server-ip
Step 3: Install & Run Geth on AWS

� Update system packages

sh
CopyEdit
sudo apt update && sudo apt upgrade -y

� Install Ethereum (Geth) on AWS

sh
CopyEdit
sudo apt install ethereum -y

� Start the Ethereum Node on AWS

sh
CopyEdit
geth --syncmode full --http --http.addr "0.0.0.0" --http.api "eth,net,web3"

✔Now, the node is running and accessible via RPC.

⃣ Interacting with the Deployed Node


Once the node is deployed, you can use Web3.js, Ethers.js, or JSON-RPC APIs to interact
with it.

A. Connecting to the Node Using Web3.js

Install Web3.js

sh
CopyEdit
npm install web3

Connect to a Local Ethereum Node

javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3("http://your-server-ip:8545");

web3.eth.getBlockNumber().then(console.log);

✔Fetches the latest block number from the blockchain.

B. Sending a Test Transaction

Example: Sending ETH Between Accounts

javascript
CopyEdit
const sender = "0xYourSenderAddress";
const receiver = "0xReceiverAddress";
const amount = web3.utils.toWei("0.1", "ether");

web3.eth.sendTransaction({from: sender, to: receiver, value: amount})


.then(receipt => console.log(receipt));

✔Transfers 0.1 ETH from sender to receiver.

You might also like