Skip to content

Web3 represents the evolution toward decentralized internet. This guide covers blockchain development fundamentals and smart contracts.

Blockchain Basics

Key Concepts

  • Distributed ledger
  • Consensus mechanisms
  • Immutability
  • Smart contracts
  • Decentralization
  • Ethereum: Smart contract platform
  • Polygon: Layer 2 scaling
  • Solana: High performance
  • Avalanche: Fast finality

Smart Contract Development

Solidity (Ethereum)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleToken {
    mapping(address => uint256) public balances;
    
    function mint(address to, uint256 amount) public {
        balances[to] += amount;
    }
    
    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }
}

Deployment

1
2
3
4
5
6
7
8
9
const { ethers } = require('hardhat');

async function deploy() {
    const Token = await ethers.getContractFactory('SimpleToken');
    const token = await Token.deploy();
    await token.deployed();
    
    console.log('Token deployed to:', token.address);
}

Web3 Integration

ethers.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const { ethers } = require('ethers');

// Connect to provider
const provider = new ethers.providers.Web3Provider(window.ethereum);

// Get signer
const signer = provider.getSigner();

// Contract interaction
const contract = new ethers.Contract(address, abi, signer);
const tx = await contract.transfer(recipient, amount);
await tx.wait();

web3.js

1
2
3
4
5
6
7
8
9
const Web3 = require('web3');
const web3 = new Web3(window.ethereum);

// Request account access
await window.ethereum.request({ method: 'eth_requestAccounts' });

// Send transaction
const accounts = await web3.eth.getAccounts();
await contract.methods.transfer(to, amount).send({ from: accounts[0] });

DApp Architecture

Frontend (React) → Web3.js → MetaMask → Blockchain
                 ↓
              IPFS (Storage)

Example DApp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useState, useEffect } from 'react';
import { ethers } from 'ethers';

function App() {
    const [account, setAccount] = useState('');
    const [contract, setContract] = useState(null);
    
    useEffect(() => {
        async function init() {
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            await provider.send("eth_requestAccounts", []);
            const signer = provider.getSigner();
            const address = await signer.getAddress();
            setAccount(address);
            
            const contract = new ethers.Contract(
                CONTRACT_ADDRESS,
                ABI,
                signer
            );
            setContract(contract);
        }
        init();
    }, []);
    
    async function handleTransfer() {
        const tx = await contract.transfer(recipient, amount);
        await tx.wait();
        alert('Transfer successful!');
    }
    
    return <button onClick={handleTransfer}>Transfer</button>;
}

Testing

Hardhat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const { expect } = require('chai');

describe('Token', function() {
    it('Should mint tokens', async function() {
        const Token = await ethers.getContractFactory('SimpleToken');
        const token = await Token.deploy();
        
        await token.mint(addr1.address, 100);
        expect(await token.balances(addr1.address)).to.equal(100);
    });
});

Security

Common Vulnerabilities

  • Reentrancy
  • Integer overflow/underflow
  • Front-running
  • Access control issues

OpenZeppelin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyToken is ERC20, Ownable {
    constructor() ERC20("MyToken", "MTK") {
        _mint(msg.sender, 1000000 * 10 ** decimals());
    }
    
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}

NFTs

ERC-721

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MyNFT is ERC721 {
    uint256 private _tokenIds;
    
    constructor() ERC721("MyNFT", "NFT") {}
    
    function mintNFT(address recipient, string memory tokenURI)
        public
        returns (uint256)
    {
        _tokenIds++;
        _mint(recipient, _tokenIds);
        _setTokenURI(_tokenIds, tokenURI);
        return _tokenIds;
    }
}

Gas Optimization

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// ❌ Expensive
for (uint i = 0; i < array.length; i++) {
    total += array[i];
}

// ✅ Optimized
uint length = array.length;
for (uint i = 0; i < length; i++) {
    total += array[i];
}

Best Practices

  1. Audit smart contracts
  2. Use established libraries
  3. Test extensively
  4. Minimize gas usage
  5. Implement access controls
  6. Monitor transactions
  7. Plan for upgrades

Tools

  • Hardhat: Development environment
  • Truffle: Framework
  • Remix: Online IDE
  • MetaMask: Wallet
  • Etherscan: Block explorer
  • OpenZeppelin: Security

Conclusion

Web3 development requires understanding both blockchain technology and traditional web development. Start with testnets and gradually build expertise.