Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions docs/learn/blockchain-basics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Blockchain Basics

This guide introduces fundamental blockchain concepts for newcomers. If you're already familiar with blockchain technology, skip to [XDC Architecture](xdc-architecture.md).
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, understand the docs directory structure
find . -type d -name docs | head -5

Repository: XinFinOrg/Docs

Length of output: 64


🏁 Script executed:

# List files in the docs directory to understand structure
fd -t f -E node_modules -E .git -E dist -E build -E site -E public -E .venv '\.md$' docs | head -20

Repository: XinFinOrg/Docs

Length of output: 697


🏁 Script executed:

# Read the blockchain-basics.md file
cat -n docs/learn/blockchain-basics.md 2>/dev/null || echo "File not found, trying alternative path"

Repository: XinFinOrg/Docs

Length of output: 6422


🏁 Script executed:

# Run the verification script from the review comment
fd -t f -E node_modules -E .git -E dist -E build -E site -E public -E .venv \
  '^(xdpos-explained|faq|tokenomics|security)\.md$'

Repository: XinFinOrg/Docs

Length of output: 90


Fix broken internal documentation links.
The following relative links in docs/learn/blockchain-basics.md are broken:

  • Line 85, 166: xdpos-explained.md does not exist in the docs tree
  • Line 172: faq.md does not exist in docs/learn/; the FAQ file is located at docs/subnet/install_guide/faq.md

Links to xdc-architecture.md (lines 3, 165) and gas-fees.md (line 167) are correct. Update the broken links to point to valid file paths or create the missing documentation files.

🤖 Prompt for AI Agents
In `@docs/learn/blockchain-basics.md` at line 3, In
docs/learn/blockchain-basics.md replace the broken relative links: for the two
occurrences of "xdpos-explained.md" (currently referenced on lines noted in the
review) either point them to a valid existing document or create a new
docs/learn/xdpos-explained.md file and update the links to that path; also
update the FAQ link to the correct path docs/subnet/install_guide/faq.md
(replace the current "faq.md" under docs/learn/), keeping the working links to
xdc-architecture.md and gas-fees.md unchanged.


## What is Blockchain?

A blockchain is a **distributed digital ledger** that records transactions across many computers. Think of it as a shared spreadsheet that:

- Everyone can read
- No single person controls
- Cannot be altered once written
- Automatically stays synchronized

```mermaid
flowchart LR
A[Transaction] --> B[Verification]
B --> C[Block Created]
C --> D[Added to Chain]
D --> E[Distributed to Network]
```

## Key Concepts

### 1. Decentralization

Instead of one central server (like a bank), blockchain uses many computers (nodes) worldwide:

| Centralized | Decentralized |
|-------------|---------------|
| Single point of failure | No single point of failure |
| Trust the institution | Trust the protocol |
| Can be censored | Censorship resistant |
| Institution controls data | Users control data |

### 2. Blocks

Transactions are grouped into **blocks**. Each block contains:

- **Transactions**: The actual data being recorded
- **Timestamp**: When the block was created
- **Previous Block Hash**: Links to the prior block
- **Block Hash**: Unique identifier for this block

```
┌─────────────────────────────────┐
│ Block #100 │
├─────────────────────────────────┤
│ Previous Hash: 0x7a8b... │
│ Timestamp: 2024-01-27 10:00:00 │
│ Transactions: │
│ - Alice → Bob: 10 XDC │
│ - Carol → Dave: 5 XDC │
│ Block Hash: 0x9f3c... │
└─────────────────────────────────┘
┌─────────────────────────────────┐
│ Block #101 │
├─────────────────────────────────┤
│ Previous Hash: 0x9f3c... │
│ ... │
└─────────────────────────────────┘
```

### 3. Cryptographic Hashing

A **hash** is a unique fingerprint of data. Even a tiny change creates a completely different hash:

```
"Hello World" → 0x7f83b...
"Hello World!" → 0x5d41a... (completely different!)
```

This makes tampering detectable—changing any transaction would change all subsequent hashes.

### 4. Consensus

How do all nodes agree on the "true" state of the blockchain? Through **consensus mechanisms**:

| Mechanism | How It Works | Example |
|-----------|--------------|---------|
| Proof of Work (PoW) | Solve complex puzzles | Bitcoin |
| Proof of Stake (PoS) | Stake tokens as collateral | Ethereum |
| Delegated PoS (DPoS) | Elected validators | XDC Network |

XDC uses **XDPoS** (XinFin Delegated Proof of Stake) - more on this in [XDPoS Explained](xdpos-explained.md).

