diff --git a/website/docs/xdcchain/developers/explorers/advanced-features.md b/website/docs/xdcchain/developers/explorers/advanced-features.md new file mode 100644 index 00000000..dcedac0c --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/advanced-features.md @@ -0,0 +1,92 @@ +--- +title: Advanced Features +--- + +## Advanced Features + +### Event Log Decoding + +Event logs are emitted by smart contracts during transaction execution. The explorer decodes these logs when the contract is verified, displaying human-readable event names and parameters. + +**Viewing Event Logs:** + +1. Navigate to a transaction detail page +2. Scroll to the **Logs** section +3. View decoded event names (e.g., `Transfer`, `Approval`) +4. Expand individual logs to see parameter names and values + +**Topics Structure:** + +- **Topic 0:** Event signature hash (keccak256 of event definition) +- **Topic 1-3:** Indexed parameters (up to 3) +- **Data:** Non-indexed parameters (ABI-encoded) + +**Example Transfer Event:** + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +Decoded display: + +- Topic 0: `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef` +- Topic 1 (from): `0x000...0001234...abcd` +- Topic 2 (to): `0x000...0005678...efgh` +- Data (value): `1000000000000000000` + +### Internal Transactions + +Internal transactions are value transfers and contract calls triggered by external transactions. They are not recorded as separate transactions on the blockchain but can be traced through execution. + +**Accessing Internal Transactions:** + +1. Open a transaction detail page +2. Click the **Internal Transactions** tab +3. View the call trace showing: + - Call depth and type (CALL, DELEGATECALL, STATICCALL) + - From and to addresses + - Value transferred + - Gas used by each internal call + +**Use Cases:** + +- Tracking multi-hop transfers +- Debugging contract interactions +- Analyzing DeFi protocol flows +- Verifying token swap paths + +### Gas Tracker + +The gas tracker provides real-time and historical gas price data, helping users optimize transaction costs. + +**Metrics Available:** + +- **Safe Gas Price:** Confirmed within expected time +- **Propose Gas Price:** Standard confirmation speed +- **Fast Gas Price:** Priority confirmation +- **Average Block Time:** Current network block interval +- **Average Gas Limit:** Typical block capacity + +**Historical Gas Charts:** + +View gas price trends over time to identify optimal transaction windows and network congestion patterns. + +### Analytics Dashboard + +The explorer provides network-wide analytics for macro-level blockchain analysis. + +**Available Charts:** + +- Daily transaction count +- Active address count +- XDC transfer volume +- Smart contract deployments +- Validator performance metrics +- Token transfer volume by category + +**Export Options:** + +Most charts support CSV export for custom analysis in spreadsheet or data science tools. + +--- + diff --git a/website/docs/xdcchain/developers/explorers/api.md b/website/docs/xdcchain/developers/explorers/api.md new file mode 100644 index 00000000..f8d5d4ea --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/api.md @@ -0,0 +1,249 @@ +--- +title: Example usage +--- + +## API Documentation + +Both XDCScan and Apothem Explorer provide REST APIs for programmatic access to blockchain data. The API enables integration with wallets, dashboards, trading bots, and analytics platforms. + +### API Key Setup + +**Creating an API Key:** + +1. Create an account on XDCScan (registration required) +2. Navigate to **API Keys** in account settings +3. Click **Create API Key** +4. Name your key (e.g., "Production Dashboard") +5. Copy the generated key immediately (shown only once) + +**Rate Limits:** + +| Plan | Requests per Second | Daily Limit | +|------|---------------------|-------------| +| Free | 5 | 10,000 | +| Standard | 10 | 100,000 | +| Professional | 25 | 500,000 | +| Enterprise | Custom | Custom | + +**Authentication:** + +Include the API key as a query parameter: + +``` +https://xdcscan.io/api?module=account&action=balance&address=xdc1234...&apikey=YourApiKey +``` + +### Core API Endpoints + +#### Account Module + +**Get XDC Balance:** + +``` +GET /api?module=account&action=balance&address={address}&tag=latest&apikey={key} +``` + +Response: + +```json +{ + "status": "1", + "message": "OK", + "result": "1000000000000000000" +} +``` + +**Get Transaction List:** + +``` +GET /api?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={key} +``` + +**Get Token Transfer Events:** + +``` +GET /api?module=account&action=tokentx&contractaddress={token}&address={holder}&page=1&offset=100&apikey={key} +``` + +**Get Token Balance:** + +``` +GET /api?module=account&action=tokenbalance&contractaddress={token}&address={holder}&tag=latest&apikey={key} +``` + +#### Contract Module + +**Get Contract ABI:** + +``` +GET /api?module=contract&action=getabi&address={contract}&apikey={key} +``` + +Response: + +```json +{ + "status": "1", + "message": "OK", + "result": "[{...}]" +} +``` + +**Get Contract Source Code:** + +``` +GET /api?module=contract&action=getsourcecode&address={contract}&apikey={key} +``` + +#### Transaction Module + +**Get Transaction Receipt Status:** + +``` +GET /api?module=transaction&action=gettxreceiptstatus&txhash={hash}&apikey={key} +``` + +**Get Transaction Status:** + +``` +GET /api?module=transaction&action=getstatus&txhash={hash}&apikey={key} +``` + +#### Block Module + +**Get Block Reward:** + +``` +GET /api?module=block&action=getblockreward&blockno={number}&apikey={key} +``` + +**Get Block Countdown:** + +``` +GET /api?module=block&action=getblockcountdown&blockno={number}&apikey={key} +``` + +#### Stats Module + +**Get XDC Supply:** + +``` +GET /api?module=stats&action=xdcsupply&apikey={key} +``` + +**Get Validators:** + +``` +GET /api?module=stats&action=validators&apikey={key} +``` + +### API Response Format + +All API responses follow a standard JSON structure: + +```json +{ + "status": "1", + "message": "OK", + "result": "..." +} +``` + +**Status Codes:** + +| Status | Meaning | +|--------|---------| +| "1" | Success | +| "0" | Error or no data | + +**Error Handling:** + +```javascript +const response = await fetch(apiUrl); +const data = await response.json(); + +if (data.status === "0") { + console.error("API Error:", data.message); + // Handle error: rate limit, invalid parameters, etc. +} else { + // Process data.result +} +``` + +### Python API Client Example + +```python +import requests + +API_KEY = "YourApiKey" +BASE_URL = "https://xdcscan.io/api" + +def get_balance(address): + params = { + "module": "account", + "action": "balance", + "address": address, + "tag": "latest", + "apikey": API_KEY + } + response = requests.get(BASE_URL, params=params) + data = response.json() + + if data["status"] == "1": + # Convert wei to XDC + balance_xdc = int(data["result"]) / 10**18 + return balance_xdc + else: + raise Exception(f"API Error: {data['message']}") + +# Example usage +address = "xdc1234567890abcdef1234567890abcdef12345678" +balance = get_balance(address) +print(f"Balance: {balance} XDC") +``` + +### JavaScript API Client Example + +```javascript +const API_KEY = "YourApiKey"; +const BASE_URL = "https://xdcscan.io/api"; + +async function getTransactions(address, page = 1, offset = 10) { + const params = new URLSearchParams({ + module: "account", + action: "txlist", + address: address, + startblock: "0", + endblock: "99999999", + page: page.toString(), + offset: offset.toString(), + sort: "desc", + apikey: API_KEY + }); + + const response = await fetch(`${BASE_URL}?${params}`); + const data = await response.json(); + + if (data.status === "1") { + return data.result.map(tx => ({ + hash: tx.hash, + from: tx.from, + to: tx.to, + value: parseInt(tx.value) / 1e18, + timestamp: new Date(parseInt(tx.timeStamp) * 1000), + gasUsed: tx.gasUsed, + status: tx.txreceipt_status === "1" ? "Success" : "Failed" + })); + } else { + throw new Error(data.message); + } +} + +// Example usage +getTransactions("xdc1234...abcd", 1, 5) + .then(txs => console.log(txs)) + .catch(err => console.error(err)); +``` + +--- + diff --git a/website/docs/xdcchain/developers/explorers/basic-usage.md b/website/docs/xdcchain/developers/explorers/basic-usage.md new file mode 100644 index 00000000..246ead8f --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/basic-usage.md @@ -0,0 +1,126 @@ +--- +title: Basic Usage +--- + +## Basic Usage + +### Searching the Blockchain + +The search bar is the primary entry point for all explorer queries. It accepts multiple input types and automatically routes to the appropriate result page. + +**Supported Search Types:** + +| Input Type | Example | Result Page | +|------------|---------|-------------| +| Wallet Address | `xdc1234...abcd` | Address detail page | +| Transaction Hash | `0xabcd...1234` | Transaction detail page | +| Block Number | `12345678` | Block detail page | +| Token Name | "XDC Token" | Token search results | +| Token Symbol | "XDC" | Token detail page | + +**Search Tips:** + +- Addresses must include the `xdc` prefix (not `0x`) +- Transaction hashes must be complete 66-character hex strings +- Block numbers can be entered as plain integers +- Partial token names trigger search results with matching tokens + +### Viewing Transaction Details + +A transaction detail page provides complete information about a single blockchain transaction. + +**Core Fields:** + +- **Transaction Hash:** Unique identifier for the transaction +- **Status:** Success, Failed, or Pending +- **Block:** Block number containing the transaction +- **Timestamp:** Exact time of block confirmation +- **From:** Sender address +- **To:** Recipient address (or contract address for contract creation) +- **Value:** Amount of XDC transferred +- **Transaction Fee:** Gas used multiplied by gas price +- **Gas Limit:** Maximum gas allocated by sender +- **Gas Used:** Actual gas consumed +- **Gas Price:** Price per unit of gas in wei +- **Nonce:** Transaction sequence number for the sender +- **Input Data:** Raw transaction payload (hexadecimal) + +**Status Indicators:** + +- **Success:** Green checkmark; transaction executed without errors +- **Failed:** Red warning; transaction reverted; gas still consumed +- **Pending:** Yellow spinner; transaction in mempool awaiting inclusion + +### Inspecting Addresses + +An address detail page aggregates all activity for a specific wallet or contract. + +**Wallet Address Page:** + +- **Balance:** Current XDC balance +- **XDC Value:** USD equivalent (XDCScan only) +- **Transaction Count:** Total transactions sent and received +- **Transaction History:** Chronological list with pagination +- **Token Holdings:** List of XRC20 and XRC721 tokens held +- **Token Transfers:** Filterable token transaction history + +**Contract Address Page:** + +All wallet fields plus: + +- **Contract Creator:** Address that deployed the contract +- **Creation Transaction:** Hash of the deployment transaction +- **Verified Source Code:** If contract has been verified +- **Contract ABI:** Application Binary Interface for interaction +- **Read Contract:** Direct read-only function calls +- **Write Contract:** Direct state-changing function calls (requires wallet connection) +- **Contract Transactions:** All transactions targeting the contract + +### Browsing Blocks + +The block detail page shows aggregate data for a single block in the blockchain. + +**Block Fields:** + +- **Block Height:** Sequential block number +- **Timestamp:** Exact confirmation time +- **Transactions:** Count and list of included transactions +- **Validator:** Address of the masternode that produced the block +- **Block Hash:** Unique cryptographic hash of the block +- **Parent Hash:** Hash of the previous block +- **Gas Used:** Total gas consumed by all transactions +- **Gas Limit:** Maximum gas allowed for the block +- **Block Size:** Data size in bytes +- **Nonce:** Mining nonce (for XDPoS consensus) + +**Block Navigation:** + +- Click "Previous Block" or "Next Block" to navigate sequentially +- Jump to any block by entering the number in the search bar + +### Tracking Tokens + +Token detail pages provide comprehensive analytics for XRC20 fungible tokens and XRC721/XRC1155 non-fungible tokens. + +**XRC20 Token Page:** + +- **Token Contract:** Contract address +- **Total Supply:** Circulating token supply +- **Holders:** Number of unique holder addresses +- **Transfers:** Total transfer transaction count +- **Price:** Current market price (if listed) +- **Market Cap:** Total supply multiplied by price +- **Holder Distribution:** Top holders with percentages +- **Transfer History:** Recent token transfers with pagination + +**XRC721/XRC1155 Token Page:** + +- **Collection Name:** NFT collection identifier +- **Total Supply:** Number of minted tokens +- **Unique Holders:** Number of unique owners +- **Transfers:** Total transfer count +- **Token List:** Individual token IDs with metadata links +- **Recent Transfers:** Latest NFT transactions + +--- + diff --git a/website/docs/xdcchain/developers/explorers/best-practices.md b/website/docs/xdcchain/developers/explorers/best-practices.md new file mode 100644 index 00000000..a3e223c8 --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/best-practices.md @@ -0,0 +1,29 @@ +--- +title: Best Practices +--- + +## Best Practices + +### For Developers + +1. **Verify All Production Contracts:** Always verify source code for contracts users interact with +2. **Use APIs for Dashboards:** Build monitoring dashboards using explorer APIs instead of direct RPC for better performance +3. **Monitor Gas Prices:** Check gas tracker before submitting large batches of transactions +4. **Test on Apothem First:** Verify contracts and test integrations on testnet before mainnet +5. **Implement Caching:** Cache API responses to reduce load and improve application responsiveness + +### For Users + +1. **Verify Before Trusting:** Check contract verification status before interacting with DeFi protocols +2. **Double-Check Addresses:** Always verify recipient addresses on the explorer before large transfers +3. **Monitor Transactions:** Track pending transactions and confirm successful execution +4. **Review Event Logs:** For complex interactions, review decoded event logs to confirm expected outcomes + +### For Validators + +1. **Monitor Block Production:** Use explorer to verify your masternode is producing blocks correctly +2. **Track Rewards:** Monitor block rewards and transaction fee accumulation +3. **Analyze Performance:** Review missed blocks and optimize node connectivity + +--- + diff --git a/website/docs/xdcchain/developers/explorers/contract-verification.md b/website/docs/xdcchain/developers/explorers/contract-verification.md new file mode 100644 index 00000000..3f494c46 --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/contract-verification.md @@ -0,0 +1,153 @@ +--- +title: Contract Verification +--- + +## Contract Verification + +Verifying smart contract source code on the explorer is essential for transparency and user trust. Verified contracts display readable source code, ABI, and enable direct interaction through the explorer interface. + +### Why Verify Contracts + +**Benefits:** + +- Users can audit source code before interacting +- Explorer displays function names instead of raw selectors +- Direct contract interaction via Read/Write tabs +- Establishes developer credibility and project legitimacy +- Enables third-party integrations and tooling + +### Verification Prerequisites + +Before submitting for verification, ensure you have: + +1. **Source Code:** Original Solidity or Vyper source files +2. **Compiler Version:** Exact compiler version used for deployment +3. **Optimization Settings:** Whether optimization was enabled and the runs parameter +4. **Constructor Arguments:** ABI-encoded constructor parameters (if any) +5. **Flattened Code:** Single-file version if using multi-file import statements + +### Single File Verification + +For contracts without external imports or with already-flattened code. + +**Steps:** + +1. Navigate to the contract address page on the explorer +2. Click the **Verify and Publish** button +3. Select **Solidity (Single File)** as the compiler type +4. Choose the exact compiler version from the dropdown +5. Select the appropriate license type +6. Paste the complete source code into the text area +7. Configure optimization settings to match deployment +8. Enter constructor arguments if the contract required them +9. Click **Verify and Publish** + +**Result:** The explorer compiles the submitted code and compares the generated bytecode with the on-chain bytecode. If they match, verification succeeds. + +### Multi-File Verification + +For contracts using import statements and multiple source files. + +**Steps:** + +1. Click **Verify and Publish** on the contract page +2. Select **Solidity (Multi-Part Files)** +3. Choose compiler version and license +4. Upload all Solidity files including imported dependencies +5. Ensure the main contract file is clearly identified +6. Configure optimization and constructor arguments +7. Submit for verification + +**Tips:** + +- Use the same file structure as your development environment +- Include all OpenZeppelin or library imports +- The main contract should match the deployed contract name + +### Flattening Code + +Flattening combines all imports into a single file for easier single-file verification. + +**Using Hardhat:** + +```bash +npm install --save-dev hardhat-abi-exporter +npx hardhat flatten contracts/MyContract.sol > flattened.sol +``` + +**Using Foundry:** + +```bash +forge flatten --output flattened.sol src/MyContract.sol +``` + +**Using Remix IDE:** + +1. Open the contract in Remix +2. Right-click in the file explorer +3. Select **Flatten** option +4. Copy the flattened output + +### Constructor Arguments + +Contracts with constructors require ABI-encoded arguments for verification. + +**Encoding Manually:** + +Use the online ABI encoder or web3.js: + +```javascript +const Web3 = require('web3'); +const web3 = new Web3(); + +const args = [ + "MyToken", // string + "MTK", // string + 18, // uint8 + web3.utils.toWei("1000000", "ether") // uint256 +]; + +const encoded = web3.eth.abi.encodeParameters( + ['string', 'string', 'uint8', 'uint256'], + args +); +console.log(encoded); +``` + +**Common Patterns:** + +- No constructor: Leave blank +- Single address: `0x0000000000000000000000001234...abcd` +- Multiple values: Concatenate ABI-encoded values + +### Proxy Contract Verification + +Proxy patterns (Transparent Proxy, UUPS, Beacon) require special verification steps. + +**Verification Process:** + +1. Verify the implementation contract first +2. Navigate to the proxy contract address +3. Select **Solidity (Single File)** or appropriate option +4. Paste the proxy contract source code (minimal proxy code) +5. In the **More Options** section, mark as proxy +6. Enter the implementation contract address +7. Submit for verification + +**Reading Proxy Contracts:** + +Once verified as a proxy, the explorer automatically routes Read/Write calls to the implementation contract while displaying the proxy address. + +### Troubleshooting Verification Failures + +| Error | Cause | Solution | +|-------|-------|----------| +| Bytecode mismatch | Wrong compiler version | Verify exact version from deployment logs | +| Bytecode mismatch | Optimization mismatch | Match optimization enabled/disabled and runs | +| Bytecode mismatch | Extra metadata | Ensure no metadata hash differences | +| Missing constructor args | Empty constructor field | Provide ABI-encoded constructor arguments | +| Import not found | Missing dependency file | Use multi-file verification or flatten | +| SPDX license mismatch | Wrong license selected | Match license from source code comments | + +--- + diff --git a/website/docs/xdcchain/developers/explorers/index.md b/website/docs/xdcchain/developers/explorers/index.md new file mode 100644 index 00000000..66e4a6f4 --- /dev/null +++ b/website/docs/xdcchain/developers/explorers/index.md @@ -0,0 +1,769 @@ +--- +title: "XDC Block Explorer Guide +related_pages: + - ./explorers/basic-usage.md + - ./explorers/contract-verification.md + - ./explorers/api.md + - ./explorers/advanced-features.md + - ./explorers/best-practices.md" +--- + +# XDC Block Explorer Guide + +XDC block explorers provide transparent access to blockchain data, enabling users to verify transactions, inspect smart contracts, track tokens, and analyze network activity. This guide covers both **XDCScan** (mainnet explorer) and **Apothem Explorer** (testnet explorer), providing comprehensive documentation for developers, validators, and everyday users. + +--- + +## Overview + +### What Is a Block Explorer + +A block explorer is a web-based tool that indexes and visualizes blockchain data in human-readable format. It serves as the primary interface between users and the underlying blockchain ledger, transforming raw block data, transaction hashes, and contract bytecode into searchable, navigable information. + +**Key Capabilities:** + +- Transaction verification and status tracking +- Address balance and transaction history lookup +- Smart contract source code verification +- Token supply, holder, and transfer analytics +- Block production and validator monitoring +- Gas price and network congestion analysis +- API access for programmatic data retrieval + +### XDCScan vs Apothem Explorer + +| Feature | XDCScan (Mainnet) | Apothem Explorer (Testnet) | +|---------|-------------------|---------------------------| +| Network | XDC Mainnet | XDC Apothem Testnet | +| URL | https://xdcscan.io | https://apothem.xdcscan.io | +| Data | Production transactions | Test transactions | +| API | Production API keys | Test API keys | +| Use Case | Production monitoring | Development and testing | +| Value | Real XDC tokens | Test XDC (faucet available) | + +Both explorers share identical interfaces and feature sets, making it seamless to transition from testnet development to mainnet deployment. + +--- + +## Getting Started + +### Accessing the Explorers + +Navigate directly to the explorer URLs in any modern web browser. No authentication is required for basic browsing. For API access and advanced features, account creation and API key generation are necessary. + +**XDCScan:** https://xdcscan.io + +**Apothem Explorer:** https://apothem.xdcscan.io + +### Explorer Interface Overview + +The explorer homepage presents a dashboard with the following primary sections: + +**Header Navigation:** + +- Search bar (supports addresses, transaction hashes, block numbers, and token names) +- Network selector (Mainnet / Testnet toggle on some interfaces) +- API and developer tools links + +**Dashboard Panels:** + +- Latest blocks with timestamp, validator, and transaction count +- Recent transactions with status, value, and gas used +- Network statistics (current block height, average block time, active validators) +- XDC price and market data (on XDCScan) + +**Footer Links:** + +- API documentation +- Contract verification portal +- Terms of service and privacy policy + +--- + +## Basic Usage + +### Searching the Blockchain + +The search bar is the primary entry point for all explorer queries. It accepts multiple input types and automatically routes to the appropriate result page. + +**Supported Search Types:** + +| Input Type | Example | Result Page | +|------------|---------|-------------| +| Wallet Address | `xdc1234...abcd` | Address detail page | +| Transaction Hash | `0xabcd...1234` | Transaction detail page | +| Block Number | `12345678` | Block detail page | +| Token Name | "XDC Token" | Token search results | +| Token Symbol | "XDC" | Token detail page | + +**Search Tips:** + +- Addresses must include the `xdc` prefix (not `0x`) +- Transaction hashes must be complete 66-character hex strings +- Block numbers can be entered as plain integers +- Partial token names trigger search results with matching tokens + +### Viewing Transaction Details + +A transaction detail page provides complete information about a single blockchain transaction. + +**Core Fields:** + +- **Transaction Hash:** Unique identifier for the transaction +- **Status:** Success, Failed, or Pending +- **Block:** Block number containing the transaction +- **Timestamp:** Exact time of block confirmation +- **From:** Sender address +- **To:** Recipient address (or contract address for contract creation) +- **Value:** Amount of XDC transferred +- **Transaction Fee:** Gas used multiplied by gas price +- **Gas Limit:** Maximum gas allocated by sender +- **Gas Used:** Actual gas consumed +- **Gas Price:** Price per unit of gas in wei +- **Nonce:** Transaction sequence number for the sender +- **Input Data:** Raw transaction payload (hexadecimal) + +**Status Indicators:** + +- **Success:** Green checkmark; transaction executed without errors +- **Failed:** Red warning; transaction reverted; gas still consumed +- **Pending:** Yellow spinner; transaction in mempool awaiting inclusion + +### Inspecting Addresses + +An address detail page aggregates all activity for a specific wallet or contract. + +**Wallet Address Page:** + +- **Balance:** Current XDC balance +- **XDC Value:** USD equivalent (XDCScan only) +- **Transaction Count:** Total transactions sent and received +- **Transaction History:** Chronological list with pagination +- **Token Holdings:** List of XRC20 and XRC721 tokens held +- **Token Transfers:** Filterable token transaction history + +**Contract Address Page:** + +All wallet fields plus: + +- **Contract Creator:** Address that deployed the contract +- **Creation Transaction:** Hash of the deployment transaction +- **Verified Source Code:** If contract has been verified +- **Contract ABI:** Application Binary Interface for interaction +- **Read Contract:** Direct read-only function calls +- **Write Contract:** Direct state-changing function calls (requires wallet connection) +- **Contract Transactions:** All transactions targeting the contract + +### Browsing Blocks + +The block detail page shows aggregate data for a single block in the blockchain. + +**Block Fields:** + +- **Block Height:** Sequential block number +- **Timestamp:** Exact confirmation time +- **Transactions:** Count and list of included transactions +- **Validator:** Address of the masternode that produced the block +- **Block Hash:** Unique cryptographic hash of the block +- **Parent Hash:** Hash of the previous block +- **Gas Used:** Total gas consumed by all transactions +- **Gas Limit:** Maximum gas allowed for the block +- **Block Size:** Data size in bytes +- **Nonce:** Mining nonce (for XDPoS consensus) + +**Block Navigation:** + +- Click "Previous Block" or "Next Block" to navigate sequentially +- Jump to any block by entering the number in the search bar + +### Tracking Tokens + +Token detail pages provide comprehensive analytics for XRC20 fungible tokens and XRC721/XRC1155 non-fungible tokens. + +**XRC20 Token Page:** + +- **Token Contract:** Contract address +- **Total Supply:** Circulating token supply +- **Holders:** Number of unique holder addresses +- **Transfers:** Total transfer transaction count +- **Price:** Current market price (if listed) +- **Market Cap:** Total supply multiplied by price +- **Holder Distribution:** Top holders with percentages +- **Transfer History:** Recent token transfers with pagination + +**XRC721/XRC1155 Token Page:** + +- **Collection Name:** NFT collection identifier +- **Total Supply:** Number of minted tokens +- **Unique Holders:** Number of unique owners +- **Transfers:** Total transfer count +- **Token List:** Individual token IDs with metadata links +- **Recent Transfers:** Latest NFT transactions + +--- + +## Contract Verification + +Verifying smart contract source code on the explorer is essential for transparency and user trust. Verified contracts display readable source code, ABI, and enable direct interaction through the explorer interface. + +### Why Verify Contracts + +**Benefits:** + +- Users can audit source code before interacting +- Explorer displays function names instead of raw selectors +- Direct contract interaction via Read/Write tabs +- Establishes developer credibility and project legitimacy +- Enables third-party integrations and tooling + +### Verification Prerequisites + +Before submitting for verification, ensure you have: + +1. **Source Code:** Original Solidity or Vyper source files +2. **Compiler Version:** Exact compiler version used for deployment +3. **Optimization Settings:** Whether optimization was enabled and the runs parameter +4. **Constructor Arguments:** ABI-encoded constructor parameters (if any) +5. **Flattened Code:** Single-file version if using multi-file import statements + +### Single File Verification + +For contracts without external imports or with already-flattened code. + +**Steps:** + +1. Navigate to the contract address page on the explorer +2. Click the **Verify and Publish** button +3. Select **Solidity (Single File)** as the compiler type +4. Choose the exact compiler version from the dropdown +5. Select the appropriate license type +6. Paste the complete source code into the text area +7. Configure optimization settings to match deployment +8. Enter constructor arguments if the contract required them +9. Click **Verify and Publish** + +**Result:** The explorer compiles the submitted code and compares the generated bytecode with the on-chain bytecode. If they match, verification succeeds. + +### Multi-File Verification + +For contracts using import statements and multiple source files. + +**Steps:** + +1. Click **Verify and Publish** on the contract page +2. Select **Solidity (Multi-Part Files)** +3. Choose compiler version and license +4. Upload all Solidity files including imported dependencies +5. Ensure the main contract file is clearly identified +6. Configure optimization and constructor arguments +7. Submit for verification + +**Tips:** + +- Use the same file structure as your development environment +- Include all OpenZeppelin or library imports +- The main contract should match the deployed contract name + +### Flattening Code + +Flattening combines all imports into a single file for easier single-file verification. + +**Using Hardhat:** + +```bash +npm install --save-dev hardhat-abi-exporter +npx hardhat flatten contracts/MyContract.sol > flattened.sol +``` + +**Using Foundry:** + +```bash +forge flatten --output flattened.sol src/MyContract.sol +``` + +**Using Remix IDE:** + +1. Open the contract in Remix +2. Right-click in the file explorer +3. Select **Flatten** option +4. Copy the flattened output + +### Constructor Arguments + +Contracts with constructors require ABI-encoded arguments for verification. + +**Encoding Manually:** + +Use the online ABI encoder or web3.js: + +```javascript +const Web3 = require('web3'); +const web3 = new Web3(); + +const args = [ + "MyToken", // string + "MTK", // string + 18, // uint8 + web3.utils.toWei("1000000", "ether") // uint256 +]; + +const encoded = web3.eth.abi.encodeParameters( + ['string', 'string', 'uint8', 'uint256'], + args +); +console.log(encoded); +``` + +**Common Patterns:** + +- No constructor: Leave blank +- Single address: `0x0000000000000000000000001234...abcd` +- Multiple values: Concatenate ABI-encoded values + +### Proxy Contract Verification + +Proxy patterns (Transparent Proxy, UUPS, Beacon) require special verification steps. + +**Verification Process:** + +1. Verify the implementation contract first +2. Navigate to the proxy contract address +3. Select **Solidity (Single File)** or appropriate option +4. Paste the proxy contract source code (minimal proxy code) +5. In the **More Options** section, mark as proxy +6. Enter the implementation contract address +7. Submit for verification + +**Reading Proxy Contracts:** + +Once verified as a proxy, the explorer automatically routes Read/Write calls to the implementation contract while displaying the proxy address. + +### Troubleshooting Verification Failures + +| Error | Cause | Solution | +|-------|-------|----------| +| Bytecode mismatch | Wrong compiler version | Verify exact version from deployment logs | +| Bytecode mismatch | Optimization mismatch | Match optimization enabled/disabled and runs | +| Bytecode mismatch | Extra metadata | Ensure no metadata hash differences | +| Missing constructor args | Empty constructor field | Provide ABI-encoded constructor arguments | +| Import not found | Missing dependency file | Use multi-file verification or flatten | +| SPDX license mismatch | Wrong license selected | Match license from source code comments | + +--- + +## API Documentation + +Both XDCScan and Apothem Explorer provide REST APIs for programmatic access to blockchain data. The API enables integration with wallets, dashboards, trading bots, and analytics platforms. + +### API Key Setup + +**Creating an API Key:** + +1. Create an account on XDCScan (registration required) +2. Navigate to **API Keys** in account settings +3. Click **Create API Key** +4. Name your key (e.g., "Production Dashboard") +5. Copy the generated key immediately (shown only once) + +**Rate Limits:** + +| Plan | Requests per Second | Daily Limit | +|------|---------------------|-------------| +| Free | 5 | 10,000 | +| Standard | 10 | 100,000 | +| Professional | 25 | 500,000 | +| Enterprise | Custom | Custom | + +**Authentication:** + +Include the API key as a query parameter: + +``` +https://xdcscan.io/api?module=account&action=balance&address=xdc1234...&apikey=YourApiKey +``` + +### Core API Endpoints + +#### Account Module + +**Get XDC Balance:** + +``` +GET /api?module=account&action=balance&address={address}&tag=latest&apikey={key} +``` + +Response: + +```json +{ + "status": "1", + "message": "OK", + "result": "1000000000000000000" +} +``` + +**Get Transaction List:** + +``` +GET /api?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={key} +``` + +**Get Token Transfer Events:** + +``` +GET /api?module=account&action=tokentx&contractaddress={token}&address={holder}&page=1&offset=100&apikey={key} +``` + +**Get Token Balance:** + +``` +GET /api?module=account&action=tokenbalance&contractaddress={token}&address={holder}&tag=latest&apikey={key} +``` + +#### Contract Module + +**Get Contract ABI:** + +``` +GET /api?module=contract&action=getabi&address={contract}&apikey={key} +``` + +Response: + +```json +{ + "status": "1", + "message": "OK", + "result": "[{...}]" +} +``` + +**Get Contract Source Code:** + +``` +GET /api?module=contract&action=getsourcecode&address={contract}&apikey={key} +``` + +#### Transaction Module + +**Get Transaction Receipt Status:** + +``` +GET /api?module=transaction&action=gettxreceiptstatus&txhash={hash}&apikey={key} +``` + +**Get Transaction Status:** + +``` +GET /api?module=transaction&action=getstatus&txhash={hash}&apikey={key} +``` + +#### Block Module + +**Get Block Reward:** + +``` +GET /api?module=block&action=getblockreward&blockno={number}&apikey={key} +``` + +**Get Block Countdown:** + +``` +GET /api?module=block&action=getblockcountdown&blockno={number}&apikey={key} +``` + +#### Stats Module + +**Get XDC Supply:** + +``` +GET /api?module=stats&action=xdcsupply&apikey={key} +``` + +**Get Validators:** + +``` +GET /api?module=stats&action=validators&apikey={key} +``` + +### API Response Format + +All API responses follow a standard JSON structure: + +```json +{ + "status": "1", + "message": "OK", + "result": "..." +} +``` + +**Status Codes:** + +| Status | Meaning | +|--------|---------| +| "1" | Success | +| "0" | Error or no data | + +**Error Handling:** + +```javascript +const response = await fetch(apiUrl); +const data = await response.json(); + +if (data.status === "0") { + console.error("API Error:", data.message); + // Handle error: rate limit, invalid parameters, etc. +} else { + // Process data.result +} +``` + +### Python API Client Example + +```python +import requests + +API_KEY = "YourApiKey" +BASE_URL = "https://xdcscan.io/api" + +def get_balance(address): + params = { + "module": "account", + "action": "balance", + "address": address, + "tag": "latest", + "apikey": API_KEY + } + response = requests.get(BASE_URL, params=params) + data = response.json() + + if data["status"] == "1": + # Convert wei to XDC + balance_xdc = int(data["result"]) / 10**18 + return balance_xdc + else: + raise Exception(f"API Error: {data['message']}") + +# Example usage +address = "xdc1234567890abcdef1234567890abcdef12345678" +balance = get_balance(address) +print(f"Balance: {balance} XDC") +``` + +### JavaScript API Client Example + +```javascript +const API_KEY = "YourApiKey"; +const BASE_URL = "https://xdcscan.io/api"; + +async function getTransactions(address, page = 1, offset = 10) { + const params = new URLSearchParams({ + module: "account", + action: "txlist", + address: address, + startblock: "0", + endblock: "99999999", + page: page.toString(), + offset: offset.toString(), + sort: "desc", + apikey: API_KEY + }); + + const response = await fetch(`${BASE_URL}?${params}`); + const data = await response.json(); + + if (data.status === "1") { + return data.result.map(tx => ({ + hash: tx.hash, + from: tx.from, + to: tx.to, + value: parseInt(tx.value) / 1e18, + timestamp: new Date(parseInt(tx.timeStamp) * 1000), + gasUsed: tx.gasUsed, + status: tx.txreceipt_status === "1" ? "Success" : "Failed" + })); + } else { + throw new Error(data.message); + } +} + +// Example usage +getTransactions("xdc1234...abcd", 1, 5) + .then(txs => console.log(txs)) + .catch(err => console.error(err)); +``` + +--- + +## Advanced Features + +### Event Log Decoding + +Event logs are emitted by smart contracts during transaction execution. The explorer decodes these logs when the contract is verified, displaying human-readable event names and parameters. + +**Viewing Event Logs:** + +1. Navigate to a transaction detail page +2. Scroll to the **Logs** section +3. View decoded event names (e.g., `Transfer`, `Approval`) +4. Expand individual logs to see parameter names and values + +**Topics Structure:** + +- **Topic 0:** Event signature hash (keccak256 of event definition) +- **Topic 1-3:** Indexed parameters (up to 3) +- **Data:** Non-indexed parameters (ABI-encoded) + +**Example Transfer Event:** + +```solidity +event Transfer(address indexed from, address indexed to, uint256 value); +``` + +Decoded display: + +- Topic 0: `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef` +- Topic 1 (from): `0x000...0001234...abcd` +- Topic 2 (to): `0x000...0005678...efgh` +- Data (value): `1000000000000000000` + +### Internal Transactions + +Internal transactions are value transfers and contract calls triggered by external transactions. They are not recorded as separate transactions on the blockchain but can be traced through execution. + +**Accessing Internal Transactions:** + +1. Open a transaction detail page +2. Click the **Internal Transactions** tab +3. View the call trace showing: + - Call depth and type (CALL, DELEGATECALL, STATICCALL) + - From and to addresses + - Value transferred + - Gas used by each internal call + +**Use Cases:** + +- Tracking multi-hop transfers +- Debugging contract interactions +- Analyzing DeFi protocol flows +- Verifying token swap paths + +### Gas Tracker + +The gas tracker provides real-time and historical gas price data, helping users optimize transaction costs. + +**Metrics Available:** + +- **Safe Gas Price:** Confirmed within expected time +- **Propose Gas Price:** Standard confirmation speed +- **Fast Gas Price:** Priority confirmation +- **Average Block Time:** Current network block interval +- **Average Gas Limit:** Typical block capacity + +**Historical Gas Charts:** + +View gas price trends over time to identify optimal transaction windows and network congestion patterns. + +### Analytics Dashboard + +The explorer provides network-wide analytics for macro-level blockchain analysis. + +**Available Charts:** + +- Daily transaction count +- Active address count +- XDC transfer volume +- Smart contract deployments +- Validator performance metrics +- Token transfer volume by category + +**Export Options:** + +Most charts support CSV export for custom analysis in spreadsheet or data science tools. + +--- + +## Troubleshooting + +### Common Issues + +**Transaction Not Found:** + +- Verify the transaction hash is complete (66 characters) +- Check if the transaction was broadcast to the correct network (mainnet vs testnet) +- Pending transactions may take time to appear; wait for block inclusion +- If recently submitted, the transaction may still be in the mempool + +**Balance Discrepancy:** + +- Ensure you are viewing the correct network explorer +- Check for pending outgoing transactions that reduce available balance +- Verify the address format includes the `xdc` prefix +- Remember that token balances are separate from XDC native balance + +**Contract Verification Failed:** + +- Double-check compiler version matches deployment exactly +- Verify optimization settings are identical +- Ensure constructor arguments are properly ABI-encoded +- Try flattening multi-file contracts into a single file +- Check for SPDX license comment mismatches + +**API Rate Limit Exceeded:** + +- Implement request throttling in your application +- Cache responses for frequently accessed data +- Consider upgrading to a paid API plan for higher limits +- Use batch requests where supported + +### Explorer-Specific Notes + +**XDCScan Mainnet:** + +- Serves production data; all values are real +- API keys are shared with Apothem for convenience +- Price data sourced from aggregated exchange APIs + +**Apothem Testnet:** + +- Test XDC has no real value +- Faucet available at https://faucet.apothem.network +- Same API structure as mainnet for seamless testing +- Useful for verifying contracts before mainnet deployment + +--- + +## Best Practices + +### For Developers + +1. **Verify All Production Contracts:** Always verify source code for contracts users interact with +2. **Use APIs for Dashboards:** Build monitoring dashboards using explorer APIs instead of direct RPC for better performance +3. **Monitor Gas Prices:** Check gas tracker before submitting large batches of transactions +4. **Test on Apothem First:** Verify contracts and test integrations on testnet before mainnet +5. **Implement Caching:** Cache API responses to reduce load and improve application responsiveness + +### For Users + +1. **Verify Before Trusting:** Check contract verification status before interacting with DeFi protocols +2. **Double-Check Addresses:** Always verify recipient addresses on the explorer before large transfers +3. **Monitor Transactions:** Track pending transactions and confirm successful execution +4. **Review Event Logs:** For complex interactions, review decoded event logs to confirm expected outcomes + +### For Validators + +1. **Monitor Block Production:** Use explorer to verify your masternode is producing blocks correctly +2. **Track Rewards:** Monitor block rewards and transaction fee accumulation +3. **Analyze Performance:** Review missed blocks and optimize node connectivity + +--- + +## Related Topics + +- [Smart Contract Verification](/smartcontract/verify): Detailed contract verification workflow +- [API Reference](/api): Complete API endpoint documentation +- [Developer Quick Start](/xdcchain/developers/quick-guide): Getting started with XDC development +- [Wallet Configuration](/xdcchain/developers/wallet-configuration): Setting up wallets for development +- [XDC3.js SDK](../sdks/xdc3js.md): JavaScript SDK for blockchain interaction +- [Token Standards](/smartcontract/tokens): XRC20, XRC721, and XRC1155 specifications diff --git a/website/docs/xdcchain/developers/faucet.md b/website/docs/xdcchain/developers/faucet.md new file mode 100644 index 00000000..76c09e16 --- /dev/null +++ b/website/docs/xdcchain/developers/faucet.md @@ -0,0 +1,11 @@ +--- +title: Faucet +--- + +# Faucet + +The XDC faucet provides free testnet XDC tokens for development and testing on the Apothem testnet. + +You can request test XDC from the official faucet at [faucet.apothem.network](https://faucet.apothem.network/). + +*Detailed guide content to be added.* diff --git a/website/docs/xdcchain/developers/getxdclisted.md b/website/docs/xdcchain/developers/getxdclisted.md new file mode 100644 index 00000000..09ae969b --- /dev/null +++ b/website/docs/xdcchain/developers/getxdclisted.md @@ -0,0 +1,110 @@ +--- +title: Get XDC Listed +--- + +# Get XDC Listed + +## Overview +This guide provides essential resources and instructions for centralized exchanges (CEXs) and other service providers seeking to integrate or list the native token of the XDC Network — XDC. + +XDC Network is an enterprise-ready, EVM-compatible blockchain that offers fast, secure, and cost-efficient infrastructure for decentralized applications and tokenized assets. The native token, XDC, plays a central role in network security, transaction gas fees, and ecosystem utility. + +This page is intended to streamline the listing and integration process with technical specifications, wallet details, and official contact support. + +## Token Information + +- **Project Name:** XDC Network +- **Token Name:** XDC MainNet +- **Token Symbol/Ticker:** XDC +- **Token Type:** XRC20 (EVM Compatible) +- **Block Finality:** 32 Blocks +- **Decimals:** 18 +- **Pair Reference:** XDC:USDC, XDC:ETH, XDC:BTC, XDC:USD +- **Block Explorer:** https://xdcscan.io | https://xdcscan.com +- **Official Website:** https://www.xinfin.org +- **Technical White Paper:** https://xinfin.org/docs/whitepaper-tech.pdf +- **MICA White Paper:** https://xinfin.org/docs/xdc-mica-whitepaper.pdf +- **Logo Files (SVG/PNG):** [Download Here](https://xinfin.org/brand-assets) + +## Network Endpoints + +## Mainnet + +**RPC Endpoints:** + +- https://rpc.xinfin.network +- https://erpc.xinfin.network +- https://arpc.xinfin.network +- https://earpc.xinfin.network +- https://xdc.public-rpc.com/ +- https://rpc.primenumbers.xyz/ + +**eRPC Endpoints:** + +- https://erpc.xdcrpc.com +- https://erpc.xinfin.network + +**Network ID:** 50 + +**Explorers:** + +- https://xdcscan.com +- https://xdcscan.io +- https://xdc.blocksscan.io +- https://explorer.xinfin.network +- https://xdc.network + +**WebSocket Endpoints:** + +- wss://ws.xinfin.network +- wss://ews.xinfin.network +- wss://aws.xinfin.network +- wss://eaws.xinfin.network + +## Testnet (Apothem Network) + +**RPC Endpoints:** + +- https://rpc.apothem.network +- https://apothem.xdcrpc.com + +**eRPC Endpoint:** + +- https://erpc.apothem.network + +**Network ID:** 51 + +💧 **XDC Network Faucet** +To facilitate testing and development, the XDC Apothem Network Faucet provides free testnet XDC tokens. These can be used to test applications and smart contracts on the Apothem Network. + +- https://faucet.apothem.network +- https://faucet.blocksscan.io + +**Explorers:** + +- https://apothem.xdcscan.io +- https://apothem.blocksscan.io +- https://explorer.apothem.network + +**WebSocket Endpoint:** + +- wss://ws.apothem.network/ws + +**Find other RPC Endpoints** + +- **Mainnet:** https://chainlist.org/chain/50 +- **Testnet(Apothem):** https://chainlist.org/chain/51 + +## Wallet Integrations + +**Browser Extensions** + +- **XDCPay 2.0:** [Add to Browser](https://chrome.google.com/webstore/detail/xdcpay-20/iidmfamdbddcbjmemafekkohbnfiblhp) +- **XDCPay:** [Add to Browser](https://chrome.google.com/webstore/detail/xdcpay/bocpokimicclpaiekenaeelehdjllofo) +- **XDC Web Wallets - Beta:** [Access Beta Wallet](http://wallet.xdc.network/#/) +- **Multi-Chain Wallets - BlocksPay:** [Add to Browser](https://chrome.google.com/webstore/detail/blockspay-secure-multiple/pogabilnghhbafaheaepaaeopjpleimd) + +## Contact and Support +For technical assistance, integration support, or further inquiries regarding listing XDC on your platform, please reach out to the XDC Network team: + +**Email:** exchange@xinfin.org diff --git a/website/docs/xdcchain/developers/ipfs.md b/website/docs/xdcchain/developers/ipfs.md new file mode 100644 index 00000000..abd89d1f --- /dev/null +++ b/website/docs/xdcchain/developers/ipfs.md @@ -0,0 +1,419 @@ +--- +title: "IPFS Integration Guide — Decentralized Storage for XDC dApps and NFTs +description: Complete IPFS guide for XDC — Pinata setup, NFT metadata storage, dApp asset hosting, cost comparison, and performance benchmarks." +--- + +Difficulty: Beginner | Time: ~20 minutes | Tools: Pinata, NFT.Storage, IPFS CLI + +# IPFS Integration Guide — Decentralized Storage for XDC dApps and NFTs + +IPFS (InterPlanetary File System) is the decentralized standard for storing NFT metadata, dApp assets, and immutable content. This guide covers IPFS integration for XDC developers. + +## Prerequisites + +- Basic understanding of file storage and hashing +- [NFT Tutorial](/smartcontract/nft) (recommended for NFT metadata context) +- Pinata or NFT.Storage account (free tiers available) + +--- + +## IPFS Concepts + +### Decentralized Storage Basics + +IPFS is a peer-to-peer protocol for storing and sharing data in a distributed file system. Unlike HTTP which uses location-based addressing (`https://site.com/file`), IPFS uses content-based addressing (`ipfs://QmHash`). + +Key benefits: +- **Immutable**: Content cannot change without changing the hash +- **Decentralized**: No single point of failure +- **Verifiable**: Hash proves content integrity +- **Deduplication**: Same content stored once globally + +### Content Addressing + +Every file on IPFS has a unique Content Identifier (CID): + +``` +ipfs://QmXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx +``` + +The CID is derived from the file's content, not its location. Change one pixel in an image → completely different CID. + +### Pinning Services + +IPFS nodes garbage collect unpinned content. Pinning services ensure your content stays available: + +| Service | Free Tier | Paid Tier | Best For | +|---------|-----------|-----------|----------| +| **Pinata** | 1 GB | $20/100 GB | NFTs, dApps | +| **NFT.Storage** | 31 GB | Free for NFTs | NFT metadata | +| **Fleek** | 3 GB | $18/100 GB | Frontend hosting | +| **Web3.Storage** | 5 GB | $4/100 GB | General storage | + +### Gateway Usage + +IPFS gateways bridge the IPFS protocol to HTTP: + +``` +https://ipfs.io/ipfs/QmHash +https://gateway.pinata.cloud/ipfs/QmHash +https://cloudflare-ipfs.com/ipfs/QmHash +``` + +--- + +## Integration Options + +### Pinata Setup + +**Step 1 — Create Account** + +1. Go to [pinata.cloud](https://pinata.cloud/) +2. Sign up for free account +3. Get your API Key and Secret from the dashboard + +**Step 2 — Upload Files** + +Using the web interface: +1. Click "Add Files" +2. Select your files or folder +3. Wait for upload confirmation +4. Copy the CID + +Using the API: + +```bash title="Terminal" +curl -X POST https://api.pinata.cloud/pinning/pinFileToIPFS \ + -H "pinata_api_key: YOUR_API_KEY" \ + -H "pinata_secret_api_key: YOUR_SECRET" \ + -F "file=@metadata/0.json" +``` + +**Step 3 — Configure Dedicated Gateway** + +Get your dedicated gateway URL from Pinata dashboard: + +``` +https://yourgateway.mypinata.cloud/ipfs/QmHash +``` + +### NFT.Storage + +NFT.Storage is purpose-built for NFT metadata: + +**Step 1 — Get API Key** + +1. Go to [nft.storage](https://nft.storage/) +2. Sign in with GitHub or email +3. Copy your API key + +**Step 2 — Upload** + +```bash title="Terminal" +curl -X POST https://api.nft.storage/upload \ + -H "Authorization: Bearer *** \ + -H "Content-Type: application/json" \ + --data-binary @metadata/0.json +``` + +**Step 3 — Store CAR Files (for large collections)** + +```bash title="Terminal" +# Install nft.storage client +npm install nft.storage + +# Upload entire folder +node upload-collection.js +``` + +```javascript title="upload-collection.js" +import { NFTStorage, File } from 'nft.storage'; +import fs from 'fs'; +import path from 'path'; + +const client = new NFTStorage({ token: 'YOUR_API_KEY' }); + +async function uploadFolder(folderPath) { + const files = fs.readdirSync(folderPath); + const fileObjects = files.map(file => { + const content = fs.readFileSync(path.join(folderPath, file)); + return new File([content], file, { type: 'application/json' }); + }); + + const cid = await client.storeDirectory(fileObjects); + console.log('Uploaded to:', cid); + return cid; +} + +uploadFolder('./metadata'); +``` + +### Fleek Deployment + +Fleek is ideal for hosting dApp frontends: + +**Step 1 — Connect Repository** + +1. Go to [fleek.xyz](https://fleek.xyz/) +2. Connect your GitHub repository +3. Select the branch to deploy + +**Step 2 — Configure Build** + +```yaml title="fleek.yaml" +sites: + - name: my-dapp + buildCommand: npm run build + publishDir: dist + framework: vite +``` + +**Step 3 — Deploy** + +Every push to the selected branch triggers automatic deployment to IPFS. + +### Self-Hosted IPFS + +For advanced users: + +```bash title="Terminal" +# Install IPFS Kubo +wget https://dist.ipfs.io/kubo/v0.24.0/kubo_v0.24.0_linux-amd64.tar.gz +tar -xvzf kubo_v0.24.0_linux-amd64.tar.gz +cd kubo && sudo bash install.sh + +# Initialize and start +ipfs init +ipfs daemon + +# Add files +ipfs add -r metadata/ +# Output: added QmHash metadata/ +``` + +--- + +## NFT Metadata + +### JSON Schema + +Standard NFT metadata format: + +```json +{ + "name": "XDC NFT #1", + "description": "A unique NFT on XDC Network", + "image": "ipfs://QmImageHash", + "animation_url": "ipfs://QmAnimationHash", + "external_url": "https://yourproject.com/nft/1", + "attributes": [ + { + "trait_type": "Rarity", + "value": "Legendary" + }, + { + "trait_type": "Power", + "value": 95, + "display_type": "number" + }, + { + "trait_type": "Color", + "value": "Blue" + } + ], + "properties": { + "creator": "0xYourAddress", + "created": "2024-01-01T00:00:00Z" + } +} +``` + +### Image Storage + +Best practices for NFT images: + +1. **Format**: PNG for pixel art, JPEG for photos, SVG for vector +2. **Size**: 1024x1024px recommended for marketplaces +3. **Optimization**: Use tools like TinyPNG before upload +4. **Organization**: Store images in `/images/` folder, metadata in root + +### Batch Uploads + +For large collections (10,000+ NFTs): + +```bash title="Terminal" +# Create metadata folder structure +mkdir -p metadata/images + +# Generate metadata with script +node generate-metadata.js + +# Upload entire folder to IPFS +pinata-upload metadata/ +``` + +```javascript title="generate-metadata.js" +const fs = require('fs'); +const path = require('path'); + +const TOTAL_NFTS = 10000; +const baseImageCID = 'QmYourImageFolderCID'; + +for (let i = 0; i < TOTAL_NFTS; i++) { + const metadata = { + name: `XDC Pioneer #${i}`, + description: `Pioneer NFT #${i} of ${TOTAL_NFTS}`, + image: `ipfs://${baseImageCID}/${i}.png`, + attributes: [ + { trait_type: 'Generation', value: 1 }, + { trait_type: 'Token ID', value: i } + ] + }; + + fs.writeFileSync( + path.join('metadata', `${i}.json`), + JSON.stringify(metadata, null, 2) + ); +} + +console.log(`Generated ${TOTAL_NFTS} metadata files`); +``` + +### Update Mechanisms + +IPFS content is immutable. To "update" metadata: + +1. Upload new metadata to IPFS (new CID) +2. Update contract's `baseURI` to point to new CID +3. Or use mutable storage (not recommended for NFTs) + +```solidity +function setBaseURI(string memory _newBaseURI) public onlyOwner { + baseURI = _newBaseURI; +} +``` + +--- + +## dApp Assets + +### Frontend Hosting + +Host your dApp frontend on IPFS via Fleek: + +```bash title="Terminal" +# Install Fleek CLI +npm install -g @fleek-platform/cli + +# Login +fleek login + +# Deploy +fleek sites deploy +``` + +### Media Storage + +Store videos, audio, and 3D models: + +```json +{ + "name": "Interactive NFT", + "animation_url": "ipfs://QmVideoHash", + "properties": { + "media_type": "video/mp4", + "duration": 30 + } +} +``` + +### Documentation Hosting + +Host docs on IPFS for censorship resistance: + +```bash title="Terminal" +# Build your docs +npm run build + +# Upload to IPFS +ipfs add -r website/build/ + +# Pin with Pinata +pinata-upload website/build/ +``` + +### Backup Strategies + +1. **Multi-pin**: Pin content on 2+ services (Pinata + NFT.Storage) +2. **Local backup**: Keep local copy of all files +3. **Gateway fallback**: Use multiple gateways (ipfs.io, pinata, cloudflare) +4. **Monitoring**: Check content availability weekly + +--- + +## Cost Comparison + +| Service | Storage | Monthly Cost | Bandwidth | +|---------|---------|--------------|-----------| +| Pinata | 100 GB | $20 | Unlimited | +| NFT.Storage | 31 GB | Free | Unlimited | +| Fleek | 100 GB | $18 | 1 TB | +| Web3.Storage | 100 GB | $4 | 1 TB | +| AWS S3 | 100 GB | $2.30 | $9/GB | +| Self-hosted | Unlimited | Server cost | Your bandwidth | + +> 💡 IPFS pinning is competitive with centralized storage for small-to-medium projects. + +--- + +## Performance Benchmarks + +| Metric | IPFS | HTTP CDN | +|--------|------|----------| +| First fetch | 2-5s | 200ms | +| Cached fetch | 200ms | 50ms | +| Global availability | 95% | 99.9% | +| Censorship resistance | High | Low | +| Content verification | Built-in | None | + +Tips for better IPFS performance: +1. Use dedicated gateways (faster than public) +2. Pre-warm cache by fetching before users +3. Use IPFS in combination with CDN for hot content + +--- + +## Security Considerations + +1. **Private Content**: IPFS is public by default. Use encryption for sensitive data: + +```javascript +import { encrypt } from 'lit-js-sdk'; + +const encrypted = await encrypt(file, accessControlConditions); +const cid = await client.storeBlob(encrypted); +``` + +2. **Gateway Spoofing**: Verify CIDs match expected hashes +3. **Pinning Service Trust**: Don't rely on single provider +4. **Content Permanence**: Pin important content, don't assume persistence + +--- + +## Troubleshooting + +| Symptom | Cause | Fix | +|---------|-------|-----| +| `504 Gateway Timeout` | Content not pinned | Check pinning status, re-pin | +| CID not resolving | Node not connected | Try different gateway | +| Slow loading | Far from nearest node | Use CDN + IPFS hybrid | +| Upload fails | File too large | Split into chunks, use CAR files | +| Content disappeared | Garbage collected | Re-pin with multiple services | + +--- + +## Next Steps + +- [NFT Tutorial →](/smartcontract/nft) — Build NFTs with IPFS metadata +- [Token Gating →](/smartcontract/token-gating) — Gate content by token ownership +- [Soulbound Tokens →](/smartcontract/sbt) — Non-transferable credentials diff --git a/website/docs/xdcchain/developers/mainnetrpc.md b/website/docs/xdcchain/developers/mainnetrpc.md new file mode 100644 index 00000000..6e8d3853 --- /dev/null +++ b/website/docs/xdcchain/developers/mainnetrpc.md @@ -0,0 +1,75 @@ +--- +title: XDC Network - RPC +--- + +# XDC Mainnet RPC +The XDC Mainnet is the live, operational environment of the XDC Network, where real transactions occur. The Mainnet is designed to support high-performance applications with low transaction fees and quick finality, making it ideal for enterprise use cases. The primary URL for accessing the XDC Mainnet via RPC. This endpoint allows you to interact with the blockchain by sending requests for data, submitting transactions, and more. + +**Public Networks** + +Users with an internet connection and access to a full node RPC can easily access the XDC Network's public blockchain. They can read, create, or validate transactions executed on the blockchain. The network's consensus mechanism, XDPoS (XinFin Delegated Proof of Stake), ensures that all nodes agree on the state of the network. + +## One-click adding XDC Network +Visit the [ChainList](https://chainlist.org/chain/50) and connect to your wallet, it will add alive RPC endpoints. + +## XDC Mainnet Specifications +- **Chain ID:** 50 +- **RPC Endpoint for XDC Mainnet:** +* https://erpc.xinfin.network +* https://earpc.xinfin.network +* https://rpc.xdc.org + +You could find more endpoints from [here](https://chainlist.org/chain/50). + +- **WebSocket Endpoint:** wss://ws.xinfin.network +- **Consensus Mechanism:** XDPoS (XinFin Delegated Proof of Stake) +- **Block Finality:** >75% +- **Consensus Nodes:** Up to 108 (Masternodes) +- **Genesis Block Date:** 2019-05-31 +- **Transaction Fee:** Gas price 0.25 Gwei + +----------- + +## Apothem Testnet RPC +The Apothem Testnet is the test environment for the XDC Network. It mirrors the Mainnet's functionality but operates with test tokens instead of real assets, making it ideal for developers to test and deploy their applications before going live. + +**Public Networks** + +Similar to the Mainnet, users can access the Apothem Testnet with an internet connection and full node RPC. They can perform all the same actions as on the Mainnet—reading, creating, or validating transactions—without the risks associated with live transactions. + +## XDC Testnet Specifications +- **Chain ID:** 51 +- **RPC Endpoint for XDC Apothem:** +* https://rpc.apothem.network + +You could find more endpoints from [here](https://chainlist.org/chain/51). + +- **WebSocket Endpoint:** wss://ws.apothem.network +- **Consensus Mechanism:** XDPoS (XinFin Delegated Proof of Stake) +- **Block Finality:** >75% +- **Consensus Nodes:** Up to 108 (Masternodes) +- **Genesis Block Date:** 2019-05-31 +- **Transaction Fee:** Gas price 0.25 Gwei + +----------- + +## Devnet RPC + +The XDC Devnet is a specialized test environment for the XDC Network, designed to closely mirror the Mainnet's functionality. The Devnet provides developers with a safe, controlled setting to test, deploy, and refine their applications using test tokens instead of real assets. This environment is crucial for ensuring that applications are robust and secure before they go live on the Mainnet. + +**Public Networks** + +Similar to the Mainnet, users can access the XDC Devnet via an internet connection and a full node RPC. The Devnet allows developers to perform the same operations they would on the Mainnet, including reading blockchain data, creating and validating transactions, and deploying smart contracts. However, since the Devnet operates with test tokens, developers can experiment freely without the financial risks associated with live transactions. + +## XDC Devnet Specifications +- **Chain ID:** 551 +- **RPC Endpoint for XDC Devnet:** +* https://devnetstats.apothem.network/devnet + +- **WebSocket Endpoint:** +- **Consensus Mechanism:** XDPoS (XinFin Delegated Proof of Stake) +- **Block Finality:** >75% +- **Consensus Nodes:** Up to 108 (Masternodes) +- **Genesis Block Date:** 2019-05-31 +- **Transaction Fee:** Gas price 0.25 Gwei +