0% found this document useful (0 votes)
3 views9 pages

Module 5

Uploaded by

mukularyaa1
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)
3 views9 pages

Module 5

Uploaded by

mukularyaa1
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

Node.

js is a runtime environment that allows you to execute JavaScript code


outside the browser, primarily on the server-side.

Earlier: JavaScript → only runs in browser

Now: [Link] → runs on server, terminal, backend systems

Why [Link]?

• Fast execution (V8 engine compiles JS to machine code)


• Handles multiple requests efficiently
• Ideal for real-time applications
• Good for data streaming
• Unified language (same language for browser and server)

Where we need JS outside browser


• Web browser run on client computer
• So javascript do not handles things on server
• So we can not connect javascript with database directly
• Can not handle file system etc.
• So we have to run javascript on browser and Node help for this

Features of [Link]

1. Asynchronous & Non-Blocking

[Link] does not wait for one task to finish before starting another.

• File read → starts


• Meanwhile → handle user request

2. Single-Threaded but Event-Driven

Uses one main thread, but handles multiple operations via:

• Event loop
• Callbacks

3. Fast Execution

Due to: V8 Engine , Compilation to machine code

4. Scalable

Suitable for: Chat apps , Streaming apps, APIs


[Link] Architecture

Event Loop Model

Request → Event Queue → Event Loop → Execution

1. Request comes (e.g., API call)


2. Added to queue
3. Event loop checks if thread is free
4. Executes task

Modules in [Link]

• Core Modules (built-in)


• User-defined modules
• Third-party modules (via npm)

[Link] Use Cases

Web servers
APIs
Real-time apps (chat apps)
Streaming services
Blockchain backend

Limitations

Not ideal for CPU-heavy tasks


Callback complexity (callback hell)
Single-threaded limitations

[Link] in Blockchain

• Smart contract interaction


• Backend APIs
• Web3 integration
What is MetaMask?

MetaMask is a cryptocurrency wallet and browser extension that allows users


to:

• Store Ethereum and tokens


• Interact with decentralized applications (DApps)
• Sign transactions securely

MetaMask acts as a bridge between browser and blockchain

Functions of MetaMask

• Wallet (store crypto assets)


• Identity (user account address)
• Gateway to DApps
• Transaction signer

What is a Wallet in Blockchain?

A wallet is not just storage, it manages:

• Public Key (Address) → visible identity


• Private Key → secret (used to sign transactions)

“Funds are stored on blockchain, not inside wallet—wallet only holds keys.”

Types of Wallets
Type Example Features

Hot Wallet MetaMask Online, easy access

Cold Wallet Hardware wallet Offline, secure

Architecture Flow
User → MetaMask → Web3 Provider → Blockchain (Ethereum)

1. User opens DApp


2. DApp requests wallet connection
3. MetaMask prompts user
4. User approves
5. DApp gets user address
6. Transactions are signed via MetaMask

1. Smart Contract (Deploy in Remix)


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

contract MessageStorage {

string public message;


address public owner;

constructor() {
owner = [Link];
}

function setMessage(string memory _msg) public {


message = _msg;
}

function getMessage() public view returns (string memory) {


return message;
}
}

steps (Remix)
1. Compile contract
2. Deploy using Injected Provider – MetaMask
3. Copy Contract Address
4. Copy ABI

Frontend (HTML + JavaScript)

Save as [Link]

<!DOCTYPE html>
<html>
<head>
<title>Simple DApp</title>
</head>
<body>

<h2>Decentralized Message DApp</h2>

<button onclick="connectWallet()">Connect Wallet</button>


<p id="account"></p>

<input type="text" id="msg" placeholder="Enter message">


<button onclick="setMessage()">Send Message</button>

<p>Stored Message: <span id="storedMsg"></span></p>


<button onclick="getMessage()">Get Message</button>

<script src="[Link]

<script>
let web3;
let contract;
let account;

// Replace with your deployed contract details


const contractAddress = "YOUR_CONTRACT_ADDRESS";
const abi = YOUR_ABI_HERE;

async function connectWallet() {


if ([Link]) {
web3 = new Web3([Link]);

const accounts = await [Link]({


method: 'eth_requestAccounts'
});

account = accounts[0];
[Link]("account").innerText = "Connected: " +
account;

contract = new [Link](abi, contractAddress);


} else {
alert("Install MetaMask");
}
}

// Write to blockchain
async function setMessage() {
const msg = [Link]("msg").value;

await [Link](msg).send({
from: account
});
}

// Read from blockchain


async function getMessage() {
const message = await [Link]().call();
[Link]("storedMsg").innerText = message;
}
</script>

</body>
</html>

Explanation

1. Wallet Connection
eth_requestAccounts

Requests permission from MetaMask


2. Web3 Initialization
web3 = new Web3([Link]);

Connects frontend → blockchain

3. Contract Instance
new [Link](abi, address)

Allows interaction with smart contract

4. Write Operation
.send({ from: account })

Requires:

• Gas
• User confirmation

5. Read Operation
.call()

Free (no gas)

Flow
User → Frontend → MetaMask → Smart Contract → Blockchain

How to Run

1. Deploy contract in Remix


2. Replace:
oYOUR_CONTRACT_ADDRESS
oYOUR_ABI_HERE
3. Open [Link] in browser
4. Connect MetaMask
5. Test:
o Send message
o Retrieve message
Solidity Testing
Testing in Solidity verifies whether a smart contract behaves correctly before deployment.

Need for Testing

• Smart contracts are immutable


• Bugs may cause financial loss
• Ensures security and reliability

Types of Testing
Type Purpose

Unit Testing Tests individual functions

Integration Testing Tests interaction between contracts

Functional Testing Verifies business logic

Security Testing Detects vulnerabilities

Regression Testing Ensures updates do not break old code

Solidity Testing Frameworks


(a) Hardhat

• Most popular framework


• JavaScript-based testing
• Local blockchain support

Install
npm install --save-dev hardhat

(b) Truffle

• Contract compilation
• Testing and deployment support

Install
npm install -g truffle

(c) Foundry

• Fast testing framework


• Supports fuzz testing
Test Nets in Blockchain
A test net is a blockchain network used for:

• Development
• Testing
• Experimentation

without using real cryptocurrency.

Purpose

• Safe smart contract deployment


• Bug detection
• Transaction simulation

Popular Ethereum Test Nets

Sepolia Testnet: Sepolia is the most widely used Ethereum test network today.

Features

• Lightweight
• Fast confirmations
• Developer-friendly
• Supported by MetaMask

Holesky Testnet: Holesky is designed for staking and infrastructure testing.

Features

• Large validator support


• Suitable for infrastructure simulations

Solidity Best Practices


(a) Use Latest Solidity Version

pragma solidity ^0.8.20;


Benefit

• Better security
• Overflow protection

(b) Use Access Control

modifier onlyOwner() {
require([Link] == owner);
_;
}

(c) Validate Inputs

require(amount > 0, "Invalid amount");

(d) Prevent Reentrancy

Follow:

1. Checks
2. Effects
3. Interactions

(e) Emit Events

event Deposit(address user, uint amount);

(f) Optimize Gas Usage

• Minimize storage operations


• Avoid unnecessary loops
• Use memory variables when possible

(g) Use Audited Libraries

OpenZeppelin provides secure reusable smart contracts.

Examples:

• ERC20
• Ownable
• ReentrancyGuard

You might also like