Unit 2
Unit 2
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.
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:
Smart contracts on Ethereum are written in Solidity, a high-level language similar to JavaScript
and Python.
solidity
CopyEdit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract HelloWorld {
string public message;
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).
1. Open Remix.
2. Paste the Solidity code.
3. Click Compile (check for errors).
After compilation, the smart contract is deployed to the Ethereum blockchain. Deployment
requires gas fees, paid in Ether (ETH).
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.
javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
ACCOUNT TYPES
� Example: A MetaMask wallet is an EOA that users control with a private key.
solidity
CopyEdit
address payable recipient = 0x123...abc;
recipient.transfer(1 ether);
⃣ Contract Accounts
� Example: A decentralized exchange (DEX) contract that holds and transfers funds when
users interact with it.
solidity
CopyEdit
contract Fund {
function deposit() public payable {} // Allows users to send ETH
}
Key Difference Between EOA and Contract Account
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 is measured in gas units, while the price of gas is denominated in Gwei.
� Example:
Alice must have 1.00105 ETH in her wallet for the transaction to succeed.
� Example in Solidity:
solidity
CopyEdit
address payable receiver = payable(0x123...);
receiver.transfer(1 ether);
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);
solidity
CopyEdit
pragma solidity ^0.8.0;
contract MyContract {
uint256 public value;
function setValue(uint256 _value) public {
value = _value;
}
}
solidity
CopyEdit
contract GasExample {
uint256 public count;
Expensive Code:
solidity
CopyEdit
contract Expensive {
uint256 public data;
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
}
}
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]);
}
}
Loops that iterate over large datasets increase gas consumption. Instead, paginate data and
process in chunks.
� 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
✔ 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.
Ethereum provides multiple ways to access and interact with smart contracts and
transactions. This includes using Web3 libraries, Ethereum wallets, and blockchain
explorers.
javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
javascript
CopyEdit
const contractABI = [...] // Replace with actual contract ABI
const contractAddress = "0x123..."; // Smart contract address
javascript
CopyEdit
const { ethers } = require("ethers");
const provider = new ethers.JsonRpcProvider("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");
javascript
CopyEdit
const contract = new ethers.Contract(contractAddress, contractABI, provider);
✔ MetaMask allows users to interact with contracts directly from their browser.
✔ DApps integrate with MetaMask using Ethereum Provider API.
javascript
CopyEdit
if (window.ethereum) {
window.ethereum.request({ method: 'eth_requestAccounts' })
.then(accounts => console.log("Connected account:", accounts[0]))
.catch(err => console.error(err));
}
javascript
CopyEdit
const txHash = "0xabc123..."; // Transaction hash
web3.eth.getTransaction(txHash)
.then(tx => console.log(tx))
.catch(err => console.error(err));
json
CopyEdit
{
"blockHash": "0x...",
"blockNumber": 1234567,
"from": "0xSenderAddress",
"to": "0xReceiverAddress",
"gas": 21000,
"gasPrice": "50000000000",
"value": "1000000000000000000"
}
javascript
CopyEdit
const transactionHash = "0xabc123...";
provider.getTransaction(transactionHash)
.then(tx => console.log(tx))
.catch(err => console.error(err));
javascript
CopyEdit
web3.eth.getTransactionReceipt(txHash)
.then(receipt => console.log(receipt))
.catch(err => console.error(err));
json
CopyEdit
{
"transactionHash": "0x...",
"blockNumber": 1234567,
"status": true,
"gasUsed": 21000
}
javascript
CopyEdit
web3.eth.sendTransaction({
from: "0xSenderAddress",
to: "0xReceiverAddress",
value: web3.utils.toWei("1", "ether"),
gas: 21000,
gasPrice: web3.utils.toWei("50", "gwei")
});
javascript
CopyEdit
const contract = new web3.eth.Contract(contractABI, contractAddress);
contract.methods.setValue(100).send({ from: senderAddress, gas: 50000 });
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
✔ 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.
The user initiates an action (e.g., swapping tokens, voting, sending funds).
The smart contract processes the transaction and updates the blockchain.
⃣ 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.
Alternatives to Mix
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
� 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.
solidity
CopyEdit
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
string public message;
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.
sh
CopyEdit
# Install Hardhat
npm install --save-dev 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.
sh
CopyEdit
truffle compile
truffle migrate --network ropsten
truffle test
sh
CopyEdit
ganache-cli -p 8545
B. Foundry & Anvil
� Installing Foundry
sh
CopyEdit
curl -L https://foundry.paradigm.xyz | bash
javascript
CopyEdit
const Web3 = require("web3");
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID");
javascript
CopyEdit
const Web3 = require("web3");
const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");
⃣ Security & Auditing Tools
A. OpenZeppelin
solidity
CopyEdit
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
sh
CopyEdit
slither MyContract.sol
⃣ Storage Solutions
A. IPFS (InterPlanetary File System)
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.
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
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);
});
});
solidity
CopyEdit
pragma solidity ^0.8.0;
contract HelloWeb3 {
string public message = "Welcome to Web3!";
}
Web3 applications need decentralized storage instead of centralized cloud providers like Google
Drive or AWS.
sh
CopyEdit
ipfs add myfile.txt
✔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);
solidity
CopyEdit
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract PriceOracle {
AggregatorV3Interface internal priceFeed;
constructor() {
priceFeed = AggregatorV3Interface(0xSomeChainlinkOracleAddress);
}
}
javascript
CopyEdit
const tx = await uniswap.swapExactTokensForTokens(amountIn, amountOutMin, path, account, deadline);
await tx.wait();
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.
sh
CopyEdit
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt update
sudo apt install ethereum
sh
CopyEdit
brew tap ethereum/ethereum
brew install ethereum
Verify Installation
sh
CopyEdit
geth version
sh
CopyEdit
geth --syncmode full --http
sh
CopyEdit
geth --syncmode light --http
B. Running an Ethereum Testnet Node
sh
CopyEdit
geth --goerli --http
sh
CopyEdit
geth attach --exec "eth.syncing" http://127.0.0.1:8545
Install Web3.js
sh
CopyEdit
npm install web3
javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3("http://localhost:8545");
web3.eth.getBlockNumber().then(console.log);
javascript
CopyEdit
const sender = "0xYourSenderAddress";
const receiver = "0xReceiverAddress";
const amount = web3.utils.toWei("0.1", "ether");
sh
CopyEdit
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt update
sudo apt install ethereum
� Verify Installation
sh
CopyEdit
geth version
sh
CopyEdit
geth --syncmode full --http
sh
CopyEdit
geth --goerli --http
sh
CopyEdit
geth attach --exec "eth.syncing" http://127.0.0.1:8545
sh
CopyEdit
ssh -i my-key.pem ubuntu@your-server-ip
Step 3: Install & Run Geth on AWS
sh
CopyEdit
sudo apt update && sudo apt upgrade -y
sh
CopyEdit
sudo apt install ethereum -y
sh
CopyEdit
geth --syncmode full --http --http.addr "0.0.0.0" --http.api "eth,net,web3"
Install Web3.js
sh
CopyEdit
npm install web3
javascript
CopyEdit
const Web3 = require('web3');
const web3 = new Web3("http://your-server-ip:8545");
web3.eth.getBlockNumber().then(console.log);
javascript
CopyEdit
const sender = "0xYourSenderAddress";
const receiver = "0xReceiverAddress";
const amount = web3.utils.toWei("0.1", "ether");