### 5. Smart Contracts

**Smart contracts** are programs that run on the blockchain. They:

- Execute automatically when conditions are met
- Cannot be changed once deployed
- Are transparent and verifiable

Example: An escrow smart contract that automatically releases payment when goods are delivered.

```solidity
// Simple smart contract example
contract Escrow {
address buyer;
address seller;

function releaseFunds() public {
require(goodsDelivered == true);
seller.transfer(amount);
}
}
```

### 6. Wallets & Addresses

A **wallet** stores your private keys. An **address** is your public identifier (like an email address for crypto):

- **Private Key**: Secret! Never share. Used to sign transactions.
- **Public Key**: Derived from private key.
- **Address**: Derived from public key. Safe to share.

```
Private Key → Public Key → Address
(secret) (derived) (share this)

XDC Address Example: xdc71C7656EC7ab88b098defB751B7401B5f6d8976F
```

## Types of Blockchains

### Public Blockchains
- Anyone can participate
- Fully transparent
- Examples: Bitcoin, Ethereum, XDC Mainnet

### Private Blockchains
- Permissioned access
- Controlled by organization
- Examples: XDC Private Subnets

### Consortium Blockchains
- Multiple organizations share control
- Semi-private
- Example: Trade finance networks on XDC

## Why XDC Network?

XDC Network combines the best of both worlds:

| Feature | Benefit |
|---------|---------|
| **Hybrid Architecture** | Public transparency + private options |
| **Enterprise Focus** | Built for trade finance and business |
| **EVM Compatible** | Use existing Ethereum tools |
| **Fast & Cheap** | 2s blocks, < $0.0001 fees |
| **Energy Efficient** | PoS uses 99.9% less energy than PoW |

## Getting Started

Ready to explore XDC Network?

