DEV Community

Cover image for Blockchain Beginner Documentation
Dependra Basnet
Dependra Basnet

Posted on

Blockchain Beginner Documentation

Complete Documentation: Blockchain and Cryptocurrency Terms with Examples in JavaScript

This documentation provides a comprehensive glossary of commonly used blockchain and cryptocurrency terms, complete with definitions, examples, and JavaScript code.


1.Blockchain

Definition:

A decentralized, distributed ledger that records transactions across a network of computers.

Example:

Bitcoin's blockchain records all BTC transactions in blocks, chained together chronologically.

Code Example:

class Block {
    constructor(index, previousHash, data, timestamp) {
        this.index = index;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = timestamp;
        this.hash = this.calculateHash();
    }

    calculateHash() {
        const crypto = require('crypto');
        return crypto.createHash('sha256')
            .update(this.index + this.previousHash + this.data + this.timestamp)
            .digest('hex');
    }
}

const blockchain = [new Block(0, "0", "Genesis Block", 1637836800)];
console.log(blockchain);
Enter fullscreen mode Exit fullscreen mode

2. Vesting

Definition:

A process where crypto tokens are distributed to stakeholders over a defined schedule.

Example:

A team member might receive 25% of their tokens after one year and the remaining 75% over the next three years.

Code Example:

function calculateVestedTokens(totalTokens, vestingPeriodYears, yearElapsed) {
    return (totalTokens / vestingPeriodYears) * yearElapsed;
}

const totalTokens = 1000;
const vestingPeriodYears = 4;
const yearElapsed = 2;

console.log(calculateVestedTokens(totalTokens, vestingPeriodYears, yearElapsed)); // Output: 500
Enter fullscreen mode Exit fullscreen mode

3. Halving

Definition:

An event where the reward for mining a block is halved, reducing the rate at which new coins are created.

Example:

Bitcoin’s halving occurs roughly every 4 years. In 2020, the mining reward was reduced from 12.5 BTC to 6.25 BTC.

Code Example:

function calculateReward(initialReward, halvings) {
    return initialReward / Math.pow(2, halvings);
}

console.log(calculateReward(50, 3)); // Output: 6.25
Enter fullscreen mode Exit fullscreen mode

4. Proof of Work (PoW)

Definition:

A consensus mechanism requiring miners to solve computational puzzles to validate transactions.

Example:

Bitcoin uses PoW to secure its blockchain.

Code Example:

const crypto = require('crypto');

function proofOfWork(blockData, difficulty) {
    const prefix = '0'.repeat(difficulty);
    let nonce = 0;

    while (true) {
        const hash = crypto.createHash('sha256')
            .update(blockData + nonce)
            .digest('hex');

        if (hash.startsWith(prefix)) {
            return { nonce, hash };
        }
        nonce++;
    }
}

console.log(proofOfWork("block_data", 4));
Enter fullscreen mode Exit fullscreen mode

5. Proof of Stake (PoS)

Definition:

A consensus mechanism where validators are chosen based on their stake in the network.

Example:

Ethereum transitioned to PoS in 2022, reducing energy usage significantly.

Code Example:

function selectValidator(stakes) {
    const totalStake = Object.values(stakes).reduce((sum, stake) => sum + stake, 0);
    const rand = Math.random() * totalStake;
    let cumulative = 0;

    for (const [validator, stake] of Object.entries(stakes)) {
        cumulative += stake;
        if (rand <= cumulative) {
            return validator;
        }
    }
}

const stakes = { Validator1: 100, Validator2: 200, Validator3: 300 };
console.log(selectValidator(stakes));
Enter fullscreen mode Exit fullscreen mode

6. Staking

Definition:

Locking up cryptocurrency in a wallet to support the network and earn rewards.

Example:

Users stake ETH to become validators in Ethereum's PoS system.

Code Example:

function calculateStakingRewards(stakeAmount, annualYield, durationYears) {
    return stakeAmount * Math.pow(1 + annualYield, durationYears) - stakeAmount;
}

console.log(calculateStakingRewards(1000, 0.1, 3)); // Output: 331.00
Enter fullscreen mode Exit fullscreen mode

7. Mining

Definition:

The process of validating blockchain transactions and earning rewards in return.

Example:

