Blockchain ve Web3 Teknolojilerine Giriş

Teknoloji 📖 4 dk okuma
#web#yapay zeka#kariyer

Blockchain ve Web3, internetin yeni nesli: decentralized, trustless, transparent.

Blockchain Temelleri

Block Structure

Block #1                Block #2                Block #3
┌─────────────┐        ┌─────────────┐        ┌─────────────┐
│ Hash:  ABC  │        │ Hash:  DEF  │        │ Hash:  GHI  │
│ Prev:  000  │───────▶│ Prev:  ABC  │───────▶│ Prev:  DEF  │
│ Data:  ...  │        │ Data:  ...  │        │ Data:  ...  │
│ Nonce: 123  │        │ Nonce: 456  │        │ Nonce: 789  │
└─────────────┘        └─────────────┘        └─────────────┘

Simple Blockchain (JavaScript)

const crypto = require('crypto');

class Block {
  constructor(index, timestamp, data, previousHash = '') {
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.previousHash = previousHash;
    this.nonce = 0;
    this.hash = this.calculateHash();
  }
  
  calculateHash() {
    return crypto
      .createHash('sha256')
      .update(
        this.index +
        this.previousHash +
        this.timestamp +
        JSON.stringify(this.data) +
        this.nonce
      )
      .digest('hex');
  }
  
  mineBlock(difficulty) {
    while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
      this.nonce++;
      this.hash = this.calculateHash();
    }
    console.log(`Block mined: ${this.hash}`);
  }
}

class Blockchain {
  constructor() {
    this.chain = [this.createGenesisBlock()];
    this.difficulty = 4;
  }
  
  createGenesisBlock() {
    return new Block(0, Date.now(), 'Genesis Block', '0');
  }
  
  getLatestBlock() {
    return this.chain[this.chain.length - 1];
  }
  
  addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.mineBlock(this.difficulty);
    this.chain.push(newBlock);
  }
  
  isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const currentBlock = this.chain[i];
      const previousBlock = this.chain[i - 1];
      
      if (currentBlock.hash !== currentBlock.calculateHash()) {
        return false;
      }
      
      if (currentBlock.previousHash !== previousBlock.hash) {
        return false;
      }
    }
    return true;
  }
}

// Usage
const blockchain = new Blockchain();
blockchain.addBlock(new Block(1, Date.now(), { amount: 100 }));
blockchain.addBlock(new Block(2, Date.now(), { amount: 200 }));

console.log('Valid:', blockchain.isChainValid());

Smart Contracts (Solidity)

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

contract SimpleToken {
    string public name = "MyToken";
    string public symbol = "MTK";
    uint256 public totalSupply;
    
    mapping(address => uint256) public balanceOf;
    
    event Transfer(address indexed from, address indexed to, uint256 value);
    
    constructor(uint256 _initialSupply) {
        totalSupply = _initialSupply;
        balanceOf[msg.sender] = _initialSupply;
    }
    
    function transfer(address _to, uint256 _value) public returns (bool) {
        require(balanceOf[msg.sender] >= _value, "Insufficient balance");
        require(_to != address(0), "Invalid address");
        
        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        
        emit Transfer(msg.sender, _to, _value);
        return true;
    }
}

Web3.js ile Interaction

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

// Get account balance
async function getBalance(address) {
  const balance = await web3.eth.getBalance(address);
  return web3.utils.fromWei(balance, 'ether');
}

// Send transaction
async function sendEther(from, to, amount, privateKey) {
  const nonce = await web3.eth.getTransactionCount(from);
  
  const tx = {
    from,
    to,
    value: web3.utils.toWei(amount, 'ether'),
    gas: 21000,
    nonce
  };
  
  const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);
  const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
  
  return receipt;
}

// Interact with contract
const contractABI = [...]; // Contract ABI
const contractAddress = '0x...';
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Read from contract
const balance = await contract.methods.balanceOf(address).call();

// Write to contract
const tx = contract.methods.transfer(toAddress, amount);
const receipt = await tx.send({ from: fromAddress });

Ethers.js (Modern alternative)

const { ethers } = require('ethers');

// Connect to provider
const provider = new ethers.providers.JsonRpcProvider('http://localhost:8545');

// Create wallet
const wallet = new ethers.Wallet(privateKey, provider);

// Contract interaction
const contract = new ethers.Contract(address, abi, wallet);

// Read
const balance = await contract.balanceOf(address);
console.log(ethers.utils.formatEther(balance));

// Write
const tx = await contract.transfer(toAddress, amount);
await tx.wait(); // Wait for confirmation

NFT (ERC-721) Example

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

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyNFT is ERC721, Ownable {
    uint256 public tokenCounter;
    
    mapping(uint256 => string) private _tokenURIs;
    
    constructor() ERC721("MyNFT", "MNFT") {
        tokenCounter = 0;
    }
    
    function createNFT(string memory tokenURI) public onlyOwner returns (uint256) {
        uint256 newTokenId = tokenCounter;
        _safeMint(msg.sender, newTokenId);
        _tokenURIs[newTokenId] = tokenURI;
        tokenCounter++;
        return newTokenId;
    }
    
    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "Token does not exist");
        return _tokenURIs[tokenId];
    }
}

DApp Architecture

Frontend (React)

  Web3.js/Ethers.js

Ethereum Node (Infura/Alchemy)

Smart Contracts

Blockchain

IPFS Integration

const { create } = require('ipfs-http-client');

const ipfs = create({ url: 'https://ipfs.infura.io:5001' });

// Upload file
async function uploadToIPFS(file) {
  const added = await ipfs.add(file);
  return `https://ipfs.io/ipfs/${added.path}`;
}

// Retrieve file
async function getFromIPFS(hash) {
  const chunks = [];
  for await (const chunk of ipfs.cat(hash)) {
    chunks.push(chunk);
  }
  return Buffer.concat(chunks);
}

Decentralized Identity

// DID (Decentralized Identifier)
const did = 'did:ethr:0x1234...';

// Verifiable Credential
const credential = {
  '@context': ['https://www.w3.org/2018/credentials/v1'],
  type: ['VerifiableCredential'],
  issuer: 'did:ethr:0xabcd...',
  issuanceDate: '2024-01-01T00:00:00Z',
  credentialSubject: {
    id: 'did:ethr:0x1234...',
    name: 'John Doe',
    degree: 'Bachelor of Science'
  }
};

Web3 ile decentralized future’ı inşa edin!