1. **Get a Wallet**: [Set up XDCPay](../xdcchain/developers/wallet-configuration.md)
2. **Get Test XDC**: [Faucet](https://faucet.blocksscan.io)
3. **Explore**: [Block Explorer](https://xdc.blocksscan.io)
4. **Build**: [Developer Quick Start](../xdcchain/developers/quick-guide.md)

## Next Steps

- [XDC Architecture](xdc-architecture.md) - Deep dive into XDC's design
- [XDPoS Consensus](xdpos-explained.md) - How XDC achieves consensus
- [Gas & Fees](gas-fees.md) - Understanding transaction costs

---

!!! question "Still have questions?"
Check our [FAQ](faq.md) or ask in [Discord](https://discord.gg/xdc).
222 changes: 222 additions & 0 deletions docs/learn/gas-fees.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
# Gas & Fees on XDC Network

Understanding how transaction fees work on XDC Network.

## Overview

XDC Network uses a **gas model** similar to Ethereum, but with significantly lower costs. Gas is a unit measuring the computational effort required to execute transactions.

## Key Concepts

### Gas vs Gas Price vs Transaction Fee

```
Transaction Fee = Gas Used × Gas Price
```

| Term | Description | Example |
|------|-------------|---------|
| **Gas** | Computational units required | 21,000 (simple transfer) |
| **Gas Price** | Cost per gas unit (in Gwei) | 0.25 Gwei |
| **Gas Limit** | Max gas you're willing to spend | 100,000 |
| **Transaction Fee** | Actual cost in XDC | 0.00000525 XDC |

## XDC Network Fee Advantages

| Metric | XDC Network | Ethereum | Savings |
|--------|-------------|----------|---------|
| Avg Gas Price | 0.25 Gwei | 20-100 Gwei | 80-400x cheaper |
| Simple Transfer | ~$0.00004 | $1-5 | 99%+ |
| Token Transfer | ~$0.0001 | $5-20 | 99%+ |
| Contract Deploy | ~$0.01-0.10 | $50-500 | 99%+ |

Comment on lines +26 to +32
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# First, read the entire gas-fees.md file to see all the tables mentioned
cat docs/learn/gas-fees.md

Repository: XinFinOrg/Docs

Length of output: 6200


🏁 Script executed:

# Check for any date references or version info in the file
head -20 docs/learn/gas-fees.md | grep -i "date\|version\|updated\|as of"

# Also check the Git history to see when this file was last modified
git log --oneline -5 docs/learn/gas-fees.md

Repository: XinFinOrg/Docs

Length of output: 118


🌐 Web query:

XDC Network current gas price 2025 2026 Blocksscan gastracker

💡 Result:

  • BlocksScan “Gas Tracker / Gas Oracle” status (2025–2026): BlocksScan’s docs show module=gastracker is WIP, and the Gas Oracle (Safe/Proposed/Fast) endpoint is listed as “Coming Soon” (i.e., not an available “current gas price” feed from Blocksscan yet). [1]
  • What XDC users commonly see as the network gas price post-upgrade: A XinFin/XDC developer forum post describing the XDC 2.0-related change reports gas moving from 0.25 Gwei (pre-upgrade) to 12.5 Gwei (post-upgrade). [2]
  • How to get the current gas price instead (reliable in 2025–2026): Query the chain via JSON-RPC eth_gasPrice (returns gas price in wei) using any XDC RPC provider/node. The XDC docs list eth_gasPrice for this purpose. [3] BlocksScan also documents an XDCScan API “proxy” style eth_gasPrice endpoint (WIP). [4]

Sources: [1] (docs.blocksscan.io) [2] (xdc.dev) [3] (docs.xdc.network) [4] (docs.blocksscan.io)

Citations:


🌐 Web query:

XDC Network TPS throughput current specifications 2025

💡 Result:

XDC Network throughput (current published specs, 2025):

  • Transactions per second (TPS): 2,000+ TPS (claimed/spec) on XDC 2.0. [1]
  • Docs throughput statement:high throughput of 2,000 TPS” (docs wording). [2]
  • Finality / block timing (XDC 2.0): After the September 2024 consensus upgrade, XDC states ~2-second block time and 3-block finality (~6 seconds). [3]
  • Note on conflicting spec pages: One official comparison table still lists 10s block time and 30s finalization for XDC 2.0, which conflicts with the 2s/6s figures above. [1]

Sources: [1] [2] [3]


Update all cost/fee comparisons and add dates—gas prices changed significantly with XDC 2.0.

The gas prices and fees in this document (lines 26–32, 62–67, 201–209) are outdated. XDC Network upgraded to XDC 2.0 in September 2024, which changed the standard gas price from 0.25 Gwei to 12.5 Gwei. This means all cost figures (e.g., ~$0.00004 per transfer) are now approximately 50× too low.

Additionally, the reference to BlocksScan Gas Tracker for checking current prices is not yet functional (marked as "Coming Soon" in Blocksscan's docs). Add "as of " timestamps or cite specific sources (e.g., XDC RPC eth_gasPrice endpoint) to help users find accurate, current values. The TPS (2,000+) and block time (2s) claims are correct for XDC 2.0.

🤖 Prompt for AI Agents
In `@docs/learn/gas-fees.md` around lines 26 - 32, Update the outdated XDC fee
figures and add timestamps/sources: replace the Avg Gas Price value "0.25 Gwei"
with "12.5 Gwei" (XDC 2.0) and scale the per-operation cost estimates (Simple
Transfer, Token Transfer, Contract Deploy) roughly 50× higher from the current
table values, adjust the "Savings" ratios accordingly, and propagate the same
corrections for the other occurrences noted (lines ~62–67 and ~201–209). Add an
"as of <date>" timestamp next to the gas-price numbers and a source note
pointing users to the XDC RPC eth_gasPrice endpoint (or live RPC) rather than
BlocksScan (flagged as "Coming Soon"). Ensure mentions of XDC 2.0 are explicit
near the updated metrics and keep the table headers "Avg Gas Price", "Simple
Transfer", "Token Transfer", and "Contract Deploy" intact so reviewers can
locate and verify the changes.

## Gas Costs by Operation

### Common Operations

| Operation | Gas Used | Cost (0.25 Gwei) |
|-----------|----------|------------------|
| XDC Transfer | 21,000 | ~$0.00004 |
| XRC20 Transfer | 65,000 | ~$0.00012 |
| XRC20 Approve | 45,000 | ~$0.00008 |
| NFT Transfer | 85,000 | ~$0.00015 |
| Contract Deploy | 500,000-3,000,000 | ~$0.001-0.05 |
| Swap (DEX) | 150,000-300,000 | ~$0.0003-0.0006 |

### EVM Opcode Costs

| Opcode | Gas | Description |
|--------|-----|-------------|
| ADD | 3 | Addition |
| MUL | 5 | Multiplication |
| SSTORE (new) | 20,000 | Store new value |
| SSTORE (update) | 5,000 | Update existing value |
| SLOAD | 800 | Load from storage |
| CALL | 700+ | External contract call |
| CREATE | 32,000 | Deploy contract |

## Setting Gas Price

### Recommended Gas Prices

| Speed | Gas Price | Confirmation |
|-------|-----------|--------------|
| 🐢 Low | 0.1 Gwei | ~30 seconds |
| 🚶 Standard | 0.25 Gwei | ~2-4 seconds |
| 🏃 Fast | 0.5 Gwei | ~2 seconds |

### In Code

=== "JavaScript (Web3.js)"
```javascript
const Xdc3 = require('xdc3');
const xdc3 = new Xdc3('https://rpc.xinfin.network');

// Get current gas price
const gasPrice = await xdc3.eth.getGasPrice();
console.log('Current gas price:', xdc3.utils.fromWei(gasPrice, 'gwei'), 'Gwei');

// Send transaction with custom gas price
const tx = await xdc3.eth.sendTransaction({
from: '0x...',
to: '0x...',
value: xdc3.utils.toWei('1', 'ether'),
gasPrice: xdc3.utils.toWei('0.25', 'gwei'),
gas: 21000
});
```

=== "JavaScript (Ethers.js)"
```javascript
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('https://rpc.xinfin.network');

// Get fee data
const feeData = await provider.getFeeData();
console.log('Gas Price:', ethers.formatUnits(feeData.gasPrice, 'gwei'), 'Gwei');

// Send transaction
const tx = await wallet.sendTransaction({
to: '0x...',
value: ethers.parseEther('1'),
gasPrice: ethers.parseUnits('0.25', 'gwei')
});
```

## Estimating Gas

Always estimate gas before sending transactions:

```javascript
// Estimate gas for a transaction
const gasEstimate = await xdc3.eth.estimateGas({
from: '0x...',
to: contractAddress,
data: contract.methods.transfer(recipient, amount).encodeABI()
});

// Add 20% buffer for safety
const gasLimit = Math.ceil(gasEstimate * 1.2);

console.log('Estimated gas:', gasEstimate);
console.log('Gas limit (with buffer):', gasLimit);
```

## Gas Optimization Tips

### For Users

1. **Set appropriate gas price**: 0.25 Gwei is usually sufficient
2. **Don't overpay**: XDC has consistent low fees
3. **Batch transactions**: Combine multiple operations when possible
4. **Off-peak times**: Fees are consistently low, but network is fastest during low activity

### For Developers

1. **Minimize storage writes**
```solidity
// Bad: Multiple storage writes
balances[user] = balances[user] + amount;
totalSupply = totalSupply + amount;

// Good: Batch operations
function batchUpdate(address user, uint256 amount) internal {
balances[user] += amount;
totalSupply += amount;
}
```

2. **Use events instead of storage for historical data**
```solidity
// Instead of storing all historical values
event Transfer(address indexed from, address indexed to, uint256 value);
```

3. **Pack storage variables**
```solidity
// Bad: Uses 3 storage slots
uint256 a;
uint256 b;
uint256 c;

// Good: Pack into fewer slots
uint128 a;
uint128 b;
uint256 c; // 2 slots total
```

4. **Use `calldata` for read-only function parameters**
```solidity
// Bad
function process(string memory data) public { }

// Good
function process(string calldata data) public { }
```

## Failed Transactions

If a transaction fails:

- Gas used up to the failure point is **still charged**
- Set appropriate gas limits to minimize losses
- Common failure reasons:
- Out of gas
- Contract revert
- Invalid parameters

```javascript
try {
const tx = await contract.methods.riskyOperation().send({
from: account,
gas: 500000,
gasPrice: xdc3.utils.toWei('0.25', 'gwei')
});
} catch (error) {
console.log('Transaction failed:', error.message);
// Gas is still consumed up to failure point
}
```

## Network Comparison

| Network | Avg Tx Fee | TPS | Block Time |
|---------|-----------|-----|------------|
| **XDC Network** | **~$0.00004** | **2,000+** | **2s** |
| Ethereum | $1-50+ | 15-30 | 12s |
| Polygon | ~$0.01 | 7,000 | 2s |
| BSC | ~$0.10 | 160 | 3s |
| Solana | ~$0.00025 | 65,000 | 0.4s |

## Summary

- XDC Network offers **99%+ cheaper** fees than Ethereum
- Standard gas price: **0.25 Gwei**
- Simple transfer: **~$0.00004**
- Always estimate gas before sending
- Optimize contracts to minimize gas usage

---

!!! tip "Calculate Your Costs"
Use the [XDC Gas Station](https://xdc.blocksscan.io/gastracker) to check current network gas prices.
Loading