Bitcoin miners use hardware like ASICs to solve mathematical puzzles.

Code Example:

const crypto = require('crypto');

function mineBlock(data, previousHash) {
    const block = {
        data: data,
        previousHash: previousHash,
        hash: crypto.createHash('sha256')
            .update(data + previousHash)
            .digest('hex')
    };
    return block;
}

const minedBlock = mineBlock("transaction_data", "0000abc123");
console.log(minedBlock);
Enter fullscreen mode Exit fullscreen mode

8. Gas Fees

Definition:

Transaction fees paid to miners or validators for processing transactions.

Example:

On Ethereum, users pay gas fees in ETH to execute smart contracts.

Code Example:

function calculateGasFee(gasPrice, gasUsed) {
    return gasPrice * gasUsed;
}

console.log(calculateGasFee(50, 21000)); // Output: 105000 Gwei
Enter fullscreen mode Exit fullscreen mode

9. Decentralized Exchange (DEX)

Definition:

A peer-to-peer platform for trading cryptocurrencies directly between users, without an intermediary. Trades are executed using smart contracts.

Example:

Uniswap is a popular DEX for decentralized token swapping.

Code Example:

class DecentralizedExchange {
    constructor(reserveA, reserveB) {
        this.reserveA = reserveA;
        this.reserveB = reserveB;
    }

    getPrice(inputAmount, inputReserve, outputReserve) {
        return (inputAmount * outputReserve) / (inputReserve + inputAmount);
    }

    swap(inputToken, inputAmount) {
        let outputAmount;
        if (inputToken === "A") {
            outputAmount = this.getPrice(inputAmount, this.reserveA, this.reserveB);
            this.reserveA += inputAmount;
            this.reserveB -= outputAmount;
        } else if (inputToken === "B") {
            outputAmount = this.getPrice(inputAmount, this.reserveB, this.reserveA);
            this.reserveB += inputAmount;
            this.reserveA -= outputAmount;
        } else {
            throw new Error("Invalid token type");
        }
        return outputAmount;
    }
}

const dex = new DecentralizedExchange(1000, 2000);
console.log("Swap 10 Token A for Token B:", dex.swap("A", 10));
console.log("Swap 20 Token B for Token A:", dex.swap("B", 20));
Enter fullscreen mode Exit fullscreen mode

10. Centralized Exchange (CEX)

Definition:

A cryptocurrency trading platform operated by a central authority or company.

Example:

Binance, Coinbase, and Kraken are examples of centralized exchanges.

Code Example:

class CentralizedExchange {
    constructor() {
        this.orderBook = { buy: [], sell: [] };
    }

    placeOrder(type, amount, price) {
        const order = { amount, price };
        this.orderBook[type].push(order);
        this.matchOrders();
    }

    matchOrders() {
        this.orderBook.buy.sort((a, b) => b.price - a.price);
        this.orderBook.sell.sort((a, b) => a.price - b.price);

        while (
            this.orderBook.buy.length > 0 &&
            this.orderBook.sell.length > 0 &&
            this.orderBook.buy[0].price >= this.orderBook.sell[0].price
        ) {
            const buyOrder = this.orderBook.buy.shift();
            const sellOrder = this.orderBook.sell.shift();
            const tradedAmount = Math.min(buyOrder.amount, sellOrder.amount);
            const tradePrice = sellOrder.price;

            console.log(`Trade executed: ${tradedAmount} units at price ${tradePrice}`);

            if (buyOrder.amount > tradedAmount) {
                buyOrder.amount -= tradedAmount;
                this.orderBook.buy.unshift(buyOrder);
            }

            if (sellOrder.amount > tradedAmount) {
                sellOrder.amount -= tradedAmount;
                this.orderBook.sell.unshift(sellOrder);
            }
        }
    }
}

const exchange = new CentralizedExchange();
exchange.placeOrder("buy", 10, 50000);
exchange.placeOrder("sell", 10, 49000);
Enter fullscreen mode Exit fullscreen mode

This documentation includes:

  • Definitions of blockchain and cryptocurrency terms.
  • Examples demonstrating real-world usage.
  • JavaScript Code Snippets implementing concepts for developers.

This serves as a complete reference guide for blockchain developers and enthusiasts.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more