diff --git a/website/docs/xdcchain/devops/runbooks/index.md b/website/docs/xdcchain/devops/runbooks/index.md new file mode 100644 index 00000000..456b87ad --- /dev/null +++ b/website/docs/xdcchain/devops/runbooks/index.md @@ -0,0 +1,632 @@ +--- +title: "Incident Response Runbooks for Node Operators +description: Step-by-step runbooks for diagnosing and resolving common XDC node failures, network issues, and security incidents." +--- + +# Incident Response Runbooks for Node Operators + +These runbooks provide structured procedures for diagnosing and resolving common incidents affecting XDC Network nodes. Each runbook includes symptoms, diagnostic commands, resolution steps, and escalation criteria. + +## Severity Classification + +| Severity | Impact | Response Time | Examples | +|----------|--------|---------------|----------| +| P1 - Critical | Node down, missed blocks, potential slashing | 15 minutes | Sync failure, disk full, key compromise | +| P2 - High | Degraded performance, partial functionality | 1 hour | High memory, slow sync, low peers | +| P3 - Medium | Non-critical issues, monitoring alerts | 4 hours | Log errors, minor config issues | +| P4 - Low | Cosmetic, informational | 24 hours | Log warnings, metric anomalies | + +--- + +## Runbook 1: Node Not Syncing + +**Severity:** P1 - Critical +**Symptoms:** +- `eth.syncing` returns object with `currentBlock` far behind `highestBlock` +- Block height not increasing +- Peer count is zero or very low + +### Diagnostic Steps + +```bash +# 1. Check sync status +bash xdc-attach.sh +> eth.syncing + +# Expected: false (synced) or object with currentBlock close to highestBlock +# Problem: currentBlock stuck or very far behind + +# 2. Check peer count +> net.peerCount + +# Expected: 10+ peers +# Problem: 0-2 peers + +# 3. Check network connectivity +curl -s http://localhost:8545 -X POST \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","method":"net_listening","params":[],"id":1}' + +# Expected: {"jsonrpc":"2.0","id":1,"result":true} +# Problem: result is false or connection refused + +# 4. Check logs +docker-compose logs --tail=100 | grep -i "peer\|sync\|error" +``` + +### Resolution + +**If peer count is 0:** + +```bash +# Check firewall rules +sudo ufw status +# Ensure port 30303/tcp and 30303/udp are open + +# Check if nodekey exists +ls -la xdcchain/XDC/nodekey +# If missing, restart node to generate new one + +# Manually add bootnodes +# Edit .env and add bootnode addresses +``` + +**If sync is stuck:** + +```bash +# Restart node +bash docker-down.sh +bash docker-up.sh + +# If still stuck, reset sync +bash docker-down.sh +rm -rf xdcchain/XDC/geth/chaindata +bash docker-up.sh +``` + +**If behind by many blocks:** + +```bash +# Download snapshot for faster sync +bash docker-down.sh +rm -rf xdcchain/XDC +wget https://download.xinfin.network/xdcchain.tar +tar -xvzf xdcchain.tar +bash docker-up.sh +``` + +### Escalation + +Escalate if: +- Node not syncing after 2 restart attempts +- Peer count remains 0 after firewall verification +- Sync gap increases over time instead of decreasing + +--- + +## Runbook 2: Disk Space Full + +**Severity:** P1 - Critical +**Symptoms:** +- "No space left on device" errors in logs +- Node crashes or becomes unresponsive +- Monitoring alert: disk usage > 90% + +### Diagnostic Steps + +```bash +# 1. Check disk usage +df -h + +# 2. Check chain data size +du -sh xdcchain/XDC/ +du -sh xdcchain/XDC/geth/chaindata + +# 3. Check log size +du -sh xdcchain/logs/ 2>/dev/null || echo "No logs directory" + +# 4. Find largest files +find xdcchain/ -type f -exec du -h {} + | sort -rh | head -20 +``` + +### Resolution + +**Immediate (buy time):** + +```bash +# Clean up old logs +find xdcchain/logs -type f -mtime +7 -delete 2>/dev/null + +# Remove temporary files +rm -f xdcchain/XDC/*.tmp +rm -f xdcchain/XDC/transactions.rlp +``` + +**Short-term (expand storage):** + +```bash +# If using LVM +sudo lvextend -L +500G /dev/mapper/xdc-volume +sudo resize2fs /dev/mapper/xdc-volume + +# If using cloud volume +# Expand EBS/GCE/Azure disk in console, then: +sudo growpart /dev/nvme0n1 1 +sudo resize2fs /dev/nvme0n1p1 +``` + +**Long-term (prune or archive):** + +```bash +# For full nodes: prune old state +bash docker-down.sh +bash xdc-attach.sh +> debug.setHead("0x" + (eth.blockNumber - 1000000).toString(16)) + +# For archive nodes: migrate to larger disk +# Follow migration procedure in backup guide +``` + +### Prevention + +```bash +# Set up disk usage monitoring alert +# Alert when > 80% full +# Auto-prune logs when > 85% full +``` + +--- + +## Runbook 3: Memory Exhaustion + +**Severity:** P2 - High +**Symptoms:** +- OOM (Out of Memory) kills in dmesg +- Node restarts unexpectedly +- High swap usage +- Slow response times + +### Diagnostic Steps + +```bash +# 1. Check current memory usage +free -h +top -o %MEM + +# 2. Check container memory (if Docker) +docker stats --no-stream + +# 3. Check for memory leaks in logs +dmesg | grep -i "oom\|out of memory" +docker-compose logs | grep -i "killed\|oom" + +# 4. Monitor memory over time +vmstat 1 10 +``` + +### Resolution + +**Immediate:** + +```bash +# Restart node to free memory +bash docker-down.sh +bash docker-up.sh +``` + +**Short-term:** + +```bash +# Reduce cache size +# Edit .env or docker-compose.yml +# Add: --cache 2048 (reduce from default 4096) + +# Increase swap (temporary) +sudo fallocate -l 8G /swapfile +sudo chmod 600 /swapfile +sudo mkswap /swapfile +sudo swapon /swapfile +``` + +**Long-term:** + +```bash +# Upgrade RAM +# Or migrate to larger instance + +# Optimize cache settings based on available memory +# 16GB RAM: --cache 2048 +# 32GB RAM: --cache 4096 +# 64GB RAM: --cache 8192 +``` + +--- + +## Runbook 4: Missed Blocks (Validators) + +**Severity:** P1 - Critical +**Symptoms:** +- Validator not producing blocks in assigned rounds +- Network stats page shows your node as offline +- Rewards decreasing + +### Diagnostic Steps + +```bash +# 1. Check if node is in validator set +bash xdc-attach.sh +> eth.getBlock("latest").validator + +# 2. Check if node is syncing +> eth.syncing +# Must be false to produce blocks + +# 3. Check peer count +> net.peerCount +# Must be > 0 + +# 4. Check if KYC is active +# Visit https://master.xinfin.network/ +# Search your coinbase address + +# 5. Check staking status +> xdc.getCandidateStatus("YOUR_COINBASE") +``` + +### Resolution + +**If not syncing:** +- Follow Runbook 1 (Node Not Syncing) + +**If KYC shows false:** +- Complete KYC process on masternode portal +- Wait for approval (can take 24-48 hours) + +**If stake is insufficient:** +- Ensure 10,000,000 XDC is staked +- Check if stake was slashed + +**If node is healthy but still missing blocks:** + +```bash +# Check system time (must be accurate) +timedatectl status + +# Sync time +sudo timedatectl set-ntp true +sudo systemctl restart systemd-timesyncd + +# Check network latency +ping -c 10 master.xinfin.network +``` + +### Escalation + +Escalate immediately if: +- Missing blocks for > 1 hour +- Stake was slashed (indicates double-signing or prolonged downtime) +- Node appears healthy but not in validator set + +--- + +## Runbook 5: Network Partition + +**Severity:** P2 - High +**Symptoms:** +- Node running but isolated from network +- Peer count drops suddenly +- Cannot reach external bootnodes + +### Diagnostic Steps + +```bash +# 1. Check network connectivity +ping 8.8.8.8 +curl -I https://xinfin.network + +# 2. Check if P2P port is reachable +nc -zv $(curl -s ifconfig.me) 30303 + +# 3. Check firewall status +sudo ufw status +sudo iptables -L | grep 30303 + +# 4. Check DNS resolution +nslookup bootnode.xinfin.network +``` + +### Resolution + +**If firewall blocking:** + +```bash +sudo ufw allow 30303/tcp +sudo ufw allow 30303/udp +sudo ufw reload +``` + +**If ISP/Cloud provider issue:** +- Check provider status page +- Verify security groups (AWS) / firewall rules (GCP/Azure) +- Ensure port 30303 is open in cloud console + +**If DNS issue:** + +```bash +# Use Google DNS temporarily +echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf + +# Or add bootnode IPs directly to config +``` + +--- + +## Runbook 6: Key Compromise or Loss + +**Severity:** P1 - Critical +**Symptoms:** +- Unauthorized transactions from validator address +- Keystore files deleted or corrupted +- Cannot access staked funds + +### Immediate Actions + +```bash +# 1. Stop node immediately +bash docker-down.sh + +# 2. Disconnect from network +sudo ufw deny out 30303/tcp +sudo ufw deny out 30303/udp +``` + +### If Keys Are Lost + +```bash +# 1. Check backups +ls -la /backup/xdc/*/keystore/ + +# 2. Restore from backup +cp /backup/xdc/latest/keystore/* xdcchain/keystore/ +cp /backup/xdc/latest/coinbase.txt xdcchain/ + +# 3. If no backup, keys are unrecoverable +# Contact XinFin support for stake recovery procedures +``` + +### If Keys Are Compromised + +```bash +# 1. Generate new keypair on secure offline machine +# 2. Submit unstake transaction from old key (if possible) +# 3. Stake from new address +# 4. Update KYC for new address +# 5. Update node configuration +``` + +### Prevention + +- Keep encrypted offline backups +- Use hardware security modules (HSM) for production +- Implement multi-sig for large stakes +- Regular key rotation schedule + +--- + +## Runbook 7: Docker Container Issues + +**Severity:** P2 - High +**Symptoms:** +- Container exits immediately +- Container running but not responding +- Image pull failures + +### Diagnostic Steps + +```bash +# 1. Check container status +docker ps -a | grep xinfin + +# 2. Check container logs +docker logs xinfin-node --tail=100 + +# 3. Check image +docker images | grep xinfin + +# 4. Check disk space for Docker +docker system df +``` + +### Resolution + +**If container exits:** + +```bash +# Check for port conflicts +sudo lsof -i :30303 +sudo lsof -i :8545 + +# Check for permission issues +ls -la xdcchain/ +sudo chown -R $(id -u):$(id -g) xdcchain/ + +# Recreate container +bash docker-down.sh +bash docker-up.sh +``` + +**If image pull fails:** + +```bash +# Check Docker Hub status +# Try pulling manually +docker pull xinfinorg/xinfin-node:latest + +# If network issue, use mirror or download manually +``` + +**If container is running but unresponsive:** + +```bash +# Restart container +docker restart xinfin-node + +# If still unresponsive, recreate +bash docker-down.sh +bash docker-up.sh +``` + +--- + +## Runbook 8: High CPU Usage + +**Severity:** P3 - Medium +**Symptoms:** +- CPU usage consistently > 90% +- Node becomes sluggish +- System load average high + +### Diagnostic Steps + +```bash +# 1. Check CPU usage +top -o %CPU +htop + +# 2. Check specific process +ps aux | grep XDC + +# 3. Check if during sync +bash xdc-attach.sh +> eth.syncing + +# 4. Check block processing time +> debug.metrics(false) +``` + +### Resolution + +**If during initial sync:** +- Normal behavior, will decrease after sync completes +- Consider upgrading CPU if sustained > 80% for days + +**If after sync:** + +```bash +# Check for spam transactions +bash xdc-attach.sh +> txpool.status + +# If high pending count, network may be under load +# Consider increasing resources +``` + +**If sustained high CPU:** + +```bash +# Reduce peer count +# Edit .env: MAX_PEERS=25 (default 50) + +# Or upgrade instance +# masternode: minimum 8 cores, recommended 16 +``` + +--- + +## Escalation Procedures + +### When to Escalate + +| Condition | Escalate To | Contact Method | +|-----------|-------------|----------------| +| Slashing event | XinFin Core Team | security@xinfin.org | +| Network-wide outage | XinFin Core Team | Discord #validators | +| Consensus failure | XinFin Core Team | Emergency hotline | +| Infrastructure issue | DevOps Lead | Internal Slack | +| Security incident | CISO + Legal | Incident response channel | + +### Communication Templates + +**P1 Incident Notification:** + +``` +Subject: [P1] XDC Node Incident - [Brief Description] + +Impact: [Masternode/Full Node] in [Region] +Severity: P1 - Critical +Start Time: [UTC] +Status: Investigating + +Symptoms: +- [Symptom 1] +- [Symptom 2] + +Actions Taken: +- [Action 1] +- [Action 2] + +Next Update: [Time + 15 minutes] +``` + +**Resolution Notification:** + +``` +Subject: [RESOLVED] XDC Node Incident - [Description] + +Duration: [Start] to [End] ([Duration]) +Root Cause: [Brief description] +Resolution: [What fixed it] + +Preventive Actions: +- [Action 1] +- [Action 2] +``` + +--- + +## Post-Incident Review Template + +**Incident ID:** INC-YYYY-MM-DD-NNN +**Date:** [Date] +**Severity:** [P1/P2/P3/P4] +**Duration:** [Start] - [End] + +### Timeline + +| Time | Event | +|------|-------| +| HH:MM | Alert triggered | +| HH:MM | Investigation started | +| HH:MM | Root cause identified | +| HH:MM | Resolution applied | +| HH:MM | Service restored | + +### Root Cause + +[Detailed description] + +### Impact + +- Blocks missed: [N] +- Downtime: [Duration] +- Users affected: [N] + +### Lessons Learned + +1. [Lesson 1] +2. [Lesson 2] + +### Action Items + +| Action | Owner | Due Date | +|--------|-------|----------| +| [Action] | [Name] | [Date] | + +--- + +## Related Topics + +- [Kubernetes Deployment](../kubernetes/index.md): Containerized deployment +- [Backup and Recovery](../backup/index.md): Backup strategies +- [Monitoring and Observability](../monitoring/index.md): Prometheus and Grafana +- [Validator Handbook](/xdcchain/developers/node_operators/validator-handbook): Validator operations diff --git a/website/docs/xdcchain/evmtoxdc.md b/website/docs/xdcchain/evmtoxdc.md new file mode 100644 index 00000000..04b9f887 --- /dev/null +++ b/website/docs/xdcchain/evmtoxdc.md @@ -0,0 +1,41 @@ +--- +title: Overview - XDC Chain +--- + +# Migrating from EVM to XDC + +Migrating a Solidity contract from Ethereum to the XDC network with Truffle involves several steps. The XDC network is a public blockchain that is EVM-compatible and designed to support enterprise-level applications. Truffle is a popular development framework for creating and deploying Solidity contracts. + +## Step 1: Install Truffle + +The first step is to install the XDC network and Truffle. This can be done by following the installation instructions provided by XDC and Truffle. + +[Installation - Truffle Suite](https://trufflesuite.com/docs/truffle/how-to/install/) + +## Step 2: Configure Truffle for XDC + +Next, Truffle needs to be configured to work with the XDC network. This involves creating a new Truffle project and configuring the Truffle config file to connect to the XDC network by using a public RPC connected to the XDC network. + +[Configuration - Truffle Suite](https://trufflesuite.com/docs/truffle/reference/configuration/) + +## Step 3: Compile the Contract + +After updating the Solidity contract, it needs to be compiled for the XDC network. This involves using the Truffle compiler to create a bytecode file that can be deployed on the XDC network. + +[Compile contracts - Truffle Suite](https://trufflesuite.com/docs/truffle/how-to/compile-contracts/) + +## Step 4: Deploy the Contract + +The next step is to deploy the updated contract on the XDC network. This can be done using Truffle's deployment commands. It is important to ensure that the contract is deployed correctly and securely. + +## Step 5: Test the Contract + +After deploying the contract, it is important to thoroughly test it on the XDC network. This includes testing all functions and features, as well as testing for security vulnerabilities. You can write tests in Truffle using Javascript to build debug and test contracts ready to be deployed onto the network + +[Write JavaScript tests - Truffle Suite](https://trufflesuite.com/docs/truffle/how-to/debug-test/write-tests-in-javascript/) + +## Step 6: Update Clients and Interfaces + +Once the contract has been migrated and tested, any clients or interfaces that interact with the contract must be updated to be compatible with the XDC network by having them point to the appropriate RPCs on the xdc network. + +For a How-To guide showing migration of a dApp from Ethereum to the XDC Network please go to [this link](https://ruslanwing100.medium.com/how-to-migrate-any-dapp-from-ethereum-to-xdc-network-using-truffle-b6a5b705bb01). \ No newline at end of file diff --git a/website/docs/xdcchain/faq.md b/website/docs/xdcchain/faq.md new file mode 100644 index 00000000..513e9d5d --- /dev/null +++ b/website/docs/xdcchain/faq.md @@ -0,0 +1,530 @@ +--- +title: "Frequently Asked Questions +description: Common questions about XDC Network — wallets, gas, deployment, tokens, nodes, bridging, and troubleshooting. Covers everything from beginner setup to advanced validator operations." +--- + +Difficulty: All Levels | Time: ~10 minutes reading + +# Frequently Asked Questions + +Quick answers to the most common questions about building on XDC Network. Organized by topic for easy navigation. + +--- + +## Getting Started + +### What is XDC Network? + +XDC Network is an EVM-compatible Layer 1 blockchain built for enterprise-grade decentralized applications. It features 2-second block times, near-zero gas fees (~$0.0001 per transaction), and deterministic finality through the XDPoS 2.0 consensus mechanism. The network is optimized for trade finance, RWA tokenization, and institutional DeFi. + +### Is XDC compatible with Ethereum? + +Yes. XDC is fully EVM-compatible, meaning: +- Solidity contracts work without modification +- MetaMask and other EVM wallets connect natively +- Hardhat, Foundry, and Remix work out of the box +- Ethereum tools and libraries (Ethers.js, Web3.js, Viem) function normally +- You can port existing Ethereum dApps with minimal changes + +### What do I need to start building? + +1. A wallet (MetaMask recommended) +2. Test XDC from the [faucet](https://faucet.apothem.network) +3. A development framework (Hardhat, Foundry, or Remix) + +See the [Developer Onboarding Guide](./developers/onboarding.md) for step-by-step setup. + +### How long does it take to deploy my first contract? + +**5 minutes** with Remix (browser-only, no installation). **15 minutes** with Hardhat or Foundry including environment setup. + +### Do I need to buy XDC to start developing? + +No. Use the [Apothem Testnet Faucet](https://faucet.apothem.network) to get free test XDC. Only buy mainnet XDC when you're ready to deploy to production. + +--- + +## Wallets & Accounts + +### Which wallets support XDC? + +Any EVM-compatible wallet works: +- **MetaMask** (recommended — most popular, best tooling support) +- **Rabby** (power users, enhanced security features) +- **Trust Wallet** (mobile-first) +- **Coinbase Wallet** (Coinbase ecosystem) +- **Frame** (desktop-native, hardware wallet focus) +- **Ledger/Trezor** (hardware wallets via MetaMask) + +### Why does my address start with `0x` instead of `xdc`? + +Both are valid. XDCScan displays addresses with `xdc` prefix for branding. EVM tools like MetaMask use `0x` prefix. They refer to the same account — only the prefix differs. + +Example: +- XDCScan: `xdc1234567890abcdef1234567890abcdef12345678` +- MetaMask: `0x1234567890abcdef1234567890abcdef12345678` + +**Conversion:** Simply replace `xdc` with `0x` (or vice versa) — the rest of the address is identical. + +### How do I add XDC to MetaMask? + +**Automatic (Recommended):** +1. Open MetaMask → Network dropdown +2. Click **Add Network** +3. Search "XDC" → Select **XDC Mainnet** or **XDC Apothem Testnet** +4. Click **Approve** + +**Manual:** See [Wallet Configuration](./developers/wallet-configuration.md). + +### Can I use the same wallet for mainnet and testnet? + +Yes. Your wallet address is identical across all networks. However, your balances are separate: +- Mainnet XDC has real value +- Testnet XDC is free and has no value + +Always verify which network you're on before transacting. + +### How do I export my private key? + +**MetaMask:** +1. Click the three dots menu → Account Details +2. Click **Export Private Key** +3. Enter your password +4. Copy the key + +> ⚠️ **Security Warning:** Never share your private key or seed phrase. Anyone with access can steal your funds. Store offline in a secure location. + +--- + +## Networks & RPC + +### What are the XDC network details? + +| Network | Chain ID | RPC URL | Explorer | Faucet | +|---------|----------|---------|----------|--------| +| **Mainnet** | 50 | `https://rpc.xinfin.network` | [xdcscan.com](https://xdcscan.com) | — | +| **Apothem Testnet** | 51 | `https://rpc.apothem.network` | [testnet.xdcscan.com](https://testnet.xdcscan.com) | [faucet.apothem.network](https://faucet.apothem.network) | +| **Devnet** | 551 | `https://devnetrpc.xinfin.network` | — | — | + +### Which RPC should I use? + +- **Development:** Apothem Testnet (free, safe to experiment) +- **Production:** Mainnet (real value, real users) +- **Testing new features:** Devnet (unstable, for core developers) + +### How do I check if RPC is working? + +```bash +curl -X POST https://rpc.apothem.network \ + -H "Content-Type: application/json" \ + -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' +``` + +Expected response: +```json +{"jsonrpc":"2.0","id":1,"result":"0x1234abcd"} +``` + +### What if the RPC is down? + +Use backup RPC endpoints: +- Mainnet: `https://erpc.xinfin.network` +- Apothem: `https://erpc.apothem.network` + +Or find more at [Chainlist](https://chainlist.org/?search=xdc). + +--- + +## Testnet & Faucet + +### How do I get test XDC? + +Visit [faucet.apothem.network](https://faucet.apothem.network) and enter your wallet address. You'll receive 1000 XDC instantly. + +### The faucet says "limit reached." What do I do? + +Wait 24 hours, or use an alternative faucet: +- [BlocksScan Faucet](https://faucet.blocksscan.io/) +- [ChainTools Faucet](https://chains.tools/faucet) + +### Can I use mainnet XDC for testing? + +No. Mainnet XDC has real value. Always test on Apothem Testnet first. Accidentally deploying untested contracts to mainnet can result in lost funds. + +### How do I switch between mainnet and testnet? + +**MetaMask:** Click the network dropdown (top center) and select the desired network. + +**Hardhat:** Use `--network xdc` for mainnet or `--network apothem` for testnet. + +**Foundry:** Use `--rpc-url xdc` or `--rpc-url apothem`. + +--- + +## Gas & Fees + +### How much are gas fees on XDC? + +XDC has effectively zero base fee. Typical costs: + +| Operation | Cost (XDC) | Cost (USD) | +|-----------|------------|------------| +| Simple transfer | ~0.0001 | ~$0.00001 | +| Token transfer | ~0.0002 | ~$0.00002 | +| Contract deployment | ~0.01–0.1 | ~$0.001–$0.01 | +| Complex contract call | ~0.001 | ~$0.0001 | + +### Why is my transaction stuck? + +XDC transactions rarely get stuck due to low gas. If pending: +1. Check your wallet is on the correct network (Chain ID 50 for mainnet, 51 for testnet) +2. Ensure you have enough XDC for gas +3. Try resubmitting with slightly higher gas price +4. Check [XDCScan](https://xdcscan.com) to see if the network is congested + +### Does XDC support EIP-1559? + +EIP-1559 is being rolled out on Apothem Testnet. Mainnet currently uses legacy gas model. Both work — your tooling handles this automatically. + +### How do I estimate gas for my transaction? + +**Hardhat:** +```javascript +const gasEstimate = await contract.myFunction.estimateGas(); +console.log(`Estimated gas: ${gasEstimate}`); +``` + +**Foundry:** +```bash +cast estimate --rpc-url apothem 0xCONTRACT_ADDRESS "myFunction()" +``` + +**MetaMask:** Automatically estimates when you confirm a transaction. + +--- + +## Smart Contracts + +### What Solidity version should I use? + +XDC supports Solidity up to 0.8.24. Use: +```solidity +pragma solidity ^0.8.24; +``` + +### How do I deploy a contract? + +Three options: + +1. **Remix** (browser) — No setup, [open and deploy](https://remix.xinfin.network) +2. **Hardhat** (JavaScript) — Best for teams, see [Hardhat Guide](/smartcontract/hardhat) +3. **Foundry** (Rust) — Fastest, see [Foundry Guide](/smartcontract/foundry) + +### How do I verify my contract on XDCScan? + +**Automatic (Hardhat):** +```bash +npx hardhat verify --network apothem 0xYOUR_CONTRACT_ADDRESS +``` + +**Automatic (Foundry):** +```bash +forge verify-contract 0xADDRESS src/Contract.sol:Contract --chain 51 +``` + +**Manual:** Go to [testnet.xdcscan.com](https://testnet.xdcscan.com), search your contract, click **Contract** → **Verify & Publish**. + +### Can I use OpenZeppelin contracts? + +Yes. Install via npm or forge: +```bash +npm install @openzeppelin/contracts +## or +forge install OpenZeppelin/openzeppelin-contracts +``` + +### Why is my contract deployment failing? + +Common causes: +- **Insufficient funds** — Get more test XDC from faucet +- **Wrong network** — Ensure you're on Apothem, not mainnet +- **Compiler mismatch** — Match pragma to compiler version exactly +- **Gas limit too low** — Increase gas limit in your config +- **Bytecode too large** — Optimize contract or split into libraries + +### How do I make my contract upgradeable? + +Use proxy patterns: +- **UUPS** (recommended) — Upgrade logic in implementation +- **Transparent Proxy** — Classic pattern, simpler + +See [Upgradeability Guide](/smartcontract/upgradeability) for full implementation. + +### Can I call my contract from a frontend? + +Yes. Use Ethers.js or Web3.js: + +```javascript +import { ethers } from "ethers"; + +const provider = new ethers.JsonRpcProvider("https://rpc.apothem.network"); +const contract = new ethers.Contract(address, abi, provider); + +const result = await contract.myFunction(); +``` + +See [JavaScript SDK](/xdcchain/developers/sdks/javascript) for detailed integration. + +--- + +## Tokens + +### What token standards does XDC support? + +- **XRC20** — Fungible tokens (like ERC20) +- **XRC721** — NFTs (like ERC721) +- **XRC404** — Hybrid tokens (fungible + NFT) + +See [Token Standards](/smartcontract/tokens) for details. + +### How do I create a token? + +Use OpenZeppelin's token contracts: +```solidity +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +contract MyToken is ERC20 { + constructor() ERC20("MyToken", "MTK") { + _mint(msg.sender, 1000000 * 10**decimals()); + } +} +``` + +### Where can I see existing tokens? + +Browse [XDCScan Tokens](https://xdcscan.io/tokens) for XRC20 tokens and [XDCScan NFTs](https://xdcscan.io/nft-top-contracts) for XRC721 collections. + +### How do I add my token to MetaMask? + +1. Open MetaMask → Assets tab +2. Click **Import tokens** +3. Paste your token contract address +4. MetaMask auto-fills symbol and decimals +5. Click **Add custom token** + +### Can I bridge tokens from Ethereum to XDC? + +Yes. Use the [XDC Bridge](https://bridge.xdc.network) or third-party bridges like Multichain. Always verify bridge contracts before transferring large amounts. + +--- + +## Nodes & Validation + +### How do I run an XDC node? + +See the [Masternode Setup Guide](./developers/node_operators/masternode.md). Options include: +- Bootstrap script (quickest) +- Docker (containerized) +- Snapshot download (fast sync) + +### What are the requirements to become a validator? + +- **10,000,000 XDC** as stake +- Dedicated server (see [Node Architecture](./developers/node_operators/node_architecture.md)) +- 24/7 uptime (99.9% expected) +- Static IP address + +### How are validators rewarded? + +Validators earn: +- Block rewards (newly minted XDC) +- Transaction fees +- Additional rewards for uptime and performance + +See [Rewards Mechanism](./rewards.md) for detailed breakdown. + +### What happens if my node goes offline? + +Slashing penalties apply for: +- Extended downtime (> few hours) +- Double signing +- Malicious behavior + +See [Slashing](./developers/node_operators/slashing.md) for penalty details. + +### Can I run a node without becoming a validator? + +Yes. You can run a **full node** or **archive node** without staking. These nodes: +- Validate transactions +- Store blockchain history +- Serve RPC requests +- Don't earn rewards + +--- + +## Bridging & Cross-Chain + +### How do I bridge assets to XDC? + +Use official bridges: +- [XDC Bridge](https://bridge.xdc.network) — Ethereum ↔ XDC +- [Multichain](https://multichain.org) — Multi-chain support + +**Steps:** +1. Connect wallet on source chain +2. Select asset and amount +3. Confirm transaction +4. Wait for confirmation (usually 10–30 minutes) +5. Receive wrapped asset on XDC + +### What are wrapped tokens? + +Wrapped tokens represent assets from other blockchains on XDC: +- **WXDC** — Wrapped XDC for DeFi compatibility +- **WETH** — Wrapped Ethereum +- **USDC** — Bridged from Ethereum + +They maintain 1:1 peg with the original asset. + +### Are bridges safe? + +Bridges carry risks: +- Smart contract bugs +- Centralized validator sets +- Liquidity constraints + +**Best practices:** +- Use official or audited bridges +- Start with small amounts +- Verify contract addresses +- Don't bridge more than you can afford to lose + +--- + +## Security + +### How do I secure my private keys? + +**Best practices:** +- Use hardware wallets (Ledger, Trezor) for large amounts +- Store seed phrases offline (metal backup recommended) +- Never share private keys or seed phrases +- Use multi-sig wallets for team funds +- Separate hot wallets (development) from cold wallets (savings) + +See [Key Management](/security/key-management) for detailed guide. + +### Are there known vulnerabilities on XDC? + +XDC uses battle-tested EVM code. Common smart contract vulnerabilities apply: +- Reentrancy +- Integer overflow/underflow +- Access control issues +- Front-running + +See [Vulnerability Catalog](/security/vulnerabilities) for comprehensive list and mitigations. + +### Should I audit my contract before mainnet? + +**Yes.** Always audit before mainnet deployment: +- Internal review (team) +- Automated tools (Slither, Mythril) +- Professional audit (CertiK, Hacken, etc.) + +See [Audit Preparation](/security/audit-prep) for checklist. + +--- + +## Troubleshooting + +### MetaMask won't connect to XDC + +- Ensure you're on the correct network (Chain ID 50 or 51) +- Try refreshing the page +- Check that MetaMask is unlocked +- Clear browser cache and try again +- Try a different browser + +### "Insufficient funds" error + +- Get test XDC from the [faucet](https://faucet.apothem.network) +- For mainnet, purchase XDC from exchanges (KuCoin, Gate.io, Bitfinex) +- Check you're on the right network (testnet vs mainnet) + +### Contract deployment fails + +- Check you have enough gas +- Verify compiler version matches pragma +- Ensure contract has no syntax errors +- Check gas limit in your config (increase if needed) + +### Can't verify contract on XDCScan + +- Match exact compiler version +- Ensure optimization settings match +- For multi-file contracts, flatten first +- Verify constructor arguments (if any) + +### Transaction pending for too long + +XDC has 2-second block times, so transactions confirm quickly. If pending: +- Check network status on [XDCScan](https://xdcscan.com) +- Try resubmitting with higher gas price +- Ensure your wallet is synced to the latest block + +### "Nonce too high" error + +Reset your MetaMask account: +1. Settings → Advanced +2. Click **Reset Account** +3. This clears transaction history without affecting funds + +--- + +## Ecosystem & Community + +### Where can I get help? + +| Resource | Link | Best For | +|----------|------|----------| +| Developer Discord | [discord.gg/xdc](https://discord.gg/xdc) | Quick questions, community support | +| Developer Forum | [www.xdc.dev](https://www.xdc.dev) | Detailed discussions, tutorials | +| GitHub Issues | [github.com/XinFinOrg](https://github.com/XinFinOrg) | Bug reports, feature requests | +| StackOverflow | Tag `xdc` | Technical coding questions | +| Telegram | [t.me/xinfintalk](https://t.me/xinfintalk) | General community chat | + +### How do I report a bug? + +Open an issue on [GitHub](https://github.com/XinFinOrg/XDPoSChain/issues) with: +- Clear title and description +- Steps to reproduce +- Expected vs actual behavior +- Environment details (wallet, network, tool versions) +- Screenshots or logs (if applicable) + +### How can I contribute to XDC? + +- **Code:** Submit PRs to [GitHub repos](https://github.com/XinFinOrg) +- **Documentation:** Improve docs (like this page!) +- **Community:** Answer questions on Discord/Forum +- **Testing:** Run testnet nodes, report bugs +- **Grants:** Apply for [XDC Foundation grants](https://xinfin.org) + +### Where can I see XDC ecosystem projects? + +- [XDC Ecosystem Directory](https://xinfin.org/ecosystem-dapps) +- [XDC Dev Forum Showcases](https://www.xdc.dev) +- [XDCScan](https://xdcscan.io) — browse deployed contracts + +--- + +## Next Steps + +- [Developer Onboarding →](./developers/onboarding.md) +- [Smart Contract Lifecycle →](/smartcontract) +- [Security Best Practices →](/security/security-practices) +- [JavaScript SDK →](/xdcchain/developers/sdks/javascript) + +--- + +*Didn't find your answer? Ask on the [Developer Forum](https://www.xdc.dev) or [Discord](https://discord.gg/xdc).* diff --git a/website/docs/xdcchain/governance/dao/index.md b/website/docs/xdcchain/governance/dao/index.md new file mode 100644 index 00000000..5c2c1f1c --- /dev/null +++ b/website/docs/xdcchain/governance/dao/index.md @@ -0,0 +1,981 @@ +--- +title: "DAO Development on XDC +description: Comprehensive guide for building Decentralized Autonomous Organizations (DAOs) on XDC Network including governance tokens, voting mechanisms, treasury management, and security best practices." +--- + +# DAO Development on XDC + +This guide provides everything needed to build, deploy, and operate Decentralized Autonomous Organizations (DAOs) on XDC Network. From governance token design to treasury management, voting mechanisms to security audits. + +## Table of Contents + +1. [DAO Concepts](#dao-concepts) +2. [Architecture Overview](#architecture-overview) +3. [Governance Token Design](#governance-token-design) +4. [Voting Mechanisms](#voting-mechanisms) +5. [Treasury Management](#treasury-management) +6. [Proposal Systems](#proposal-systems) +7. [Timelock and Execution](#timelock-and-execution) +8. [Tool Integration](#tool-integration) +9. [Security Best Practices](#security-best-practices) +10. [Legal and Compliance](#legal-and-compliance) +11. [Example: Building a Community DAO](#example-building-a-community-dao) +12. [Testing and Deployment](#testing-and-deployment) +13. [Related Topics](#related-topics) + +--- + +## DAO Concepts + +### What is a DAO + +A Decentralized Autonomous Organization (DAO) is an entity governed by smart contracts and community voting rather than centralized leadership. On XDC Network, DAOs leverage EVM compatibility to deploy proven governance patterns with fast finality and low transaction costs. + +### Key Characteristics + +| Characteristic | Description | XDC Advantage | +|---------------|-------------|---------------| +| Decentralized | No single point of control | XDPoS consensus ensures fast, fair validation | +| Autonomous | Smart contracts execute decisions | 2-second finality for rapid execution | +| Transparent | All actions on-chain | Public ledger with XDCScan explorer | +| Token-Governed | Voting power through tokens | Low gas costs enable frequent participation | + +### Governance Models + +**Token-Based Voting** +- One token equals one vote +- Simplest model, used by most DAOs +- Risk: Plutocracy (wealth concentration) + +**Quadratic Voting** +- Voting cost increases quadratically +- Formula: Cost = Votes^2 +- Reduces whale dominance + +**Delegated Voting** +- Token holders delegate votes to representatives +- Similar to representative democracy +- Reduces voter apathy + +**Reputation-Based** +- Voting power from contributions, not wealth +- Meritocratic approach +- Harder to implement fairly + +**Multi-Sig Governance** +- Predefined signers required for actions +- Useful for treasury management +- Common in early-stage DAOs + +--- + +## Architecture Overview + +### Core Components + +``` +DAO Architecture +| +|-- Governance Token (XRC20) +| |-- Voting power delegation +| |-- Balance tracking +| |-- Transfer restrictions (optional) +| +|-- Governor Contract +| |-- Proposal creation +| |-- Voting logic +| |-- Quorum calculation +| |-- Execution scheduling +| +|-- Timelock Contract +| |-- Delayed execution +| |-- Emergency pause +| |-- Cancellation logic +| +|-- Treasury Contract +| |-- Asset management +| |-- Spending limits +| |-- Multi-sig requirements +| +|-- Proposal System + |-- Discussion phase + |-- Voting phase + |-- Execution phase + |-- Cancellation +``` + +### Component Interactions + +1. **Token holders** delegate voting power or vote directly +2. **Governor** receives proposals, tracks votes, checks quorum +3. **Timelock** queues successful proposals with delay +4. **Treasury** holds assets and releases per approved proposals +5. **Executors** carry out proposal actions after timelock expires + +--- + +## Governance Token Design + +### XRC20 Governance Token + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; +import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; + +contract XDCGovernanceToken is ERC20, ERC20Votes, ERC20Permit, Ownable { + constructor( + string memory name, + string memory symbol, + uint256 initialSupply + ) ERC20(name, symbol) ERC20Permit(name) Ownable(msg.sender) { + _mint(msg.sender, initialSupply); + } + + // Required overrides for ERC20Votes + function _update(address from, address to, uint256 value) + internal + override(ERC20, ERC20Votes) + { + super._update(from, to, value); + } + + function nonces(address owner) + public + view + override(ERC20Permit, Nonces) + returns (uint256) + { + return super.nonces(owner); + } + + // Optional: Minting controlled by governance + function mint(address to, uint256 amount) external onlyOwner { + _mint(to, amount); + } + + // Optional: Burn functionality + function burn(uint256 amount) external { + _burn(msg.sender, amount); + } +} +``` + +### Token Distribution Strategies + +| Strategy | Allocation | Use Case | +|----------|-----------|----------| +| Fair Launch | 100% to community | Maximum decentralization | +| Team + Community | 20% team, 80% community | Balanced incentives | +| Gradual Release | Vesting over 4 years | Long-term alignment | +| Airdrop + Liquidity | 50% airdrop, 50% DEX | Rapid distribution | + +### Voting Power Calculation + +```solidity +// Checkpoint-based voting (prevents flash loan attacks) +function getVotes(address account) public view returns (uint256) { + return getPastVotes(account, block.number - 1); +} + +// Delegation +function delegate(address delegatee) public { + _delegate(msg.sender, delegatee); +} +``` + +**Security Note:** Always use `block.number - 1` for vote snapshots to prevent manipulation within the same block. + +--- + +## Voting Mechanisms + +### OpenZeppelin Governor + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import "@openzeppelin/contracts/governance/Governor.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorSettings.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorCountingSimple.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorVotes.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorVotesQuorumFraction.sol"; +import "@openzeppelin/contracts/governance/extensions/GovernorTimelockControl.sol"; + +contract XDCGovernor is + Governor, + GovernorSettings, + GovernorCountingSimple, + GovernorVotes, + GovernorVotesQuorumFraction, + GovernorTimelockControl +{ + constructor( + IVotes _token, + TimelockController _timelock, + uint256 _votingDelay, // Blocks before voting starts + uint256 _votingPeriod, // Blocks voting remains open + uint256 _quorumPercentage // % of total supply required + ) + Governor("XDCGovernor") + GovernorSettings( + _votingDelay, // e.g., 1 block (~2 seconds on XDC) + _votingPeriod, // e.g., 50400 blocks (~1 day) + 0 // Proposal threshold (0 tokens) + ) + GovernorVotes(_token) + GovernorVotesQuorumFraction(_quorumPercentage) + GovernorTimelockControl(_timelock) + {} + + // Required overrides + function votingDelay() + public + view + override(IGovernor, GovernorSettings) + returns (uint256) + { + return super.votingDelay(); + } + + function votingPeriod() + public + view + override(IGovernor, GovernorSettings) + returns (uint256) + { + return super.votingPeriod(); + } + + function quorum(uint256 blockNumber) + public + view + override(IGovernor, GovernorVotesQuorumFraction) + returns (uint256) + { + return super.quorum(blockNumber); + } + + function state(uint256 proposalId) + public + view + override(Governor, GovernorTimelockControl) + returns (ProposalState) + { + return super.state(proposalId); + } + + function propose( + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + string memory description + ) public override(Governor, IGovernor) returns (uint256) { + return super.propose(targets, values, calldatas, description); + } + + function _execute( + uint256 proposalId, + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + bytes32 descriptionHash + ) internal override(Governor, GovernorTimelockControl) { + super._execute(proposalId, targets, values, calldatas, descriptionHash); + } + + function _cancel( + address[] memory targets, + uint256[] memory values, + bytes[] memory calldatas, + bytes32 descriptionHash + ) internal override(Governor, GovernorTimelockControl) returns (uint256) { + return super._cancel(targets, values, calldatas, descriptionHash); + } + + function _executor() + internal + view + override(Governor, GovernorTimelockControl) + returns (address) + { + return super._executor(); + } + + function supportsInterface(bytes4 interfaceId) + public + view + override(Governor, GovernorTimelockControl) + returns (bool) + { + return super.supportsInterface(interfaceId); + } +} +``` + +### Voting Configuration for XDC + +| Parameter | Mainnet Value | Testnet Value | Rationale | +|-----------|--------------|---------------|-----------| +| Voting Delay | 1 block | 1 block | 2-second finality means minimal delay | +| Voting Period | 50,400 blocks | 7,200 blocks | ~1 day mainnet, ~4 hours testnet | +| Quorum | 4% | 1% | Low enough for participation, high enough for legitimacy | +| Proposal Threshold | 100 tokens | 10 tokens | Prevents spam | +| Timelock Delay | 2 days | 1 hour | Time to review before execution | + +### Advanced: Quadratic Voting Implementation + +```solidity +contract QuadraticVoting { + mapping(uint256 => mapping(address => uint256)) public votesCast; + mapping(uint256 => uint256) public totalQuadraticVotes; + + function castQuadraticVote( + uint256 proposalId, + uint256 voteCount, + bool support + ) external { + uint256 cost = voteCount * voteCount; + governanceToken.transferFrom(msg.sender, address(this), cost); + + votesCast[proposalId][msg.sender] = voteCount; + totalQuadraticVotes[proposalId] += voteCount; + + emit QuadraticVoteCast(proposalId, msg.sender, voteCount, support); + } +} +``` + +--- + +## Treasury Management + +### Treasury Contract + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import "@openzeppelin/contracts/access/AccessControl.sol"; +import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +contract XDCTreasury is AccessControl, ReentrancyGuard { + bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); + bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); + + // Spending limits + mapping(address => uint256) public dailyLimits; + mapping(address => uint256) public spentToday; + uint256 public lastResetDay; + + // Asset tracking + address[] public heldTokens; + mapping(address => bool) public isTrackedToken; + + event FundsReceived(address indexed sender, uint256 amount); + event FundsSent(address indexed token, address indexed recipient, uint256 amount); + event LimitUpdated(address indexed token, uint256 newLimit); + + constructor(address governance) { + _grantRole(DEFAULT_ADMIN_ROLE, governance); + _grantRole(GOVERNANCE_ROLE, governance); + lastResetDay = block.timestamp / 1 days; + } + + receive() external payable { + emit FundsReceived(msg.sender, msg.value); + } + + // Governance-controlled spending + function executeTransfer( + address token, + address recipient, + uint256 amount + ) external onlyRole(GOVERNANCE_ROLE) nonReentrant { + _resetDailySpending(); + + require( + spentToday[token] + amount <= dailyLimits[token], + "Exceeds daily limit" + ); + + spentToday[token] += amount; + + if (token == address(0)) { + (bool success, ) = recipient.call{value: amount}(""); + require(success, "XDC transfer failed"); + } else { + IERC20(token).transfer(recipient, amount); + } + + emit FundsSent(token, recipient, amount); + } + + // Guardian can pause in emergency + function emergencyPause() external onlyRole(GUARDIAN_ROLE) { + _pause(); + } + + function _resetDailySpending() internal { + uint256 currentDay = block.timestamp / 1 days; + if (currentDay > lastResetDay) { + lastResetDay = currentDay; + // Reset spentToday for all tracked tokens + for (uint i = 0; i < heldTokens.length; i++) { + spentToday[heldTokens[i]] = 0; + } + spentToday[address(0)] = 0; + } + } + + function setDailyLimit(address token, uint256 limit) + external + onlyRole(GOVERNANCE_ROLE) + { + dailyLimits[token] = limit; + if (!isTrackedToken[token]) { + isTrackedToken[token] = true; + heldTokens.push(token); + } + emit LimitUpdated(token, limit); + } + + function getBalance(address token) external view returns (uint256) { + if (token == address(0)) { + return address(this).balance; + } + return IERC20(token).balanceOf(address(this)); + } +} +``` + +### Treasury Best Practices + +| Practice | Implementation | Purpose | +|----------|---------------|---------| +| Multi-sig Required | 3-of-5 signers for emergency | Prevent single-key compromise | +| Daily Limits | Cap on daily outflows | Limit damage from exploits | +| Timelock All Transfers | 48-hour delay | Community review period | +| Asset Diversification | Hold XDC, stablecoins, ETH | Reduce volatility risk | +| Regular Audits | Quarterly reviews | Catch vulnerabilities | + +--- + +## Proposal Systems + +### Proposal Lifecycle + +``` +1. Discussion (Off-chain) + - Forum discussion + - Temperature check (Snapshot) + - Refine proposal + +2. Submission (On-chain) + - Meet proposal threshold + - Submit to Governor + - Pay proposal deposit (refundable) + +3. Voting Period + - Voting delay passes + - Token holders vote + - Track quorum + +4. Execution + - If passed: queue in timelock + - Wait timelock delay + - Execute actions + +5. Cancellation + - Proposer can cancel before execution + - Guardian can cancel malicious proposals +``` + +### Proposal Types + +| Type | Description | Example | +|------|-------------|---------| +| Parameter Change | Update protocol settings | Change quorum from 4% to 5% | +| Treasury Spend | Transfer funds | Fund development grant | +| Contract Upgrade | Replace implementation | Upgrade staking contract | +| Member Management | Add/remove roles | Add new guardian | +| Text Proposal | Non-binding signal | Community sentiment | + +### Creating a Proposal + +```javascript +// Using ethers.js +const governor = new ethers.Contract(governorAddress, governorABI, signer); + +// Encode function call +const tokenInterface = new ethers.Interface(tokenABI); +const calldata = tokenInterface.encodeFunctionData("transfer", [ + recipientAddress, + ethers.parseEther("1000") +]); + +// Submit proposal +const tx = await governor.propose( + [tokenAddress], // targets + [0], // values (XDC to send) + [calldata], // calldatas + "Proposal #1: Fund Development Grant" // description +); + +await tx.wait(); +``` + +--- + +## Timelock and Execution + +### Timelock Controller + +```solidity +// OpenZeppelin TimelockController +// Deploy with: +// - minDelay: 2 days (172800 seconds) +// - proposers: [Governor address] +// - executors: [Governor address, any address] +// - admin: address(0) (renounce after setup) + +contract Deployment { + function deployTimelock() external returns (address) { + address[] memory proposers = new address[](1); + proposers[0] = governorAddress; + + address[] memory executors = new address[](1); + executors[0] = address(0); // Anyone can execute + + TimelockController timelock = new TimelockController( + 2 days, // minDelay + proposers, // proposers + executors, // executors + address(0) // admin (renounced) + ); + + return address(timelock); + } +} +``` + +### Execution Flow + +```javascript +// 1. Queue (after proposal passes) +const tx = await governor.queue( + [tokenAddress], + [0], + [calldata], + descriptionHash +); + +// 2. Wait for timelock delay (2 days) + +// 3. Execute +const tx = await governor.execute( + [tokenAddress], + [0], + [calldata], + descriptionHash +); +``` + +--- + +## Tool Integration + +### Snapshot Integration + +Snapshot provides gasless voting for DAOs. Integrate with XDC: + +```javascript +// snapshot-config.json +{ + "name": "XDC Community DAO", + "network": "50", // XDC mainnet chain ID + "symbol": "XDCGOV", + "strategies": [ + { + "name": "erc20-balance-of", + "params": { + "address": "0x...", + "symbol": "XDCGOV", + "decimals": 18 + } + } + ], + "members": [ + "0x..." // Admin addresses + ], + "filters": { + "minScore": 100, + "onlyMembers": false + } +} +``` + +**Setup Steps:** +1. Visit [Snapshot](https://snapshot.org/) +2. Connect wallet with XDC +3. Create space with XDC network +4. Set voting strategies +5. Link to on-chain execution + +### Safe (Gnosis Safe) Multi-Sig + +```javascript +// Deploy Safe on XDC +import Safe from '@safe-global/protocol-kit'; + +const safe = await Safe.init({ + provider: 'https://rpc.xinfin.network', + signer: process.env.PRIVATE_KEY, + safeAddress: predictedSafeAddress +}); + +// Create transaction +const safeTransaction = await safe.createTransaction({ + transactions: [{ + to: recipient, + value: '1000000000000000000', // 1 XDC + data: '0x' + }] +}); + +// Sign and execute +const txHash = await safe.getTransactionHash(safeTransaction); +const signature = await safe.signTransactionHash(txHash); +``` + +### Treasury Dashboard Tools + +| Tool | Purpose | Integration | +|------|---------|-------------| +| DeBank | Portfolio tracking | Read-only API | +| Zapper | Treasury overview | Contract reading | +| Llama | DAO treasury analytics | Custom subgraph | +| Dune Analytics | Custom queries | SQL on XDC data | + +--- + +## Security Best Practices + +### Smart Contract Security + +| Check | Implementation | Priority | +|-------|---------------|----------| +| Reentrancy Guard | Use OpenZeppelin's modifier | Critical | +| Access Control | Role-based permissions | Critical | +| Integer Overflow | Solidity 0.8+ built-in | Critical | +| Front-running | Commit-reveal or timelock | High | +| Flash Loan Attacks | Vote snapshots at block N-1 | High | +| Governance Takeover | Quorum + timelock delays | High | + +### Audit Checklist + +``` +Pre-Deployment: +[ ] Unit tests for all functions +[ ] Integration tests for proposal flow +[ ] Fuzzing with Echidna or Foundry +[ ] Slither static analysis +[ ] Certik/OpenZeppelin audit +[ ] Bug bounty program setup +[ ] Emergency pause tested +[ ] Upgrade path documented +``` + +### Common Attack Vectors + +| Attack | Description | Prevention | +|--------|-------------|------------| +| Flash Loan Voting | Borrow tokens to vote, return in same block | Snapshot at block N-1 | +| Governance Takeover | Acquire majority tokens, pass malicious proposal | High quorum + timelock | +| Proposal Spam | Create many proposals to DOS | Proposal threshold + deposit | +| Vote Buying | Pay users for votes | Private voting (zk-SNARKs) | +| Sybil Attacks | Create many small accounts | Identity verification or token weight | + +--- + +## Legal and Compliance + +### Legal Structures + +| Structure | Jurisdiction | Best For | +|-----------|-------------|----------| +| Swiss Association | Switzerland | Large, established DAOs | +| Cayman Islands Foundation | Cayman | Investment DAOs | +| Wyoming DAO LLC | Wyoming, USA | US-based projects | +| Marshall Islands Non-Profit | Marshall Islands | International scope | +| Unincorporated | None | Experimental, small DAOs | + +### Compliance Considerations + +- **Securities Laws:** Governance tokens may be securities in some jurisdictions +- **Tax:** Treasury income may be taxable +- **KYC/AML:** Required for certain treasury operations +- **Data Privacy:** Member data protection (GDPR) + +### Recommended Approach + +1. Start as unincorporated with multi-sig +2. Incorporate as non-profit once treasury grows +3. Consult legal counsel before token distribution +4. Document governance processes for legal clarity + +--- + +## Example: Building a Community DAO + +### Step-by-Step Deployment + +**Step 1: Deploy Token** + +```javascript +const tokenFactory = new ethers.ContractFactory( + XDCGovernanceTokenABI, + XDCGovernanceTokenBytecode, + deployer +); + +const token = await tokenFactory.deploy( + "XDC Community Token", + "XCT", + ethers.parseEther("10000000") // 10M tokens +); +await token.waitForDeployment(); +console.log("Token deployed:", await token.getAddress()); +``` + +**Step 2: Deploy Timelock** + +```javascript +const timelockFactory = new ethers.ContractFactory( + TimelockControllerABI, + TimelockControllerBytecode, + deployer +); + +const timelock = await timelockFactory.deploy( + 2 * 24 * 60 * 60, // 2 days + [], // Proposers (will add governor later) + [], // Executors + deployer.address // Temporary admin +); +``` + +**Step 3: Deploy Governor** + +```javascript +const governorFactory = new ethers.ContractFactory( + XDCGovernorABI, + XDCGovernorBytecode, + deployer +); + +const governor = await governorFactory.deploy( + await token.getAddress(), + await timelock.getAddress(), + 1, // voting delay (1 block) + 50400, // voting period (~1 day) + 4 // quorum (4%) +); +``` + +**Step 4: Configure Roles** + +```javascript +// Grant governor proposer role +await timelock.grantRole( + await timelock.PROPOSER_ROLE(), + await governor.getAddress() +); + +// Grant governor executor role +await timelock.grantRole( + await timelock.EXECUTOR_ROLE(), + await governor.getAddress() +); + +// Renounce timelock admin (critical for decentralization) +await timelock.renounceRole( + await timelock.TIMELOCK_ADMIN_ROLE(), + deployer.address +); +``` + +**Step 5: Transfer Token Ownership** + +```javascript +await token.transferOwnership(await governor.getAddress()); +``` + +**Step 6: Distribute Tokens** + +```javascript +// Airdrop to community +const airdropRecipients = [...]; // Array of addresses +const airdropAmounts = [...]; // Array of amounts + +for (let i = 0; i < airdropRecipients.length; i++) { + await token.transfer(airdropRecipients[i], airdropAmounts[i]); +} +``` + +--- + +## Testing and Deployment + +### Test Suite + +```javascript +// test/Governance.test.js +const { expect } = require("chai"); +const { ethers } = require("hardhat"); + +describe("XDC Governance", function () { + let token, governor, timelock, owner, addr1, addr2; + + beforeEach(async function () { + [owner, addr1, addr2] = await ethers.getSigners(); + + // Deploy token + const Token = await ethers.getContractFactory("XDCGovernanceToken"); + token = await Token.deploy("GovToken", "GOV", ethers.parseEther("1000000")); + + // Deploy timelock + const Timelock = await ethers.getContractFactory("TimelockController"); + timelock = await Timelock.deploy( + 3600, // 1 hour min delay for testing + [], + [], + owner.address + ); + + // Deploy governor + const Governor = await ethers.getContractFactory("XDCGovernor"); + governor = await Governor.deploy( + await token.getAddress(), + await timelock.getAddress(), + 1, // 1 block voting delay + 100, // 100 blocks voting period + 4 // 4% quorum + ); + + // Setup roles + await timelock.grantRole(await timelock.PROPOSER_ROLE(), await governor.getAddress()); + await timelock.grantRole(await timelock.EXECUTOR_ROLE(), await governor.getAddress()); + }); + + it("Should create a proposal", async function () { + const targets = [await token.getAddress()]; + const values = [0]; + const calldatas = [token.interface.encodeFunctionData("mint", [addr1.address, ethers.parseEther("1000")])]; + + await expect(governor.propose(targets, values, calldatas, "Mint tokens")) + .to.emit(governor, "ProposalCreated"); + }); + + it("Should execute a successful proposal", async function () { + // Delegate votes + await token.delegate(owner.address); + + // Create proposal + const targets = [await token.getAddress()]; + const values = [0]; + const calldatas = [token.interface.encodeFunctionData("mint", [addr1.address, ethers.parseEther("1000")])]; + const description = "Mint tokens to addr1"; + + const tx = await governor.propose(targets, values, calldatas, description); + const receipt = await tx.wait(); + const event = receipt.logs.find(l => l.fragment?.name === "ProposalCreated"); + const proposalId = event.args.proposalId; + + // Vote + await governor.castVote(proposalId, 1); // 1 = For + + // Advance time past voting period + await network.provider.send("evm_increaseTime", [3600]); + await network.provider.send("evm_mine"); + + // Queue and execute + const descriptionHash = ethers.id(description); + await governor.queue(targets, values, calldatas, descriptionHash); + + await network.provider.send("evm_increaseTime", [3600]); // Timelock delay + await network.provider.send("evm_mine"); + + await governor.execute(targets, values, calldatas, descriptionHash); + + expect(await token.balanceOf(addr1.address)).to.equal(ethers.parseEther("1000")); + }); +}); +``` + +### Deployment Script + +```javascript +// scripts/deploy-dao.js +const hre = require("hardhat"); + +async function main() { + const [deployer] = await hre.ethers.getSigners(); + console.log("Deploying with:", deployer.address); + + // Deploy Token + const Token = await hre.ethers.getContractFactory("XDCGovernanceToken"); + const token = await Token.deploy("XDC Community DAO", "XCD", hre.ethers.parseEther("10000000")); + await token.waitForDeployment(); + console.log("Token:", await token.getAddress()); + + // Deploy Timelock + const Timelock = await hre.ethers.getContractFactory("TimelockController"); + const timelock = await Timelock.deploy( + 172800, // 2 days + [], + [], + deployer.address + ); + await timelock.waitForDeployment(); + console.log("Timelock:", await timelock.getAddress()); + + // Deploy Governor + const Governor = await hre.ethers.getContractFactory("XDCGovernor"); + const governor = await Governor.deploy( + await token.getAddress(), + await timelock.getAddress(), + 1, + 50400, + 4 + ); + await governor.waitForDeployment(); + console.log("Governor:", await governor.getAddress()); + + // Configure + await timelock.grantRole(await timelock.PROPOSER_ROLE(), await governor.getAddress()); + await timelock.grantRole(await timelock.EXECUTOR_ROLE(), await governor.getAddress()); + await timelock.renounceRole(await timelock.TIMELOCK_ADMIN_ROLE(), deployer.address); + await token.transferOwnership(await governor.getAddress()); + + console.log("DAO deployment complete!"); +} + +main().catch(console.error); +``` + +--- + +## Related Topics + +- [XDC Governance Overview](/xdcchain/governance/overview): Existing XDCDAO documentation +- [Smart Contract Development](/smartcontract): General smart contract guide +- [Security Best Practices](/security/overview): Security documentation +- [XRC20 Token Standard](/smartcontract/tokens/xrc20): Token implementation +- [Account Abstraction](/smartcontract/account-abstraction): Advanced wallet patterns diff --git a/website/docs/xdcchain/governance/overview.md b/website/docs/xdcchain/governance/overview.md new file mode 100644 index 00000000..73328f21 --- /dev/null +++ b/website/docs/xdcchain/governance/overview.md @@ -0,0 +1,22 @@ +--- +title: Overview - XDCDAO +--- + + +# XDC Governance Overview +![governance](../img/xdcdao.png) + +The DAO Treasury within the [XDCDAO](https://www.xdcdao.org/) framework plays a critical role in the XDC Network's decentralized governance system. It is meticulously designed to manage the community's collective resources efficiently, securely, and transparently. This section provides a structured overview of the DAO Treasury, highlighting its purpose, operation, funding sources, and significance within the DAOFIN ecosystem. + +## Purpose of the DAO Treasury + +The DAO Treasury's primary objective is to support the sustainable growth and development of the XDC Network by financing projects and initiatives that align with the community's goals. It acts as the financial hub for: + +- Funding protocol enhancements. +- Supporting community-driven projects. +- Enhancing network security. +- Facilitating ecosystem expansion. + + + + diff --git a/website/docs/xdcchain/governance/user-guide.md b/website/docs/xdcchain/governance/user-guide.md new file mode 100644 index 00000000..2be6c8f5 --- /dev/null +++ b/website/docs/xdcchain/governance/user-guide.md @@ -0,0 +1,9 @@ +--- +title: XDC DAO User Guide +--- + +# XDC DAO User Guide + +This guide explains how to participate in XDC DAO governance, including creating proposals, voting, delegating voting power, and reviewing passed proposals. + +*Content to be added.* diff --git a/website/docs/xdcchain/img/cleanup.png b/website/docs/xdcchain/img/cleanup.png new file mode 100644 index 00000000..48d925b3 Binary files /dev/null and b/website/docs/xdcchain/img/cleanup.png differ diff --git a/website/docs/xdcchain/img/installation.png b/website/docs/xdcchain/img/installation.png new file mode 100644 index 00000000..16a7ae95 Binary files /dev/null and b/website/docs/xdcchain/img/installation.png differ diff --git a/website/docs/xdcchain/img/installation1.png b/website/docs/xdcchain/img/installation1.png new file mode 100644 index 00000000..7732dfd8 Binary files /dev/null and b/website/docs/xdcchain/img/installation1.png differ diff --git a/website/docs/xdcchain/img/installation2.png b/website/docs/xdcchain/img/installation2.png new file mode 100644 index 00000000..63a53798 Binary files /dev/null and b/website/docs/xdcchain/img/installation2.png differ