# B2B Address Notification Service (/docs/advanced-features/b2b-address-notification-service) ## Coin & Token Transfer Watcher [#coin--token-transfer-watcher] This document explains how to use the Watched Addresses system to receive real-time webhook notifications for W Chain coin (WCO) transfers and ERC-20 token transfers involving your registered addresses. The system provides: * A CRUD API to manage watched addresses and webhook URLs * Real-time POST webhooks on transfers matching your watch rules * Automatic retries with exponential backoff on delivery failures All user-facing addresses and hashes in API responses and webhooks are 0x-prefixed. Internally, addresses are stored lowercase without the 0x prefix. ### Authentication [#authentication] All endpoints require an API key via the HTTP Authorization header: * Authorization: Bearer YOUR\_API\_KEY If the key is valid, the server resolves your watcher\_id and authorizes the request. If invalid or missing, the server returns 401 Unauthorized. ### Base Path [#base-path] * Base URL: `https://oracle.w-chain.com/api` (append a specific path; the root `/api` has no page) ### Address Normalization [#address-normalization] * Input (create/update): You may send addresses with or without the 0x prefix. The server normalizes by stripping 0x if present and storing lowercase hex without 0x. * Output (list/get/update responses and webhooks): All addresses and transaction hashes are 0x-prefixed for consistency with wallets and explorers. ### Endpoints [#endpoints] #### Create a watched address [#create-a-watched-address] * Method: `POST` * Path: `/notifications/watched-addresses` * Body fields: * `address` (string, required): Address with or without 0x; must be 40 hex characters when normalized * `watch_coin` (boolean, optional, default `true`): Watch native coin (WCO) transfers * `watch_token` (boolean, optional, default `true`): Watch ERC-20 token transfers * `webhook_url` (string, required): HTTPS URL to receive webhooks Example: ```bash curl -X POST https://oracle.w-chain.com/api/notifications/watched-addresses \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "address": "0xabc1234567890abcdefabc1234567890abcdef0", "watch_coin": true, "watch_token": true, "webhook_url": "https://yourapp.example.com/watched-address-webhook" }' ``` Success response (200): ```json { "success": true, "data": { "id": "...", "watcher_id": 123, "address": "0xabc1234567890abcdefabc1234567890abcdef0", "watch_coin": true, "watch_token": true, "webhook_url": "https://yourapp.example.com/watched-address-webhook", "created_at": "...", "updated_at": "..." } } ``` #### List watched addresses [#list-watched-addresses] * Method: `GET` * Path: `/notifications/watched-addresses` Example: ```bash curl -X GET https://oracle.w-chain.com/api/notifications/watched-addresses \ -H "Authorization: Bearer YOUR_API_KEY" ``` Success response (200): ```json { "success": true, "data": [ { "id": "...", "watcher_id": 123, "address": "0xabc1234567890abcdefabc1234567890abcdef0", "watch_coin": true, "watch_token": true, "webhook_url": "https://yourapp.example.com/watched-address-webhook", "created_at": "...", "updated_at": "..." } ] } ``` #### Get a watched address by ID [#get-a-watched-address-by-id] * Method: `GET` * Path: `/notifications/watched-addresses/:id` Example: ```bash curl -X GET https://oracle.w-chain.com/api/notifications/watched-addresses/ID_HERE \ -H "Authorization: Bearer YOUR_API_KEY" ``` Success response (200): ```json { "success": true, "data": { "id": "...", "watcher_id": 123, "address": "0xabc1234567890abcdefabc1234567890abcdef0", "watch_coin": true, "watch_token": true, "webhook_url": "https://yourapp.example.com/watched-address-webhook", "created_at": "...", "updated_at": "..." } } ``` #### Update a watched address [#update-a-watched-address] * Method: `PATCH` * Path: `/notifications/watched-addresses/:id` * Body: Any subset of the create fields (`address`, `watch_coin`, `watch_token`, `webhook_url`) Example: ```bash curl -X PATCH https://oracle.w-chain.com/api/notifications/watched-addresses/ID_HERE \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "watch_token": false }' ``` Success response (200): ```json { "success": true, "data": { "id": "...", "watcher_id": 123, "address": "0xabc1234567890abcdefabc1234567890abcdef0", "watch_coin": true, "watch_token": false, "webhook_url": "https://yourapp.example.com/watched-address-webhook", "created_at": "...", "updated_at": "..." } } ``` #### Delete a watched address [#delete-a-watched-address] * Method: `DELETE` * Path: `/notifications/watched-addresses/:id` Example: ```bash curl -X DELETE https://oracle.w-chain.com/api/notifications/watched-addresses/ID_HERE \ -H "Authorization: Bearer YOUR_API_KEY" ``` Success response (200): ```json { "success": true } ``` ### Webhook Delivery [#webhook-delivery] When a transfer involving any of your watched addresses occurs, we send a POST request with JSON to the `webhook_url` configured for that watched address. * Method: `POST` * Headers: * `Content-Type: application/json` * `Authorization: Bearer ` this is the same API Key used by the Watcher identity, should be used to ensure the authenticity of the webhook request * Timeout: 10 seconds. If your endpoint does not respond within 10 seconds, it is treated as a failure and retried. #### Payload fields [#payload-fields] These fields are sent in the request body. Values are formatted for user-facing consumption as described. * `id` (number): Internal notification ID * `watched_addresses_id` (string, UUID): The watched\_addresses row ID * `watcher_id` (number): Your watcher ID * `hash` (string): 0x-prefixed transaction hash * `type` (string enum): `COIN_TRANSFER` or `TOKEN_TRANSFER` * `sender` (string): 0x-prefixed sender address * `receiver` (string): 0x-prefixed receiver address. For contract creations or transactions without a `to`, this may be an empty string. * `amount` (number | null): * COIN\_TRANSFER: Amount is in wei, as a JSON number. Note: very large values may exceed JavaScript’s exact integer range; handle carefully if you require exact arithmetic. * TOKEN\_TRANSFER: Raw token units as a JSON number (decimals not applied). Fetch the token’s decimals and normalize on your side if needed. * `asset` (string): * COIN\_TRANSFER: The literal string `WCO` * TOKEN\_TRANSFER: 0x-prefixed token contract address * `timestamp` (string): Timestamp of notification row creation as produced by Postgres (timestamp without time zone). Treat as a textual timestamp; convert/timezone as desired on your side. * `webhook_url` (string): The target URL (provided for your reference) * `api_key` (string | null): The API key stored for your watcher, if any (also sent via the Authorization header) * `next_retry_at` (string | null): Scheduled time for the next retry (if previously failed), else null Example payload: ```json { "id": 12345, "watched_addresses_id": "a1b2c3d4-1111-2222-3333-abcdefabcdef", "watcher_id": 678, "hash": "0x3fa9e1...c1d2", "type": "TOKEN_TRANSFER", "sender": "0x1111111111111111111111111111111111111111", "receiver": "0x2222222222222222222222222222222222222222", "amount": 2500000000000000000, "asset": "0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", "timestamp": "2025-09-10 08:00:00.000000", "webhook_url": "https://yourapp.example.com/watched-address-webhook", "api_key": "YOUR_API_KEY_OR_NULL", "next_retry_at": null } ``` ### Retry Policy (Exponential Backoff) [#retry-policy-exponential-backoff] If a webhook delivery fails (non-2xx response, timeout, or network error), the system schedules a retry using the following backoff (minutes): * 1, 3, 10, 15, 60 On the Nth failure, the Nth interval is used; after the 5th failure, retries continue every 60 minutes. * `retry_count` increments on each failure. * `next_retry_at` is set to `now + interval`. * On a successful 2xx response, `processed_at` is set and the notification will not be retried further. The retry worker selects unprocessed notifications whose `next_retry_at` is due. ### Implementation Notes [#implementation-notes] * Address formatting * Inputs accept with or without 0x; stored lowercase without 0x internally. * API responses (create/list/get/update) return addresses with 0x. * Webhook payload prefixes `hash`, `sender`, `receiver`, and (for tokens) `asset` with 0x. * Receiver may be empty string * For coin transfers where `to` is null (e.g., contract creation), receiver is emitted as an empty string. * Amount type * Currently sent as a JSON number. If exact precision is required in your system, convert or handle carefully to avoid precision loss in JavaScript environments. * Asset field * `WCO` for native coin transfers; otherwise the token contract address (0x-prefixed) for token transfers. * Timeouts * Webhook POSTs time out in 10 seconds (treated as failure). * Authorization header on webhook * If an API key is present for the watcher, the webhook request to your server includes `Authorization: Bearer `. ### Example Receiver (Pseudocode) [#example-receiver-pseudocode] ```ts import express from 'express'; const app = express(); app.use(express.json()); app.post('/watched-address-webhook', (req, res) => { // Optionally verify Authorization header matches what you expect // const auth = req.headers['authorization']; const n = req.body; // See payload fields above // Handle idempotency if you store notifications (e.g., by `n.id`) if (n.type === 'COIN_TRANSFER') { // n.asset === 'WCO' // n.amount is wei (number); beware precision in JS } else if (n.type === 'TOKEN_TRANSFER') { // n.asset is token contract address (0x-prefixed) // n.amount is raw units; fetch token decimals to normalize } res.status(200).send('ok'); }); app.listen(3000); ``` ### Troubleshooting [#troubleshooting] * 401 Unauthorized on API calls * Ensure `Authorization: Bearer YOUR_API_KEY` is present and valid. * Webhook not received * Confirm your server is reachable over HTTPS and returns 200 within 10 seconds. * Check if retries are scheduled by inspecting your logs or querying notifications with `processed_at IS NULL` and `next_retry_at` in the past. * Amount precision issues * The `amount` is sent as a JSON number; for exact arithmetic, convert or handle using big number libraries on your side. ### Change Log [#change-log] * 2025-09: Added `asset` to notification schema and payload. For coin transfers set to `WCO`; for token transfers set to the token contract address. * 2025-09: Standardized 0x-prefix formatting in API responses and webhook payloads (hash, sender, receiver, token asset). # Public Price API (/docs/advanced-features/public-price-api) ### Overview [#overview] The W-Chain Price API provides real-time price data for tokens within the W-Chain ecosystem. Currently supporting WCO and WAVE tokens, this API delivers USD-denominated prices with caching for optimal performance. Future token additions will follow the same endpoint structure and response format. ### Base URL [#base-url] `https://oracle.w-chain.com/api/price` ### Authentication [#authentication] All Price API endpoints are publicly accessible and do not require authentication. ### Common Response Format [#common-response-format] All price endpoints return a consistent JSON structure: ```json { "price": 1.2345, "asset": "TOKEN_SYMBOL", "base_currency": "USD" } ``` #### Response Fields [#response-fields] * `price`: Current price of the asset in USD (number) * `asset`: Token symbol/identifier (string) * `base_currency`: Always "USD" for price denomination (string) *** ### Supported Tokens [#supported-tokens] #### 1. WCO Token Price [#1-wco-token-price] **Endpoint:** `GET /wco`\ **Cache:** 1 minute\ **Description:** Retrieves the current USD price of WCO token from the latest price feed data. **Example Request** ``` GET https://oracle.w-chain.com/api/price/wco ``` **Example Response** ```json { "price": 0.0234, "asset": "WCO", "base_currency": "USD" } ``` **Data Source** * **Source**: Internal price feed database (`price_feed_wco` table) * **Update Frequency**: Real-time price feed updates * **Precision**: Full decimal precision as stored in database * **Fallback**: Returns `null` if no price data available **Technical Implementation** * Queries the most recent price entry from `price_feed_wco` table * Implements 60-second caching to reduce database load * Orders by timestamp descending to get latest price * Handles database errors gracefully *** #### 2. WAVE Token Price [#2-wave-token-price] **Endpoint:** `GET /wave`\ **Cache:** Inherits from WCO cache (1 minute)\ **Description:** Retrieves the current USD price of WAVE token, calculated using WCO price and WAVE/WCO trading pair data. **Example Request** ``` GET https://oracle.w-chain.com/api/price/wave ``` **Example Response** ```json { "price": 1.4567, "asset": "WAVE", "base_currency": "USD" } ``` **Price Calculation** WAVE USD price is calculated using the formula: ``` WAVE_USD_Price = WAVE_WCO_Rate × WCO_USD_Price ``` Where: * `WAVE_WCO_Rate`: Latest trading pair price from pair ID 1 * `WCO_USD_Price`: Current WCO price from `/api/price/wco` **Data Sources** * **Primary**: Trading pair data (pair ID: 1) for WAVE/WCO rate * **Secondary**: WCO USD price from internal price feed * **Dependencies**: Requires both WCO price and trading pair data **Technical Implementation** * Makes internal API call to `/api/price/wco` for WCO price * Fetches latest WAVE/WCO pair price using `getLatestPairPricesById(1)` * Multiplies pair rate by WCO USD price for final WAVE USD price * Inherits caching behavior from WCO endpoint *** ### Future Token Support [#future-token-support] Additional tokens will be added following the same patterns: #### Endpoint Structure [#endpoint-structure] ``` GET /api/price/{token_symbol} ``` #### Response Format [#response-format] All future tokens will maintain the same response structure: ```json { "price": number, "asset": "TOKEN_SYMBOL", "base_currency": "USD" } ``` #### Implementation Patterns [#implementation-patterns] New tokens will follow one of these implementation patterns: 1. **Direct Price Feed** (like WCO): * Dedicated price feed table * Direct USD pricing * Simple database query 2. **Calculated Price** (like WAVE): * Based on trading pair data * Calculated against base token (typically WCO) * Derived USD pricing *** ### Error Handling [#error-handling] #### Database Errors [#database-errors] When price data cannot be retrieved: ```json { "price": null, "asset": "TOKEN_SYMBOL", "base_currency": "USD" } ``` #### Missing Dependencies [#missing-dependencies] For calculated prices (like WAVE), if dependencies are unavailable: * Returns appropriate error response * Logs error details for debugging * Maintains API consistency ### Caching Strategy [#caching-strategy] #### WCO Token [#wco-token] * **Cache Key**: `api_price_wco` * **TTL**: 60 seconds * **Strategy**: Database query caching * **Invalidation**: Time-based expiration #### WAVE Token [#wave-token] * **Cache Dependency**: Inherits from WCO caching * **Additional Caching**: Trading pair data may have separate caching * **Effective TTL**: Minimum of dependent cache TTLs #### Benefits [#benefits] * Reduces database load * Improves response times * Maintains data freshness * Handles high-frequency requests efficiently ### Rate Limiting [#rate-limiting] No explicit rate limiting is enforced, but the caching mechanism naturally throttles database queries. Clients should: * Respect cache durations * Avoid excessive polling * Implement client-side caching for frequently accessed data ### Use Cases [#use-cases] #### For DeFi Applications [#for-defi-applications] * **Portfolio Valuation**: Calculate total portfolio value in USD * **Trading Interfaces**: Display current market prices * **Yield Farming**: Calculate APY and rewards in USD terms * **Liquidity Pools**: Price LP tokens and calculate impermanent loss #### For Analytics Platforms [#for-analytics-platforms] * **Market Data**: Real-time price tracking and charts * **Market Cap Calculations**: Combine with supply data for market cap * **Price Alerts**: Trigger notifications on price movements * **Historical Analysis**: Track price trends over time #### For Wallets and Exchanges [#for-wallets-and-exchanges] * **Balance Display**: Show USD values of token holdings * **Trading Pairs**: Price discovery for trading interfaces * **Order Books**: Reference pricing for limit orders * **Fee Calculations**: Calculate transaction fees in USD ### Data Freshness [#data-freshness] #### WCO Price Updates [#wco-price-updates] * **Source**: Real-time price feed system * **Frequency**: Continuous updates based on market activity * **Latency**: Sub-minute from price feed to API (with caching) #### WAVE Price Updates [#wave-price-updates] * **Source**: Trading pair activity on W-Chain DEX * **Frequency**: Updates with each trade in WAVE/WCO pair * **Latency**: Depends on WCO price freshness + pair data updates ### Best Practices [#best-practices] #### For Developers [#for-developers] 1. **Handle Null Prices**: Always check for `null` price values 2. **Implement Fallbacks**: Have backup pricing sources when possible 3. **Cache Appropriately**: Respect API cache durations in your application 4. **Error Handling**: Implement robust error handling for network issues #### For High-Frequency Applications [#for-high-frequency-applications] 1. **Batch Requests**: Group multiple price requests when possible 2. **WebSocket Alternative**: Consider WebSocket connections for real-time updates 3. **Local Caching**: Implement application-level caching 4. **Rate Management**: Avoid overwhelming the API with requests #### For Financial Applications [#for-financial-applications] 1. **Precision Handling**: Use appropriate decimal precision for financial calculations 2. **Timestamp Tracking**: Track when prices were last updated 3. **Audit Trails**: Log price data usage for compliance 4. **Backup Systems**: Implement redundant price sources ### Integration Examples [#integration-examples] #### JavaScript/TypeScript [#javascripttypescript] ```javascript // Fetch single token price async function getTokenPrice(symbol) { try { const response = await fetch(`https://oracle.w-chain.com/api/price/${symbol.toLowerCase()}`); const data = await response.json(); return data.price; } catch (error) { console.error(`Error fetching ${symbol} price:`, error); return null; } } // Fetch multiple token prices async function getPortfolioValue(holdings) { const prices = await Promise.all([ fetch('https://oracle.w-chain.com/api/price/wco').then(r => r.json()), fetch('https://oracle.w-chain.com/api/price/wave').then(r => r.json()) ]); let totalValue = 0; holdings.forEach(holding => { const price = prices.find(p => p.asset === holding.symbol)?.price || 0; totalValue += holding.amount * price; }); return totalValue; } ``` #### Python [#python] ```python import requests import asyncio import aiohttp def get_token_price(symbol): """Fetch token price synchronously""" try: response = requests.get(f'https://oracle.w-chain.com/api/price/{symbol.lower()}') response.raise_for_status() return response.json()['price'] except requests.RequestException as e: print(f"Error fetching {symbol} price: {e}") return None async def get_multiple_prices(symbols): """Fetch multiple token prices asynchronously""" async with aiohttp.ClientSession() as session: tasks = [] for symbol in symbols: url = f'https://oracle.w-chain.com/api/price/{symbol.lower()}' tasks.append(session.get(url)) responses = await asyncio.gather(*tasks) prices = {} for response, symbol in zip(responses, symbols): if response.status == 200: data = await response.json() prices[symbol] = data['price'] else: prices[symbol] = None return prices ``` ### Monitoring and Observability [#monitoring-and-observability] #### Health Checks [#health-checks] * Monitor API response times * Track cache hit/miss ratios * Alert on price data staleness * Monitor database connectivity #### Key Metrics [#key-metrics] * **Response Time**: API endpoint latency * **Cache Efficiency**: Cache hit percentage * **Data Freshness**: Time since last price update * **Error Rate**: Failed requests percentage * **Dependency Health**: WCO price availability for WAVE calculations ### Support and Troubleshooting [#support-and-troubleshooting] #### Common Issues [#common-issues] 1. **Null Prices**: Check if price feed is active and database is accessible 2. **Stale Data**: Verify cache TTL settings and price feed updates 3. **WAVE Price Errors**: Ensure both WCO price and trading pair data are available 4. **High Latency**: Check database performance and network connectivity #### Getting Help [#getting-help] * Verify endpoint URLs and request format * Check for network connectivity issues * Review error messages in API responses * Monitor W-Chain network status for underlying issues *** *This API documentation covers the current implementation of WCO and WAVE price endpoints. As new tokens are added to the W-Chain ecosystem, they will follow similar patterns and be documented with the same level of detail.* # W Swap LP Price API (/docs/advanced-features/w-swap-lp-price-api) This document describes the W Swap LP Value API endpoint that returns the latest token price and LP (Liquidity Provider) token price in USD for a specific trading pair. ### Endpoint [#endpoint] * Method: `GET` * Path: `/api/w-swap/lp-value/:id` ### Purpose [#purpose] * Returns the latest price of the pair. * Returns the estimated USD value of one LP token for the pair. * Also returns the pair name for convenience. ### Request [#request] * Path parameter `id` (number): The `trade_pairs.id` of the pair. #### Example [#example] ``` GET /api/w-swap/lp-value/2 ``` ### Success Response [#success-response] * Status: `200 OK` * Body: ```json { "latestPrice": 1.2345, "lpPriceInUsd": 0.5678, "pair": "USDT/WCO" } ``` #### Field Details [#field-details] * `latestPrice` (number): The latest exchange rate of the pair (token1 per token0 or vice versa depending on pair configuration). * `lpPriceInUsd` (number): The estimated value of 1 LP token in USD. * `pair` (string): The human-readable pair name from `trade_pairs.name`. ### Error Responses [#error-responses] * `400 Bad Request`: Missing `id` path parameter. ```json { "statusCode": 400, "statusMessage": "Missing id parameter" } ``` * `404 Not Found`: Price or pair not found (no matching `trade_pairs.id` or missing price data). ```json { "statusCode": 404, "statusMessage": "Price not found" } ``` ### Supported Trade Pairs [#supported-trade-pairs] The following trade pairs are supported by this API. Use the corresponding `ID` in the request URL. | ID | Pair Name | | -- | --------- | | 1 | WAVE/WCO | | 2 | USDT/WCO | | 3 | USDC/WCO | | 4 | SOL/WCO | | 5 | DOGE/WCO | | 6 | XRP/WCO | ### Implementation Notes [#implementation-notes] * The endpoint fetches the latest price and pair name in a single query for efficiency. * Results are cached for 60 seconds (`maxAge: 60`, `swr: true`) to reduce database load and improve response times. * Authentication is not required for this public endpoint. ### Related Endpoints [#related-endpoints] * `GET /api/w-swap/volume/:id` — returns the last 24 hours of traded volume (in USD). # W Swap Trade Volume API (/docs/advanced-features/w-swap-trade-volume-api) This document describes the W Swap Trade Volume API endpoint that returns the last 24 hours of traded volume (in USD) for a specific trading pair. ### Endpoint [#endpoint] * Method: `GET` * URL: `https://oracle.w-chain.com/api/w-swap/volume/:id` ### Purpose [#purpose] * Returns the 24-hour aggregated USD volume for the specified trading pair. * Also returns the pair name for convenience. ### Request [#request] * Path parameter `id` (number): The `trade_pairs.id` of the pair. #### Example [#example] ``` GET https://oracle.w-chain.com/api/w-swap/volume/2 ``` ### Success Response [#success-response] * Status: `200 OK` * Body: ```json { "vol24h": 12345.67, "pair": "USDT/WCO" } ``` #### Field Details [#field-details] * `vol24h` (number): Total swap volume in USD over the past 24 hours. * `pair` (string): The human-readable pair name from `trade_pairs.name`. ### Error Responses [#error-responses] * `400 Bad Request`: Missing `id` path parameter. ```json { "statusCode": 400, "statusMessage": "Missing id parameter" } ``` * `404 Not Found`: Pair not found (no matching `trade_pairs.id`). ```json { "statusCode": 404, "statusMessage": "Pair not found" } ``` ### How Volume Is Calculated [#how-volume-is-calculated] * Source table: `trade_pair_swap_events`. * Aggregation: Sum of `usd_value` for rows where: * `pair_id` equals the requested `id`. * `timestamp` is within the last 24 hours (`gt now - 24h` and `lte now`). * USD valuation: * Stablecoins (`USDT`, `USDC`, and bridged variants) use a 1:1 USD mapping. * `WCO` is valued using its CoinGecko USD price. * Other tokens may currently resolve to `0` USD unless specifically supported. * Caching: Results are cached for \~60 seconds to reduce load. ### `trade_pairs` Reference [#trade_pairs-reference] The following pairs (from `trade_pairs`) are relevant for W Swap operations and USD valuation logic. The `usd_value_from` column indicates which token is used to determine USD value during swaps: `0` means `token0`, `1` means `token1`. | id | name | platform | pair\_address | token0\_address | token1\_address | token0\_decimals | token1\_decimals | fee | usd\_value\_from | wave\_pid | | -- | -------- | -------- | ------------------------------------------ | ------------------------------------------ | ------------------------------------------ | ---------------- | ---------------- | --- | ---------------- | --------- | | 1 | WAVE/WCO | 0 | 0x35264f0e8cd7a32341f47dbfbf2d85b81fd0ef0a | 0x42abfb13b4e3d25407ffa9705146b7cb812404a0 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 18 | 18 | 300 | 1 | 0 | | 2 | USDT/WCO | 0 | 0xd4e9176d5189dbb24f40e5c6c45bb1682dcb3324 | 0x40cb2cccf80ed2192b53fb09720405f6fe349743 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 6 | 18 | 300 | 0 | 1 | | 3 | USDC/WCO | 0 | 0x00d91ce419c068e36928fd8e9379b11d0011f052 | 0x643ec74ed2b79098a37dc45dcc7f1abfe2ade6d8 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 6 | 18 | 300 | 0 | 2 | | 4 | SOL/WCO | 0 | 0x9556d7afa868cb8b25657d34f3e0d46929f9d710 | 0xd4f93cacd6d607789c8ecf1dddeba8b0c4d915a8 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 18 | 18 | 300 | 1 | 4 | | 5 | DOGE/WCO | 0 | 0x8b5f11ea77641b208fb53b4b91b2825db64b8c32 | 0x6cdfda79787caa4ad1a95456095bedc95abd2d75 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 8 | 18 | 300 | 1 | 5 | | 6 | XRP/WCO | 0 | 0x24f07de79398f24c9d4dd60a281a29843e43b7fd | 0x4560d5eb0c32a05fa59acd2e8d639f84a15a2414 | 0xedb8008031141024d50ca2839a607b2f82c1c045 | 18 | 18 | 300 | 1 | 6 | #### Note on `wave_pid` [#note-on-wave_pid] The `wave_pid` sequence skips `3` because in Wave Farm, pool ID `3` is a `WCO` Single Stake pool (not an LP pool). Therefore, LP-related pairs continue with `4`, `5`, `6`, etc. ### Usage Examples [#usage-examples] #### cURL [#curl] ```bash curl -s "http:///api/w-swap/volume/2" ``` #### JavaScript (fetch) [#javascript-fetch] ```js // Fetch 24h volume for pair id 2 (USDT/WCO) const resp = await fetch('/api/w-swap/volume/2'); if (!resp.ok) throw new Error('Request failed'); const data = await resp.json(); // data.vol24h is a number in USD; data.pair is the pair name ``` ### Implementation Notes [#implementation-notes] * Internals use a 60-second cache to avoid excessive DB queries. * If there are no swap events in the last 24h for the given pair, `vol24h` returns `0`. * Authentication is not required for this public endpoint. ### Related Endpoints [#related-endpoints] * `GET /api/w-swap/lp-value/:id` — returns latest pair price and LP price (in USD). # WCO Supply Information API (/docs/advanced-features/wco-supply-information-api) ### Overview [#overview] The WCO Supply Information API provides real-time data about the WCO token supply distribution, including circulating supply, locked supply, and burned tokens. This endpoint is essential for understanding the tokenomics and current state of WCO tokens in circulation. ### Endpoint Details [#endpoint-details] **URL:** `https://oracle.w-chain.com/api/wco/supply-info`\ **Method:** `GET`\ **Cache:** 2 minutes TTL\ **Authentication:** None required ### Response Structure [#response-structure] The API returns a comprehensive JSON response with the following structure: ```json { "timestamp": "2024-01-15T10:30:00.000Z", "cache": { "ttl_seconds": 120, "note": "This endpoint is cached for 2 minutes" }, "summary": { "initial_supply_wco": "1000000000", "locked_supply_wco": "250000000.123456789", "burned_supply_wco": "5000000.987654321", "circulating_supply_wco": "744999999.888888890" }, "raw": { "units": { "native": "WCO", "base": "wei", "wei_per_wco": "1000000000000000000" }, "initial_supply_wei": "1000000000000000000000000000", "locked_supply_wei": "250000000123456789000000000", "burned_supply_wei": "5000000987654321000000000", "circulating_supply_wei": "744999999888888890000000000", "locked_supply_breakdown": [ { "address": "0x1234...", "label": "validators-staking", "balance_wei": "200000000000000000000000000", "balance_wco": "200000000.0" }, { "address": "0x5678...", "label": "vesting:team", "balance_wei": "50000000123456789000000000", "balance_wco": "50000000.123456789" } ], "burned_supply_breakdown": { "address": "0x0000000000000000000000000000000000000000", "label": "evm-zero-address", "balance_wei": "5000000987654321000000000", "balance_wco": "5000000.987654321" } }, "methodology": { "formula": "circulating = initial_genesis_supply - (sum of locked addresses balances) - burned_balance", "data_sources": { "rpc_provider": "WCHAIN_RPC_PROVIDER", "multicall3_contract": "aggregate3 + getEthBalance" }, "address_labels": { "validators_staking": "0x1234...", "vesting_contracts": { "team": "0x5678...", "advisors": "0x9abc..." }, "burn_address": "0x0000000000000000000000000000000000000000" }, "verification": { "how_to_verify": "Query each address balance on-chain or via any RPC, and confirm calculations match the formula." } } } ``` ### Understanding the Response [#understanding-the-response] #### Summary Section [#summary-section] The `summary` section provides human-readable WCO token amounts: * **`initial_supply_wco`**: The total initial supply of WCO tokens at genesis * **`locked_supply_wco`**: Total tokens locked in various contracts (staking, vesting, etc.) * **`burned_supply_wco`**: Total tokens sent to the burn address (0x0000...) * **`circulating_supply_wco`**: Tokens available for trading and transactions #### Raw Data Section [#raw-data-section] The `raw` section contains precise wei-denominated values and detailed breakdowns: * **`units`**: Explains the denomination system (1 WCO = 10^18 wei) * **`*_supply_wei`**: Exact token amounts in wei (smallest unit) * **`locked_supply_breakdown`**: Individual balances of each locked address * **`burned_supply_breakdown`**: Details of tokens sent to burn address #### Methodology Section [#methodology-section] Provides transparency about data collection and calculation methods: * **`formula`**: Mathematical formula used for circulating supply calculation * **`data_sources`**: Technical details about data retrieval methods * **`address_labels`**: Human-readable labels for contract addresses * **`verification`**: Instructions for independently verifying the data ### Calculation Methodology [#calculation-methodology] #### Circulating Supply Formula [#circulating-supply-formula] ``` Circulating Supply = Initial Supply - Locked Supply - Burned Supply ``` #### Locked Supply Categories [#locked-supply-categories] 1. **Validators Staking Contract**: Tokens staked by validators for network security 2. **Vesting Contracts**: Tokens allocated to team, advisors, and other stakeholders with time-based release schedules #### Data Collection Process [#data-collection-process] 1. **Multicall3 Integration**: Uses efficient batch calls to query multiple address balances simultaneously 2. **Real-time Queries**: Balances are fetched directly from the W-Chain RPC provider 3. **Precision Handling**: All calculations use BigInt to maintain precision with large numbers 4. **Error Handling**: Implements safeguards against negative circulating supply due to chain anomalies ### Use Cases [#use-cases] #### For Developers [#for-developers] * **DeFi Integration**: Use circulating supply data for market cap calculations * **Analytics Dashboards**: Display real-time tokenomics information * **Trading Applications**: Incorporate supply metrics into trading algorithms #### For Researchers [#for-researchers] * **Tokenomics Analysis**: Study token distribution and unlock schedules * **Market Research**: Analyze supply dynamics and their market impact * **Verification**: Independently verify supply calculations using provided methodology #### For Exchanges [#for-exchanges] * **Market Data**: Provide accurate circulating supply for market cap calculations * **Compliance**: Maintain transparency about token supply for regulatory purposes ### Data Freshness and Caching [#data-freshness-and-caching] * **Cache Duration**: 2 minutes (120 seconds) * **Update Frequency**: Data refreshes automatically every 2 minutes * **Real-time Accuracy**: Balances reflect the most recent blockchain state within cache window ### Verification Guide [#verification-guide] To independently verify the supply data: 1. **Query Individual Addresses**: Use any W-Chain RPC endpoint to query balances of addresses listed in `methodology.address_labels` 2. **Sum Locked Balances**: Add up all balances from validators staking and vesting contracts 3. **Query Burn Address**: Check balance of `0x0000000000000000000000000000000000000000` 4. **Apply Formula**: Subtract locked and burned amounts from initial supply 5. **Compare Results**: Your calculation should match the API response ### Error Handling [#error-handling] The API implements robust error handling: * **Network Issues**: Automatic retries for RPC calls * **Invalid Responses**: Graceful handling of malformed blockchain responses * **Negative Supply Protection**: Clamps circulating supply to zero if calculation results in negative value ### Rate Limiting [#rate-limiting] No explicit rate limiting is applied, but the 2-minute cache reduces the load on underlying blockchain infrastructure. For high-frequency applications, respect the cache TTL to optimize performance. ### Support [#support] For technical support or questions about this API: * Check the verification methodology to ensure correct interpretation * Review the raw data section for precise calculations * Consult the W-Chain documentation for blockchain-specific details # WPoints Public API (/docs/advanced-features/wpoints-public-api) ### Overview [#overview] The Points API provides comprehensive access to user points data within the W-Chain ecosystem. These endpoints allow you to retrieve points information for individual users, leaderboards, and comparative analytics across different time periods and categories. ### Base URL [#base-url] `https://oracle.w-chain.com/api/points` ### Authentication [#authentication] All Points API endpoints are publicly accessible and do not require authentication. ### Common Parameters [#common-parameters] #### Month Format [#month-format] When specifying months in API calls, use the format: `YYYY-MM` * Example: `2024-01` for January 2024 * Example: `2024-12` for December 2024 #### User Parameter [#user-parameter] User addresses should be provided as Ethereum-compatible addresses (0x prefixed hex strings). *** ### Endpoints [#endpoints] #### 1. Monthly Leaderboard [#1-monthly-leaderboard] **Endpoint:** `GET /leaderboard`\ **Cache:** 5 minutes\ **Description:** Retrieves the points leaderboard for a specific month, showing all users ranked by their total points. **Parameters** | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------- | | `month` | string | Yes | Month in YYYY-MM format | **Example Request** ``` GET https://oracle.w-chain.com/api/points/leaderboard?month=2024-01 ``` **Example Response** ```json [ { "user": "0x1234567890123456789012345678901234567890", "points": 15750 }, { "user": "0x0987654321098765432109876543210987654321", "points": 12300 }, { "user": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", "points": 8900 } ] ``` **Response Fields** * `user`: Ethereum address of the user * `points`: Total points earned by the user in the specified month **Notes** * Results are automatically sorted by points in descending order (highest first) * Only includes users who earned points during the specified month *** #### 2. User Points Details [#2-user-points-details] **Endpoint:** `GET /user`\ **Cache:** 5 minutes\ **Description:** Retrieves detailed points information for a specific user in a given month, including individual point entries with categories and transaction hashes. **Parameters** | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------- | | `month` | string | Yes | Month in YYYY-MM format | | `user` | string | Yes | User's Ethereum address | **Example Request** ``` GET https://oracle.w-chain.com/api/points/user?month=2024-01&user=0x1234567890123456789012345678901234567890 ``` **Example Response** ```json [ { "category": "trading", "points": 500, "created_at": "2024-01-15T14:30:00.000Z", "hash": "0xabc123def456789..." }, { "category": "staking", "points": 250, "created_at": "2024-01-14T09:15:00.000Z", "hash": "0xdef789abc123456..." }, { "category": "liquidity_provision", "points": 1000, "created_at": "2024-01-13T16:45:00.000Z", "hash": "0x123456789abcdef..." } ] ``` **Response Fields** * `category`: The category/type of activity that earned the points * `points`: Number of points earned for this specific activity * `created_at`: ISO timestamp when the points were awarded * `hash`: Transaction hash associated with the point-earning activity **Notes** * Results are ordered by creation date (most recent first) * Provides granular view of all point-earning activities *** #### 3. User Points by Category [#3-user-points-by-category] **Endpoint:** `GET /user-by-category`\ **Cache:** 30 seconds\ **Description:** Retrieves aggregated points for a specific user grouped by category for a given month. **Parameters** | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------- | | `month` | string | Yes | Month in YYYY-MM format | | `user` | string | Yes | User's Ethereum address | **Example Request** ``` GET https://oracle.w-chain.com/api/points/user-by-category?month=2024-01&user=0x1234567890123456789012345678901234567890 ``` **Example Response** ```json [ { "category": "trading", "points": 5500 }, { "category": "liquidity_provision", "points": 3200 }, { "category": "staking", "points": 1800 }, { "category": "referral", "points": 750 } ] ``` **Response Fields** * `category`: The category/type of activity * `points`: Total points earned in this category for the specified month **Notes** * Results are sorted by points in descending order (highest category first) * Provides a summary view of user's point distribution across activities *** #### 4. Current Month User Points [#4-current-month-user-points] **Endpoint:** `GET /user-by-current-month`\ **Cache:** 1 minute\ **Description:** Retrieves the total points for a specific user in the current month. **Parameters** | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------- | | `user` | string | Yes | User's Ethereum address | **Example Request** ``` GET https://oracle.w-chain.com/api/points/user-by-current-month?user=0x1234567890123456789012345678901234567890 ``` **Example Response** ```json { "points": 8750 } ``` **Response Fields** * `points`: Total points earned by the user in the current month **Notes** * Automatically uses the current month (no month parameter needed) * Useful for real-time dashboards and current progress tracking *** #### 5. Points Comparison vs Last Month [#5-points-comparison-vs-last-month] **Endpoint:** `GET /vs-last-month`\ **Cache:** 1 minute\ **Description:** Compares a user's points between the current period and the corresponding period in the previous month, with intelligent date range handling. **Parameters** | Parameter | Type | Required | Description | | --------- | ------ | -------- | ----------------------- | | `user` | string | Yes | User's Ethereum address | **Example Request** ``` GET https://oracle.w-chain.com/api/points/vs-last-month?user=0x1234567890123456789012345678901234567890 ``` **Example Response** ```json { "current": { "points": 8750, "period": { "start": "2024-01-01T00:00:00.000Z", "end": "2024-01-19T23:59:59.999Z" } }, "lastMonth": { "points": 6200, "period": { "start": "2023-12-01T00:00:00.000Z", "end": "2023-12-19T23:59:59.999Z" } }, "comparison": { "difference": 2550, "percentageChange": 41.13, "isFullMonthComparison": false } } ``` **Response Fields** **Current Period:** * `current.points`: Points earned in the current period * `current.period.start`: Start date of current comparison period * `current.period.end`: End date of current comparison period **Last Month Period:** * `lastMonth.points`: Points earned in the corresponding previous period * `lastMonth.period.start`: Start date of previous comparison period * `lastMonth.period.end`: End date of previous comparison period **Comparison Analytics:** * `comparison.difference`: Absolute difference in points (current - last month) * `comparison.percentageChange`: Percentage change from last month (rounded to 2 decimal places) * `comparison.isFullMonthComparison`: Boolean indicating if comparing full months or partial periods **Intelligent Date Range Logic** The endpoint uses smart date range comparison: 1. **Late in Month (Day >= 28)**: Compares full months * Current: Full current month * Previous: Full previous month 2. **Early/Mid Month (Day < 28)**: Compares equivalent date ranges * Current: Month start to current date * Previous: Same date range in previous month * Example: If today is Jan 19, compares Jan 1-19 vs Dec 1-19 **Use Cases** * **Progress Tracking**: Monitor user engagement trends * **Gamification**: Show improvement or decline in user activity * **Analytics**: Understand user behavior patterns over time *** ### Error Handling [#error-handling] All endpoints return appropriate HTTP status codes and error messages: #### 400 Bad Request [#400-bad-request] Returned when required parameters are missing or invalid. ```json { "statusCode": 400, "statusMessage": "Missing month parameter" } ``` #### 404 Not Found [#404-not-found] Returned when no points data is found for the specified criteria. ```json { "statusCode": 404, "statusMessage": "Points not found" } ``` ### Caching Strategy [#caching-strategy] Each endpoint implements intelligent caching to balance data freshness with performance: | Endpoint | Cache Duration | Reasoning | | ------------------------ | -------------- | --------------------------------------------- | | `/leaderboard` | 5 minutes | Leaderboard changes relatively slowly | | `/user` | 5 minutes | Detailed history is relatively stable | | `/user-by-category` | 30 seconds | Category summaries may update more frequently | | `/user-by-current-month` | 1 minute | Current month data changes more frequently | | `/vs-last-month` | 1 minute | Comparison data needs to be relatively fresh | ### Rate Limiting [#rate-limiting] No explicit rate limiting is enforced, but clients should respect the cache durations to optimize performance and reduce server load. ### Data Categories [#data-categories] Common point categories include: * `trading`: Points earned from trading activities * `staking`: Points from staking WCO tokens * `liquidity_provision`: Points from providing liquidity to pools * `referral`: Points from referring new users * `governance`: Points from participating in governance * `bridge`: Points from using cross-chain bridge functionality ### Best Practices [#best-practices] #### For Developers [#for-developers] 1. **Cache Awareness**: Respect cache durations in your application logic 2. **Error Handling**: Implement proper error handling for 400/404 responses 3. **Date Formatting**: Always use YYYY-MM format for month parameters 4. **Address Validation**: Validate Ethereum addresses before making API calls #### For Analytics [#for-analytics] 1. **Trend Analysis**: Use `/vs-last-month` for growth tracking 2. **Category Insights**: Use `/user-by-category` to understand user behavior 3. **Leaderboard Tracking**: Monitor `/leaderboard` for competitive analysis #### For User Interfaces [#for-user-interfaces] 1. **Real-time Updates**: Use `/user-by-current-month` for live progress displays 2. **Historical Data**: Use `/user` for detailed activity timelines 3. **Comparative Views**: Use `/vs-last-month` for progress indicators ### Support [#support] For technical support or questions about the Points API: * Verify parameter formats match the documentation * Check error messages for specific guidance * Ensure user addresses are valid Ethereum addresses * Consult the caching information for data freshness expectations # Audit Reports (/docs/audit-reports) | Audit Category | Audit Files | | --- | --- | | W Chain L1 Blockchain Audit Report | [W-Chain-Audit-Report.pdf](/docs-assets/files/W-Chain-Audit-Report.pdf) | | W Coin Migration Portal Audit Report | [W Coin Migration Audit Report.pdf](/docs-assets/files/W-Coin-Migration-Audit-Report.pdf) | # Proof of Stake (/docs/consensus/proof-of-stake) **Proof of Stake (PoS)** is a consensus mechanism used by blockchain networks like W Chain to secure the network and validate transactions. Unlike Proof of Work (PoW), which relies on miners solving complex cryptographic puzzles, PoS allows network participants (known as validators) to produce and validate new blocks based on the amount of cryptocurrency they hold and are willing to “stake” (lock up) as collateral. The PoS mechanism reduces energy consumption compared to PoW, while also incentivizing participants to act honestly since they have a financial stake in the network. #### How PoS Works in W Chain [#how-pos-works-in-w-chain] In W Chain’s PoS implementation, validators are selected based on their staked tokens, and they are responsible for producing and validating blocks. Validators earn rewards for their work but can also face penalties if they act dishonestly or fail to perform their duties. Here’s how the PoS mechanism functions in W Chain: 1. **Validators Stake Tokens**: To become a validator, participants must lock up (or stake) a minimum amount of W Chain tokens in a staking contract. 2. **Block Validation**: Validators are chosen to produce blocks based on the amount of tokens they have staked and their past performance. Once selected, the validator proposes a new block to be added to the blockchain. 3. **Rewards and Penalties**: Validators earn rewards for producing valid blocks. However, if they attempt to manipulate the network or act maliciously, they risk losing part or all of their staked tokens. ![Proof of Stake overview](/docs-assets/images/proof-of-stake.png) **Staking in W Chain** Staking is the process by which participants lock up their W Chain tokens to become validators. Validators are essential for maintaining the network's security and producing new blocks. The more tokens a validator stakes, the higher their chances of being selected to validate blocks and earn rewards. **Benefits of Staking**: * **Earning Rewards**: Validators earn rewards for producing blocks and validating transactions. * **Network Security**: Staking ensures that validators are financially motivated to act honestly, securing the network. * **Participation in Consensus:** Validators play a key role in maintaining consensus and ensuring the blockchain operates smoothly. **Unstaking in W Chain** Unstaking is the process of withdrawing staked tokens from the validator set. Validators can only unstake all of their tokens at once. After unstaking, they are no longer eligible to validate blocks or earn rewards. **Important Considerations**: * Validators must unstake all tokens at once; partial unstaking is not allowed. * After unstaking, validators no longer participate in block production or receive rewards. #### Epochs and Validator Responsibilities [#epochs-and-validator-responsibilities] Epochs are a critical concept in W Chain’s PoS implementation. They define specific time frames (measured in blocks) during which a particular set of validators is responsible for block production. **How Epochs Work:** 1. **Epoch Duration**: Each epoch lasts for a set number of blocks. The duration can be configured by node operators during the genesis block creation. 2. **Validator Set Update**: At the end of each epoch, the validator set is updated. Validators query the ValidatorSet Smart Contract to retrieve the new set of validators for the next epoch. 3. **New Epoch Start**: After the epoch block is produced, a new epoch begins with the updated validator set. **Why Epochs Are Important**: * **Validator Rotation**: Epochs ensure that the validator set is regularly updated, providing fairness and decentralization. New validators can join, and inactive or dishonest validators are removed. * **Staking and Unstaking**: Validators can only join or leave the set at the end of an epoch, ensuring the stability of the network during each epoch. #### Validator Responsibilities [#validator-responsibilities] **Validators are responsible for**: 1. **Block Production**: Validators propose new blocks to be added to the blockchain. This requires maintaining a consistent connection to the network and following the consensus rules. 2. **Validating Transaction**s: Validators must ensure that all transactions in the proposed block are valid according to the network rules. 3. **Staking and Security**: Validators need to maintain their stake and ensure their node is operating correctly. Misbehavior or downtime can result in penalties or removal from the validator set. **Penalties and Slashing**: * Validators who act maliciously or fail to perform their duties may lose a portion of their staked tokens through a process called slashing. This incentivizes validators to act honestly and secure the network. #### Proof of Stake Workflow in W Chain [#proof-of-stake-workflow-in-w-chain] 1. **Become a Validator**: * Stake the required minimum number of W Chain tokens. * The validator becomes part of the validator set and is eligible to propose blocks. 2. **Participate in Consensus**: * Validators are randomly selected to propose blocks based on the amount of staked tokens and their past performance. * Validators validate transactions and propose a block to the network. **Earn Rewards**: * Validators earn W Chain token rewards for each valid block they produce. 4. **Unstaking:** * Validators can choose to unstake their tokens, at which point they are removed from the validator set and cease participating in block production. # Introduction and Overview (/docs) **Welcome to W Chain** W Chain is a next-generation blockchain platform designed to bring trust, transparency, and efficiency to global payments and decentralized finance (DeFi). By combining the strengths of public and private blockchain technologies, W Chain provides businesses, developers, and users with a flexible and secure foundation to build innovative applications that scale with their needs. **What is W Chain?** W Chain is a hybrid blockchain platform that blends the openness and transparency of public blockchains with the control and security of private networks. This unique architecture ensures that businesses can operate with confidence, knowing they have the flexibility to maintain privacy where needed, while also benefiting from the decentralization of a public chain. Our vision is simple: to create a world where financial transactions are fast, secure, and accessible to everyone, everywhere. Whether you’re sending cross-border payments, developing cutting-edge DeFi applications, or securing enterprise data, W Chain empowers you to do it all efficiently and cost-effectively. # Smart contract (/docs/tutorial/smart-contract) W Chain utilizes the Ethereum Virtual Machine (EVM) in the backend. Smart contracts are written in Solidity and they can function on W Chain as they do on Ethereum. To deploy a smart contract, you send a transaction containing your bytecode without specifying any recipients. After the contract is deployed, it will be available to all users of the W Chain network. You don't have to write and deploy your smart contract manually like that, there many tools or frameworks that will help you write, test and deploy your smart contracts in better ways. ### Foundry [#foundry] Foundry is an open-source, modern development framework designed for writing, testing, and deploying Solidity smart contracts for Ethereum and other EVM-compatible blockchains. Written in Rust, it offers a fast, efficient, and developer-friendly environment with tools like Forge for compiling, testing, and deploying contracts, Cast for interacting with the blockchain via the command line, and Anvil for running a local Ethereum node for testing. Foundry emphasizes simplicity, speed, and modularity, allowing developers to write robust tests in Solidity, debug contracts easily, and integrate with existing Ethereum tools. Its focus on a test-driven development approach and seamless integration with Git makes it a popular choice for building secure and scalable decentralized applications. We recommend Foundry, as it natively use Solidity in its scripting, testing and deploying functionalities. You will never need to switch between different programming languages, use Solidity everywhere! Here is the recommended settings for your `foundry.toml`: ```toml [profile.default] src = "src" out = "out" libs = ["lib"] solc = '0.8.19' optimizer = true optimizer_runs = 10_000 [etherscan] wchain = { key = "verifyContract", chain = 171717, url = 'https://scan.w-chain.com/api' } wchain-test = { key = "verifyContract", chain = 71117, url = 'https://scan-testnet.w-chain.com/api' } [rpc_endpoints] wchain = "https://rpc.w-chain.com" wchain-test = "https://rpc-testnet.w-chain.com" ``` Using this settings, you will be able to use the RPC in your CLI commands. Here are some examples: ```bash cast send 0x6807dc923806fE8Fd134338EABCA509979a7e0cB --value 1ether --rpc-url wchain --private-key $PRIVATE_KEY ``` ```bash cast balance 0x6807dc923806fE8Fd134338EABCA509979a7e0cB --rpc-url wchain ``` ``` forge create src/SomeContract.sol:MyContract --rpc-url wchain --verify --chain 171717 --private-key $PRIVATE_KEY ``` ### Hardhat [#hardhat] Hardhat is an open-source, flexible, and extensible development environment for writing, compiling, testing, and deploying Solidity smart contracts for Ethereum and EVM-compatible blockchains. Built with JavaScript and Node.js, it provides a robust framework for developers to create, debug, and deploy smart contracts efficiently. Key features include the Hardhat Network for local blockchain testing, a powerful task runner for automating workflows, and support for plugins to extend functionality. Hardhat’s intuitive API, detailed error reporting, and integration with tools like TypeScript and Ethers.js make it ideal for both beginners and experienced developers building secure, scalable decentralized applications. Compared to Foundry, Hardhat will require you to switch contexts between Solidity and Javascript/TypeScript. This benefits developers with good Javascript background as it will use familiar testing modules, and share same contexts with Ethers JS, building early connection to UI/Frontend side of the dApp. Here is a settings you can start from: ```javascript module.exports = { networks: { w_chain_testnet: { url: "https://rpc-testnet.w-chain.com", accounts: [process.env.PRIVATE_KEY], }, w_chain: { url: "https://rpc.w-chain.com", accounts: [process.env.PRIVATE_KEY], } }, etherscan: { apiKey: "free-key", customChains: [ { network: "W Chain Testnet", chainId: 71117, urls: { apiURL: "https://scan-testnet.w-chain.com/api", browserURL: "https://scan-testnet.w-chain.com" } }, { network: "W Chain", chainId: 171717, urls: { apiURL: "https://scan.w-chain.com/api", browserURL: "https://scan.w-chain.com" } } ] } }; ``` ### Verifying Smart Contract [#verifying-smart-contract] We recommend you to use Foundry or Hardhat to build, deploy and to verify the source code on W Chain Block Explorer. If there's any situation you want to manually verify a smart contract, you can send the POST request to W Chain Block Explorer's API. Here's an example: ```bash curl --location 'https://scan.w-chain.com/api?module=contract&action=verifysourcecode' \ --form 'contractaddress="0xYourContractAddress"' \ --form 'sourceCode="// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Storage { uint256 number; function store(uint256 num) public { number = num; } function retrieve() public view returns (uint256){ return number; } }"' \ --form 'contractname="Storage"' \ --form 'codeformat="solidity-single-file"' \ --form 'compilerversion="v0.8.17+commit.8df45f5f"' \ --form 'optimizationUsed="1"' \ --form 'runs="200"' \ --form 'constructorArguements=""' \ --form 'evmversion="london"' \ --form 'licenseType="3"' ``` It's very important to ensure the exact code format, source code, compiler version, constructor arguments (if any), optimizations configs and EVM version. # Web3 Wallet Setup (/docs/tutorial/web3-wallet-setup) As a full pledged EVM compatible network, you can interact with W Chain Network using all popular Web3 Wallet app. (i.e. Rabby, Metamask, Rainbow, Phantom, etc). Add the following Network Information to your Wallet App. Depends on your app choice, it may fall under "Add Custom Network" section. * Network name: **W Chain** * RPC URL: [https://rpc.w-chain.com](https://rpc.w-chain.com) * ChainID: **171717** * Currency Symbol: **WCO** * Decimals**: 18** (if asked) * Block explorer URL: [https://scan.w-chain.com](https://scan.w-chain.com) * Network name: **W Chain Testnet** * RPC URL: [https://rpc-testnet.w-chain.com](https://rpc-testnet.w-chain.com) * ChainID: **71117** * Currency Symbol: **WCO** * Block explorer URL: [https://scan-testnet.w-chain.com](https://scan-testnet.w-chain.com) # Block Explorer (/docs/w-swap/block-explorer) - [W Scan](/docs/w-swap/block-explorer/w-scan) # W Scan (/docs/w-swap/block-explorer/w-scan) W Scan is a self‑hosted Blockscout explorer for W Chain. It runs the latest Blockscout backend (`v8.11`) with a frontend based on `v2` plus custom UI improvements. It supports both W Chain Mainnet and Testnet and includes the full Blockscout feature set. ### Overview [#overview] * Networks: `W Chain Mainnet` and `W Chain Testnet` * Chain IDs: Mainnet `171717`, Testnet `71117` * Explorer URLs: * Mainnet: `https://scan.w-chain.com` * Testnet: `https://scan-testnet.w-chain.com` * Core features: address/transaction/block/token search, decoded input data, internal txs, logs, contract verification, ABI publishing, read/write contract, token pages, labels, and API access. ### Quick Start [#quick-start] 1. Open the appropriate URL (Mainnet or Testnet). 2. Use the top search bar to paste an `address`, `transaction hash`, `block number/hash`, or `token contract`. 3. Click results to open detail pages with balances, transfers, logs, decoded calls, and more. 4. Switch networks via the network selector in the header. ### Address Pages [#address-pages] * Summary: shows total balance, token holdings, and recent transactions. * Tokens: view ERC‑20 balances and transfer history per token. * Internal txs: inspect value transfers created within contract executions. * Labels: community or system labels may appear for known contracts. ### Transaction Details [#transaction-details] * Overview: status, gas usage, fee, nonce, and timestamps. * Decoding: function signature and input parameters are decoded when ABI is known. * Logs: event topics and parameters; filter or expand for details. * Internal txs: visualize internal calls/value movements during execution. ### Token Pages [#token-pages] * Metadata: name, symbol, decimals, holders, and transfers. * Holders: ranked list of addresses and their balances. * Analytics: supply and transfer charts when available. ### Smart Contracts [#smart-contracts] * Verify: publish source code to enable full decoding and ABI access. * ABI: once verified, ABI is available to clients and the explorer. * Read/Write: interact with verified contracts directly from the UI (read state or send transactions). ### Network Switching [#network-switching] * Use the header selector to switch between `Mainnet` and `Testnet`. * Links and searches remain network‑scoped; ensure you’re on the correct network before sharing URLs. ### API & Exports [#api--exports] * W Scan exposes Blockscout’s standard APIs for indexing and querying chain data. * For endpoints, authentication options, rate limits, CSV exports, and GraphQL/REST usage, see the official Blockscout documentation at `https://docs.blockscout.com`. ### Troubleshooting [#troubleshooting] * Data not found: confirm you’re on the right network (Mainnet vs Testnet). * Undecoded input: verify the contract and publish the ABI to enable decoding. * Pending tx: network congestion may delay inclusion; retry with appropriate gas settings. * Indexing lag: recent blocks may take a moment to index; refresh after a short interval. ### FAQs [#faqs] * Is everything supported? Yes—W Scan includes the full Blockscout feature set for W Chain. * Can I verify contracts? Yes—publish sources and metadata to enable full decoding and interaction. * Where do I find developer docs? See `https://docs.blockscout.com` for complete guidance and API references \[Blockscout Docs]. # Bridge (/docs/w-swap/bridge) Bridge supported assets between W Chain and other networks using W Swap’s Bridge page. This guide covers supported chains and tokens, approvals, transaction statuses, and best practices. ### Overview [#overview] * Networks Supported: `Ethereum`, `BNB Chain`, and `W Chain` * Native Tokens: `ETH` (Ethereum), `BNB` (BNB Chain), `WCO` (W Chain) * Purpose: Move supported assets cross‑chain to trade or provide liquidity on W Chain * Finality: A validator-based process confirms bridge transfers; funds are minted or released when votes reach quorum ### Supported Assets [#supported-assets] * From Ethereum → W Chain: * `USDT` * `USDC` * From BNB Chain → W Chain: * `bUSDT` * `bUSDC` * `XRP` (BEP‑20) * `DOGE` (BEP‑20) * `SOL` (BEP‑20) * From W Chain → Ethereum or BNB Chain: * Tokens mirrored on W Chain including `USDT`, `USDC`, and Binance‑peg variants (`bUSDT`, `bUSDC`), plus `XRP`, `DOGE`, `SOL` for BNB Chain direction. Note: * Token availability depends on the selected From/To networks. The Bridge page filters assets accordingly. * On W Chain, bridged tokens have distinct addresses; always verify the token symbol and address shown in the UI. ### Chain IDs and Explorer Links [#chain-ids-and-explorer-links] * Chain IDs: * `Ethereum Mainnet`: `1` * `BNB Chain Mainnet`: `56` * `W Chain Mainnet`: `171717` * Explorers (used by the DApp): * Ethereum: `https://etherscan.io/tx/` * BNB Chain: `https://bscscan.com/tx/` * W Chain: `https://scan.w-chain.com/tx/` Testnets (if applicable): * `Sepolia` (Ethereum): `11155111` * `BNB Chain Testnet`: `97` * `W Chain Testnet`: `71117` (Explorer: `https://scan-testnet.w-chain.com/tx/`) ### Prerequisites [#prerequisites] * A supported EVM wallet (e.g., Rabby—recommended for enhanced safety—or MetaMask). * Gas on the source chain (`ETH` for Ethereum, `BNB` for BNB Chain, `WCO` for W Chain). * The token you want to bridge in your source chain wallet. ### Bridging Steps [#bridging-steps] 1. Open the `Bridge` page and connect your wallet. 2. In `From`, choose the source network (Ethereum / BNB Chain / W Chain). In `To`, choose the destination. 3. Select a supported asset for the chosen route; use the token selector or search. 4. Enter the amount to bridge. The UI shows any limits/fees and estimated arrival. 5. If prompted, click `Approve` to grant the bridge contract permission to transfer your token. 6. Click `Bridge` and confirm in your wallet. 7. Track status in the `Confirm` modal and `Bridge History`. Typical statuses include: * `Transaction Initialized` * `Transaction Pending` * `Transaction Submitted` * `Transaction Awaiting Validators Votes` * `Transaction Successful` (funds arrive on destination) * `Transaction Failed` or `Rejected` Arrival and Claiming: * No manual claim step is generally required. Funds are credited on the destination chain once validators finalize the transfer. * The DApp provides explorer links for both source and destination transactions. ### Fees and Timing [#fees-and-timing] * Fees vary by route and token. They are displayed before you confirm the bridge. * Timing depends on source chain congestion and validator finalization. Expect longer times during network congestion. ### Bridge History [#bridge-history] * Use `Bridge History` to review previous transfers, current status, and retry or reference transaction hashes as needed. ### Troubleshooting [#troubleshooting] * `Approval Required`: Approve the specific token on the source chain before bridging. * `Unsupported Route`: Switch networks or choose a supported asset for the selected From/To pair. * `Pending Too Long`: Check the explorer links and try again during lower congestion; ensure adequate gas. * `Rejected/Failed`: Review wallet prompts, increase gas settings if necessary, and retry. ### Safety Tips [#safety-tips] * Only bridge tokens listed by the DApp; do not paste arbitrary addresses. * Confirm the `From` and `To` networks are correct before submitting. * Maintain sufficient gas on both sides if you plan to interact immediately after bridging. ### FAQs [#faqs] * Can I bridge directly to trade? Yes—bridge first to W Chain, then use the Trade page. * Do I need to claim funds? No, funds arrive automatically after validator finalization. * Where do I find transaction links? In the modal and history, linking to `etherscan.io`, `bscscan.com`, and `scan.w-chain.com`. # Liquidity (/docs/w-swap/liquidity) Provide and manage liquidity in constant-product AMM pools on W Chain. This guide covers creating positions, understanding LP tokens and fees, and safely removing liquidity. ### Overview [#overview] * Network: W Chain (EVM-compatible; native gas token `WCO`) * Model: a constant-product AMM (x·y = k) * LP Tokens: Minted to represent your position; burned when removing liquidity * Fees: 0.25% per trade paid to LPs (accrues within pool reserves) ### Prerequisites [#prerequisites] * A supported wallet (e.g., Rabby or Metamask) connected to `W Chain`. * Sufficient `WCO` for gas. * The two assets you want to deposit. If assets are on Ethereum or BNB Chain, bridge them first. ### Add Liquidity [#add-liquidity] 1. Open `Liquidity` or `Add Liquidity` page. 2. Select the token pair (Token A and Token B). You may paste contract addresses for custom tokens. 3. Enter an amount for one token; the UI computes the corresponding amount for the other token based on current pool price. 4. Approve spending for each token if prompted (`Approve Token A` / `Approve Token B`). 5. Review details: * `Pool Share`: Estimated percentage of the pool you’ll own. * `Prices`: Implied exchange rates after your deposit. * `Slippage/Min Received`: Relevant when creating the initial pool or large deposits. 6. Click `Supply` (or `Add Liquidity`) and confirm in your wallet. 7. After confirmation, you receive `LP tokens` representing your position. Notes: * If a pool does not exist yet, your deposit sets the initial price. Carefully choose amounts to avoid unintended pricing. * For new pools, higher slippage tolerance may be needed; the UI will guide you. ### Remove Liquidity [#remove-liquidity] 1. Navigate to your position (e.g., `Pool` page or `Your Liquidity`). 2. Choose the position and select `Remove`. 3. If prompted, approve the router to spend your LP tokens (`Approve LP`). 4. Select the percentage to remove (e.g., 25%, 50%, 100%). 5. Review expected amounts of Token A and Token B. 6. Click `Remove`, confirm in your wallet, and wait for the transaction to finalize. ### Fees and Rewards [#fees-and-rewards] * Each trade pays a 0.25% liquidity fee to LPs, accruing inside the pool as additional reserves. * Your portion of fees is implicit in the increased value of your LP tokens. * Realization occurs when you withdraw liquidity (your redeemed amounts include fee accrual). ### Risks and Best Practices [#risks-and-best-practices] * Impermanent Loss: Price divergence between tokens can reduce your position value vs. holding. * Slippage: Large deposits/withdrawals can move price; consider splitting actions. * Smart Contract Risk: Use official UI and verified token addresses. * Gas Costs: Keep `WCO` for approvals, adds, and removals. ### Troubleshooting [#troubleshooting] * `Approve Required`: Approve both tokens before adding liquidity; approve LPs before removing. * `Insufficient Balance`: Confirm balances on W Chain and consider bridging if needed. * `Transaction Reverted`: Increase slippage tolerance or reduce deposit size. * `No Positions Visible`: Ensure correct wallet and network (`W Chain`) are selected. ### FAQs [#faqs] * How do I earn fees? Fees accumulate in the pool; your LP token share entitles you to a proportional claim when you withdraw. * Can I add single-sided liquidity? a constant-product AMM requires balanced deposits; use a swap first if needed. * Where can I see my positions? Use the `Pool` or `Your Liquidity` view in the DApp. # Trade (/docs/w-swap/trade) This guide explains how to use the Trade page of W Swap. The interface is a familiar Uniswap V2-style experience adapted for W Chain (native token `WCO`) with the same core flow: connect a wallet, select tokens, approve if required, set slippage, and confirm the trade. ### Overview [#overview] * Network: W Chain (EVM-compatible; native gas token `WCO`) * Purpose: Trade between supported ERC‑20 tokens on W Chain * Model: a constant-product AMM (x·y = k) * Key actions: Token selection, allowance approval, slippage and deadline configuration, transaction confirmation ### Prerequisites [#prerequisites] * A supported EVM wallet such as `Rabby` (recommended) or `MetaMask` installed in your browser. * Some `WCO` to pay gas fees on W Chain. * Bridged or existing assets on W Chain. If your assets are on Ethereum or BNB Chain, you can use the Bridge page to bring them to W Chain first. ### Connect Your Wallet [#connect-your-wallet] 1. Open W Swap and click `Connect Wallet`. 2. Select your wallet—`Rabby` (recommended) offers enhanced transaction safety; `MetaMask` is also supported. 3. Switch to `W Chain` in your wallet when prompted. If W Chain is not added, the app can suggest adding it automatically. ### Select Tokens and Amounts [#select-tokens-and-amounts] 1. On the Trade page, use the token selectors for `From` and `To`. 2. Choose a token from the list or paste a contract address for custom tokens. 3. Enter the `From` amount; the interface quotes the estimated output and route. 4. Review: * `Price Impact`: Expected slippage due to trade size vs. pool depth. * `Minimum Received`: Accounted for slippage tolerance. * `Route`: The path across pools the trade will take. Notes on Wrapped Native Token: * Some interfaces label the wrapped native token as `WETH` historically. On W Chain, the native token is `WCO`, and its wrapped form may be shown as `Wrapped WCO (WWCO)`. Treat any “WWCO or WETH” entry as the wrapped version of WCO used in pools. ### Allowance Approval (If Required) [#allowance-approval-if-required] Many ERC‑20 tokens require an on-chain approval before they can be spent by the router. 1. If you see an `Approve` button, click it to submit an approval transaction. 2. Wait for confirmation in your wallet and the explorer. 3. Once approved, the `Swap` button becomes available. ### Settings: Slippage and Deadline [#settings-slippage-and-deadline] * Slippage Tolerance: Adjust in the settings panel to control acceptable price movement. A typical range is `0.1%–1%` for liquid pools; higher for illiquid assets. * Transaction Deadline: Prevents stuck trades; the swap reverts if not included before the deadline. * Expert Mode: If available, use with caution; it disables some safety checks. ### Execute the Trade [#execute-the-trade] 1. Click `Trade` (the button may be labeled `Swap` in the UI). 2. Review the summary in the confirmation modal. 3. Confirm in your wallet and wait for the transaction to be mined. 4. Track the transaction via the link to `scan.w-chain.com` provided by the DApp. ### Troubleshooting [#troubleshooting] * `Insufficient Liquidity`: Try smaller amounts or a different route. * `Approval Failed`: Reopen your wallet, confirm permissions, and retry. * `High Price Impact Warning`: Reduce trade size or split into smaller trades. * `Transaction Reverted`: Increase slippage tolerance slightly or check token allowances. * `Stuck/Pending`: Consider increasing gas settings in your wallet and resubmitting. ### Safety Tips [#safety-tips] * Only paste token addresses from trusted sources. * Double-check the `Minimum Received` value matches expectations. * Keep some `WCO` for gas; trades will fail if your gas balance is 0. ### FAQs [#faqs] * Can I trade from Ethereum or BNB Chain directly? No, first bridge supported assets to W Chain using the `Bridge` page, then trade on W Chain. * Why do I see `Approve` before `Trade`? ERC‑20 tokens require a one-time allowance for the router to spend your tokens. * Where do I view my transaction? Use the explorer link (e.g., `https://scan.w-chain.com/tx/`). # Farm (/docs/w-swap/wave/farm) ![WAVE Farm](/docs-assets/images/wave-farm.png) ### What Is WAVE Farm? [#what-is-wave-farm] * **Network**: W Chain (custom EVM network). Gas token is `WCO` (acts like ETH on W Chain). * **DEX**: [W Swap](/docs/w-swap/trade). Liquidity providers receive **LP tokens** that represent their share of a pool. * **Farm**: WAVE Farm lets you stake those LP tokens to earn **WAVE** rewards. *** ### Quick Start [#quick-start] 1. Open `https://wave.w-chain.com` in a desktop browser with an EVM wallet (Rabby is recommended). 2. Connect your wallet. If prompted, approve adding **W Chain** to your wallet. 3. Fund your wallet with some `WCO` to pay gas fees. 4. Add liquidity on [**W Swap** Liquidity Pool page](/docs/w-swap/liquidity) to receive LP tokens. 5. Return to **WAVE Farm** and stake the LP tokens to start earning WAVE. *** ### Interface Overview [#interface-overview] * **Total Value Locked (TVL)**: Overall value staked in the protocol. * **Your Farms**: Shows your total staked amount, pending rewards, and pool list. * **Actions**: * `Add Liquidity`: Shortcut to W Swap’s liquidity page. * `Harvest All`: Claim all pending WAVE rewards across all pools. * Per‑pool actions: `Stake / Deposit`, `Harvest`, and `Withdraw`. *** ### How It Works (LP Staking) [#how-it-works-lp-staking] * You deposit LP tokens (from W Swap) into the farm’s contracts. * The farm periodically distributes **WAVE** rewards to each pool based on allocation (weight/multiplier). * Your share of the pool’s rewards depends on your **stake relative to total staked LP** in that pool. *** ### [Add Liquidity on W Swap](/docs/w-swap/liquidity#add-liquidity) [#add-liquidity-on-w-swap] 1. Go to `https://w-swap.com/#/pool`. 2. Select a token pair (e.g., `WAVE/WCO`, `USDT/WCO`). 3. Provide equal value of each token and confirm the transaction. 4. After the transaction, you’ll receive **LP tokens** for that pair. Tip: Pools with higher multipliers may have higher reward rates but often attract more stakers (see Dilution below). *** ### Stake (Deposit) LP Tokens [#stake-deposit-lp-tokens] 1. On `https://wave.w-chain.com`, locate the pool that matches your LP token (e.g., `WAVE/WCO`). 2. Click `Stake` or `Deposit`. 3. If this is your first time, click `Approve` to allow the farm to use your LP tokens. 4. Enter the LP amount to stake and confirm the transaction. 5. After confirmation, your staked balance appears under the pool, and rewards begin accruing. Notes: * Approval is a one‑time transaction per LP token. * Gas fees are paid in `WCO`. Keep a small buffer for future actions. *** ### Harvest Rewards (Single Pool) [#harvest-rewards-single-pool] 1. In the pool row, click `Harvest` to claim your pending WAVE from that pool. 2. Confirm the transaction in your wallet. 3. After confirmation, your wallet receives WAVE and the pool’s pending amount resets to `0`. When to harvest: * You can harvest anytime. Frequent harvesting increases gas costs; occasional harvesting is more cost‑efficient. *** ### Harvest All (Across All Pools) [#harvest-all-across-all-pools] 1. Click `Harvest All` in the top right of Your Farms. 2. Review the summary (pending WAVE amount) and confirm. 3. The app sends transactions to claim rewards from all pools you are staked in. Tip: Harvest All is convenient but may cost more gas overall than harvesting only the pool(s) you care about at the moment. *** ### Withdraw LP Tokens [#withdraw-lp-tokens] 1. In the pool row, click `Withdraw`. 2. Enter the LP amount you want to remove and confirm. 3. Your LP tokens return to your wallet; you stop earning rewards on the withdrawn amount. Common reasons to withdraw: * Rebalancing liquidity, reducing exposure, or moving to a different pool. *** ### Reward APR Explained [#reward-apr-explained] * **APR** is the annualized rate of rewards distributed to a pool, expressed as a percentage of the pool’s total value. * It depends on several factors, and therefore **changes over time**: * WAVE emission rate to farms. * Pool weight/multiplier (allocation). * Total value staked in the pool (TVL). * Market price of WAVE and the LP tokens. Conceptual formula: ``` Pool APR ≈ (Rewards to pool per year × WAVE price) / Pool TVL ``` Your personal yield will be close to the pool APR when your share of the pool is small relative to total TVL; harvesting and compounding can move you closer to **APY** (with compounding) rather than APR (no compounding). *** ### Dilution Risk (Why Your APR Can Drop) [#dilution-risk-why-your-apr-can-drop] * **Dilution** happens when more users stake into the same pool. Your fractional share of rewards becomes smaller. * Pools with high multipliers often attract new stake quickly, which can dilute early participants unless they also increase stake. * Practical implications: * If TVL rises faster than rewards allocated to the pool, APR falls. * Your pending rewards accumulate at a slower rate when your share shrinks. * To maintain yield, some users harvest and restake (compound), but this requires additional gas and exposes you to IL (impermanent loss) if you adjust underlying liquidity. Risk tips: * Don’t chase APR alone; check pool TVL trends and token volatility. * Harvest on a cadence that balances gas cost and reward accrual. * Diversify across pools to reduce single‑pool dilution risk. *** ### Fees, Gas, and Costs [#fees-gas-and-costs] * All transactions (approve, stake, harvest, withdraw) cost gas paid in `WCO`. * Keep a small `WCO` balance to avoid failed transactions. * Liquidity positions on W Swap are subject to **DEX trading fees** and **impermanent loss**; the farm rewards aim to offset these but cannot guarantee profit. *** ### Troubleshooting [#troubleshooting] * Can’t connect wallet: Ensure your wallet is unlocked and your browser allows wallet connections. * Wrong network: Switch to **W Chain** in your wallet. The site may prompt you to add/switch networks. * No LP tokens showing: Confirm you added liquidity to the exact token pair and are on the correct network. * Approval error: Try increasing the gas or resetting wallet allowance if an earlier approve was rejected. * Stuck transaction: Speed up or cancel from your wallet; then retry. *** ### FAQs [#faqs] * **What’s the difference between APR and APY?** APR ignores compounding; APY includes it. If you harvest and restake regularly, your realized return moves toward APY. * **Which pool should I choose?** Consider multiplier, TVL, token volatility, and your portfolio goals. Higher APR can be short‑lived if dilution increases. * **Do I need to claim rewards before withdrawing?** No. Withdrawing usually harvests or leaves rewards claimable depending on pool contract behavior. When in doubt, harvest first. * **Is my principal safe?** Your LP tokens are staked in smart contracts. Smart contract risk, market risk, and impermanent loss still apply. *** ### Useful Links [#useful-links] * WAVE Farm: `https://wave.w-chain.com` * W Swap (Add Liquidity): `https://app.w-swap.com/#/pool` * W Chain: `https://w-chain.com` *** ### Best Practices (Quick Checklist) [#best-practices-quick-checklist] * Keep `WCO` for gas at all times. * Approve only the LP tokens you plan to stake. * Monitor APR and TVL; watch for dilution. * Harvest on a sensible schedule; consider compounding if it fits your strategy. * Review token risks and impermanent loss before adding liquidity. *** ### Disclaimer [#disclaimer] This guide is for informational purposes only and does not constitute financial advice. Rewards, APR, and prices fluctuate. Always do your own research and manage risk responsibly. # WAVE (/docs/w-swap/wave) - [Farm](/docs/w-swap/wave/farm) # Key Features That Make W Chain (/docs/welcome-to-w-chain/key-features-that-make-w-chain) **Mainnet and Testnet**: * The **W Chain Mainnet** is our fully operational network, where real-world applications are deployed securely and efficiently. * The **W Chain Testnet** is a safe testing environment for developers to experiment, deploy, and fine-tune applications before launching on the Mainnet. **Hybrid Blockchain**: W Chain’s hybrid model offers the best of both worlds—public blockchain for transparency and community-driven applications, and private blockchain for businesses that need tighter control over their data and operations. **High Performance**: W Chain is built to handle thousands of transactions per second (TPS), ensuring that no matter the scale, your business can run smoothly without interruptions or delays. **Scalability**: Our architecture is designed to grow with you. Whether you're a startup or a global enterprise, W Chain can scale to meet your needs with ease. **DeFi-Ready**: Developers can quickly deploy decentralized finance applications, from staking mechanisms to complex lending and borrowing protocols. # Roadmap (/docs/welcome-to-w-chain/roadmap) ![W Chain roadmap](/docs-assets/images/roadmap.png) # Node (/docs/working-with-a-node/node) ### Overview [#overview] In a Proof-of-Stake (PoS) Ethereum Virtual Machine (EVM) compatible blockchain, nodes form the foundational infrastructure that ensures the network’s functionality, security, and decentralization. Nodes are broadly classified into two categories—Validator Nodes and Non-Validator Nodes—each fulfilling specific roles within the ecosystem. This section provides a high-level introduction to these node types and their contributions to a PoS EVM network, setting the stage for detailed exploration in subsequent sections. ### Node Types and Roles [#node-types-and-roles] #### Validator Node [#validator-node] Validator Nodes are active participants in the PoS consensus mechanism. By staking a required amount of cryptocurrency, these nodes are responsible for validating transactions, proposing new blocks, and finalizing them through a process known as "sealing." They play a critical role in maintaining the network’s security and integrity, earning staking rewards and transaction fees in return for their efforts. #### Non-Validator Node [#non-validator-node] Non-Validator Nodes, identified by a seal: false configuration, do not engage in the consensus process or block production. Operating as full nodes or light nodes, they focus on synchronizing with the blockchain, verifying transactions and blocks for local use, and relaying data across the network. These nodes enhance accessibility, support decentralized data propagation, and provide infrastructure for applications and users without the resource-intensive demands of validation. ### Network Contribution [#network-contribution] Validator Nodes drive the core operations of block creation and consensus, ensuring the blockchain progresses securely and consistently. Non-Validator Nodes complement this by bolstering network resilience, enabling data availability, and facilitating broader participation. Together, they create a balanced and robust PoS EVM environment. # Non-Validator Node Setup (/docs/working-with-a-node/node/non-validator-node-setup) A Non-Validator Node follows the chain and verifies every block, but does not take part in consensus or produce blocks. Developers, dApps, exchanges and explorers use one to query the blockchain through their own RPC endpoint. No stake is needed. Since block **24,630,300** (12 October 2026) the network runs the v1.0.8 consensus rules. Older versions can no longer follow the chain. Every command on this page uses **v1.0.8**. This guide is for **mainnet**. Testnet node packages for v1.0.8 are not published yet. If you need a testnet node, contact the W Chain team. Don't set up a new node. Follow the upgrade guide instead: it replaces the binary and `genesis.json` and keeps everything else. It is written for validators, but the steps are the same for any node. [Download the v1.0.8 upgrade guide (PDF)](/docs-assets/files/W-Chain-Validator-Upgrade-v1.0.8.pdf) ### Step 1: Prepare the System [#step-1-prepare-the-system] Your machine must meet these minimums: | Resource | Minimum | | --- | --- | | vCPUs | 2 or more | | Memory | 8 GB | | Disk | 200 GB, SSD or NVMe | | OS | Ubuntu 20.04, 22.04 or 24.04 (x86-64 / amd64) | | Network | 5 Mbps up and down | You can run a node on your own dedicated server, but a professional cloud provider such as AWS, DigitalOcean, Azure, GCP, Hetzner or Contabo is recommended. ### Step 2: Install Dependencies [#step-2-install-dependencies] ```bash sudo apt update && sudo apt upgrade -y sudo apt install -y curl ``` These commands use `apt`. Adjust them if your system uses a different package manager. ### Step 3: Prepare Directory [#step-3-prepare-directory] ```bash mkdir -p ~/w-chain && cd ~/w-chain ``` The rest of this guide assumes the user is `ubuntu`, so the folder is `/home/ubuntu/w-chain`. If your user is different, use your own path everywhere you see `/home/ubuntu/w-chain`. ### Step 4: Download Node v1.0.8 and genesis.json [#step-4-download-node-v108-and-genesisjson] Both come from the [v1.0.8 release](https://github.com/w-chain/node/releases/tag/v1.0.8). It is published for **Linux amd64**, which is what AWS EC2 and most VPS providers use. ```bash cd ~/w-chain U=https://github.com/w-chain/node/releases/download/v1.0.8 curl -fL -O $U/w-chain-node-v1.0.8-linux-amd64.tar.gz curl -fL -O $U/genesis.json curl -fL -O $U/checksums-v1.0.8.txt sha256sum -c checksums-v1.0.8.txt ``` `curl` prints download progress first. The last two lines must be: ``` w-chain-node-v1.0.8-linux-amd64.tar.gz: OK genesis.json: OK ``` If anything says `FAILED`, delete the files and download them again. Unpack the node and give it a short name. The rest of this guide calls it `w-chain-node`: ```bash tar -xzf w-chain-node-v1.0.8-linux-amd64.tar.gz mv w-chain-node-linux-amd64 w-chain-node chmod +x w-chain-node ``` Do not edit `genesis.json`, and always take it from the v1.0.8 release. It switches on the v1.0.8 rules and lists the current bootnodes. An older copy either makes the node stop at block 24,630,300 or points at bootnodes that no longer exist. ### Step 5: Verify Files [#step-5-verify-files] ```bash ./w-chain-node version grep -c wchainv1 genesis.json ``` You should see: ``` [VERSION INFO] Release version = v1.0.8 Git branch = fix/v1.0.8 Commit hash = a474bc5bd34e2c35bbc432e7ef2e81a62b99673a Build time = Thu Oct 8 09:18:20 UTC 2026 4 ``` The version must read **v1.0.8** and the last line must be **4**. If not, go back to Step 4. ### Step 6: Initialize Keys and Blockchain Data Directories [#step-6-initialize-keys-and-blockchain-data-directories] This creates the data directory and the node's network identity: ```bash ./w-chain-node secrets init --data-dir main-chain --insecure ``` A non-validator never signs blocks, so you don't need to save or protect the keys this prints. They only identify your node to its peers. ### Step 7: Create Server Config [#step-7-create-server-config] Keep the node's settings in a config file instead of passing flags. From `~/w-chain`, generate the template and open it: ```bash cd ~/w-chain ./w-chain-node server export --type json nano default-config.json ``` Set these values. Use absolute paths: | Setting | Value | Notes | | --- | --- | --- | | `chain_config` | `/home/ubuntu/w-chain/genesis.json` | The genesis file from Step 4 | | `data_dir` | `/home/ubuntu/w-chain/main-chain` | The data directory from Step 6 | | `grpc_addr` | `127.0.0.1:9632` | Admin API, local only. It has no password | | `jsonrpc_addr` | `127.0.0.1:8545` or `0.0.0.0:8545` | See "Exposing RPC" below | | `network` → `libp2p_addr` | `0.0.0.0:1478` | Peer-to-peer, must be reachable from the internet | | `network` → `nat_addr` | your server's public IP | So peers can reach you | | `tx_pool` → `price_limit` | `800000000000` | Minimum gas price in wei (800 Gwei) | | `seal` | `false` | A non-validator must **not** seal | The relevant lines look like this: ```json title="default-config.json" "chain_config": "/home/ubuntu/w-chain/genesis.json", "data_dir": "/home/ubuntu/w-chain/main-chain", "grpc_addr": "127.0.0.1:9632", "jsonrpc_addr": "127.0.0.1:8545", "network": { ... "libp2p_addr": "0.0.0.0:1478", "nat_addr": "203.0.113.10", ... }, "seal": false, "tx_pool": { "price_limit": 800000000000, ... } ``` #### Exposing RPC [#exposing-rpc] - **Only your own apps on this server use it:** keep `127.0.0.1:8545`. - **Other machines need it:** the safest setup keeps `127.0.0.1:8545` and puts a reverse proxy (for example nginx or Caddy) in front of it, with HTTPS and rate limiting. If you must bind `0.0.0.0:8545`, allow 8545 in the firewall only from the IP addresses that need it. ### Step 8: Utilizing Blockchain Backup File [#step-8-utilizing-blockchain-backup-file] Syncing from scratch takes days and gets slower as the chain grows. Start from the published snapshot instead. The `mainnet/latest` links always point to the newest snapshot. The current one is from 7 September 2026; your node syncs the remaining blocks from peers after it starts. ```bash cd ~/w-chain/main-chain B=https://wchain-sanpshot-677276113339-eu-central-1-an.s3.eu-central-1.amazonaws.com/mainnet/latest curl -fL -O $B/trie.tar.gz curl -fL -O $B/blockchain.tar.gz curl -fL -O $B/SHA256SUMS ``` This is the slowest step: about 16 GB in total. #### Verify before unpacking [#verify-before-unpacking] A truncated download gives a corrupt database that fails in confusing ways later, so check both archives first: ```bash sha256sum -c SHA256SUMS ``` Both lines must read `OK`. If one doesn't, delete that archive, download it again and re-check. #### Unpack [#unpack] ```bash tar -xzf trie.tar.gz && rm trie.tar.gz tar -xzf blockchain.tar.gz && rm blockchain.tar.gz ``` `main-chain` now holds four directories: the new `blockchain` and `trie`, plus `consensus` and `libp2p` from Step 6. #### Fix ownership [#fix-ownership] The files must belong to the user the service runs as: ```bash sudo chown -R ubuntu:ubuntu /home/ubuntu/w-chain/main-chain ``` Replace `ubuntu:ubuntu` with your user and group if they differ. `ls -ld /home/ubuntu/w-chain` shows them. ### Step 9: Create a System Service [#step-9-create-a-system-service] Run the node as a systemd service so it survives reboots and restarts if it crashes: ```bash sudo nano /etc/systemd/system/w-chain-node.service ``` Paste this in: ```ini title="/etc/systemd/system/w-chain-node.service" [Unit] Description=W Chain Node After=network.target StartLimitIntervalSec=1 [Service] Type=simple User=ubuntu WorkingDirectory=/home/ubuntu/w-chain ExecStart=/home/ubuntu/w-chain/w-chain-node server --config /home/ubuntu/w-chain/default-config.json Restart=on-failure RestartSec=5 LimitNOFILE=65535 [Install] WantedBy=multi-user.target ``` Save and exit. Adjust `User` and the paths if your setup differs. ### Step 10: Enable and Run the Node Service [#step-10-enable-and-run-the-node-service] ```bash sudo systemctl daemon-reload sudo systemctl enable w-chain-node.service sudo systemctl start w-chain-node.service ``` Your node now catches up with the network from the snapshot. Watch it: ```bash journalctl -u w-chain-node -f ``` You want a steady stream of `block committed` lines with rising block numbers. To check how far it has synced, ask your node for its latest block and compare it with [W Scan](https://scan.w-chain.com): ```bash curl -s -X POST -H 'Content-Type: application/json' \ --data '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}' \ http://127.0.0.1:8545 ``` The result is the block number in hex. ### Step 11: Firewall [#step-11-firewall] Open only what you need: | Port | Open to | | --- | --- | | **1478/tcp** (P2P) | Everyone. Required | | **8545/tcp** (RPC) | Only the IPs that use your RPC, and only if you bound it to `0.0.0.0` | | **9632/tcp** (admin API) | Nobody. Never expose it | Allow SSH first, or you will lock yourself out. If your SSH port is not 22, use your port number. ```bash sudo apt-get install -y ufw sudo ufw allow 22/tcp sudo ufw allow 1478/tcp sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw --force enable sudo ufw status verbose ``` To let one machine use your RPC, replace `1.2.3.4` with its IP: ```bash sudo ufw allow from 1.2.3.4 to any port 8545 proto tcp ``` If Docker runs on the same machine, its published ports bypass ufw. Bind containers to `127.0.0.1`, or use your provider's firewall instead. In your provider's firewall (on AWS, the instance's Security Group), allow inbound only: - TCP **1478** from anywhere (IPv4 and IPv6) - TCP **22** (SSH) from your own IP - TCP **8545** only from the IPs that use your RPC, if you need it Allow all outbound. ### Important Commands to Maintain and Monitor Your Node [#important-commands-to-maintain-and-monitor-your-node] #### Service [#service] ```bash sudo systemctl start w-chain-node ``` ```bash sudo systemctl stop w-chain-node ``` ```bash sudo systemctl restart w-chain-node ``` ```bash sudo systemctl status w-chain-node ``` #### Logging [#logging] ```bash journalctl -u w-chain-node ``` ```bash journalctl -u w-chain-node -f ``` #### Is my node following the chain? [#is-my-node-following-the-chain] Count the blocks it committed in the last minute: ```bash sudo journalctl -u w-chain-node -S -1min | grep -c 'block committed' ``` Blocks come about every 2 seconds, so a node that has caught up shows about **20–35**. A number near **0** means it is not following the chain. ### Troubleshooting [#troubleshooting] **The node does not start: `fork is not available: wchainv1…`** `genesis.json` is from v1.0.8 but the binary is older. Repeat Step 4 and check that `./w-chain-node version` says v1.0.8. **The node runs but stays stuck or finds no peers** 1. Port **1478** is reachable from the internet and `nat_addr` is your public IP. 2. `genesis.json` came from the **v1.0.8** release: `grep -c wchainv1 genesis.json` must print `4`. 3. `seal` is `false` and `./w-chain-node version` reports **v1.0.8**. # Validator Node Setup (/docs/working-with-a-node/node/validator-node-setup) This guide sets up a **Validator Node** on W Chain mainnet (chain ID 171717). A validator stakes **10,000,000 WCO** and produces blocks with the rest of the network, so plan for a machine that stays online all the time. Since block **24,630,300** (12 October 2026) the network runs the v1.0.8 consensus rules. Older versions can no longer follow the chain. Every command on this page uses **v1.0.8**. This guide is for **mainnet**. Testnet node packages for v1.0.8 are not published yet. If you need a testnet node, contact the W Chain team. Don't set up a new node. Follow the upgrade guide instead: it replaces the binary and `genesis.json`, keeps your keys, config, chaindata and stake, and takes about 10 minutes. [Download the v1.0.8 upgrade guide (PDF)](/docs-assets/files/W-Chain-Validator-Upgrade-v1.0.8.pdf) **What you will do:** 1. Prepare the machine and install dependencies (Steps 1–3) 2. Download and verify node v1.0.8 and `genesis.json` (Steps 4–5) 3. Create your validator keys and server config (Steps 6–7) 4. Restore the chaindata snapshot (Step 8) 5. Stake and register on-chain (Steps 9–10) 6. Run the node as a service and lock down the firewall (Steps 11–13) Budget about an hour, most of it waiting for the snapshot download. It controls your entire 10,000,000 WCO stake and can move it in a single transaction with no delay. Store it in a password manager. Never paste it into a chat or a ticket, and never put it on a machine you don't control. ### Step 1: Prepare the System [#step-1-prepare-the-system] Your machine must meet these minimums: | Resource | Minimum | | --- | --- | | vCPUs | 4 or more | | Memory | 16 GB | | Disk | 1 TB, SSD or NVMe | | OS | Ubuntu 20.04, 22.04 or 24.04 (x86-64 / amd64) | | Node.js | v22 with npm v10 or newer | | Network | 5 Mbps up and down | Node.js is only needed for the staking scripts in Step 9, not to run the node. You can run a node on your own dedicated server, but a professional cloud provider such as AWS, DigitalOcean, Azure, GCP, Hetzner or Contabo is recommended. ### Step 2: Install Dependencies [#step-2-install-dependencies] ```bash sudo apt update && sudo apt upgrade -y sudo apt install -y git npm ``` These commands use `apt`. Adjust them if your system uses a different package manager. ### Step 3: Prepare Directory [#step-3-prepare-directory] ```bash mkdir -p ~/w-chain && cd ~/w-chain ``` The rest of this guide assumes the user is `ubuntu`, so the folder is `/home/ubuntu/w-chain`. If your user is different, use your own path everywhere you see `/home/ubuntu/w-chain`. ### Step 4: Download Node v1.0.8 and genesis.json [#step-4-download-node-v108-and-genesisjson] Both come from the [v1.0.8 release](https://github.com/w-chain/node/releases/tag/v1.0.8). It is published for **Linux amd64**, which is what AWS EC2 and most VPS providers use. ```bash cd ~/w-chain U=https://github.com/w-chain/node/releases/download/v1.0.8 curl -fL -O $U/w-chain-node-v1.0.8-linux-amd64.tar.gz curl -fL -O $U/genesis.json curl -fL -O $U/checksums-v1.0.8.txt sha256sum -c checksums-v1.0.8.txt ``` `curl` prints download progress first. The last two lines must be: ``` w-chain-node-v1.0.8-linux-amd64.tar.gz: OK genesis.json: OK ``` If anything says `FAILED`, delete the files and download them again. Unpack the node and give it a short name. The rest of this guide calls it `w-chain-node`: ```bash tar -xzf w-chain-node-v1.0.8-linux-amd64.tar.gz mv w-chain-node-linux-amd64 w-chain-node chmod +x w-chain-node ``` Do not edit `genesis.json`, and always take it from the v1.0.8 release. It switches on the v1.0.8 rules and lists the current bootnodes. An older copy either makes the node stop at block 24,630,300 or points at bootnodes that no longer exist. ### Step 5: Verify Files [#step-5-verify-files] ```bash ./w-chain-node version grep -c wchainv1 genesis.json ``` You should see: ``` [VERSION INFO] Release version = v1.0.8 Git branch = fix/v1.0.8 Commit hash = a474bc5bd34e2c35bbc432e7ef2e81a62b99673a Build time = Thu Oct 8 09:18:20 UTC 2026 4 ``` The version must read **v1.0.8** and the last line must be **4**. If not, go back to Step 4. ### Step 6: Initialize Keys and Blockchain Data Directories [#step-6-initialize-keys-and-blockchain-data-directories] This creates the data directory and your validator keys: ```bash ./w-chain-node secrets init --data-dir main-chain --insecure ``` It prints your new identity: ``` [SECRETS OUTPUT] Public key (address) = 0x9C107AA6471e3...E9c6EdE083b8f5 BLS Public key = 0x800f1157a49bb59f5e5d790...fe349fa19a3c323f518a4bd4aa963 Node ID = 16Uiu2HAmVbykGW...DUpLgTw7NbDVbKf1Me4D ``` Save all three. You need the address and the BLS public key in Step 10. You also need the **private key** of this address. It is the single line in this file: ```bash cat ~/w-chain/main-chain/consensus/validator.key ``` Copy it somewhere safe (a password manager), then clear your terminal with `clear`. The node keeps `validator.key` on disk because it signs blocks with it. Tighten its permissions. Run this as the same user the node service will run as, or the node can't read its own keys: ```bash chmod 400 ~/w-chain/main-chain/consensus/validator.key chmod 400 ~/w-chain/main-chain/consensus/validator-bls.key ``` ### Step 7: Create Server Config [#step-7-create-server-config] Keep the node's settings in a config file instead of passing flags. From `~/w-chain`, generate the template and open it: ```bash cd ~/w-chain ./w-chain-node server export --type json nano default-config.json ``` Set these values. Use absolute paths: | Setting | Value | Notes | | --- | --- | --- | | `chain_config` | `/home/ubuntu/w-chain/genesis.json` | The genesis file from Step 4 | | `data_dir` | `/home/ubuntu/w-chain/main-chain` | The data directory from Step 6 | | `grpc_addr` | `127.0.0.1:9632` | Admin API, local only. It has no password | | `jsonrpc_addr` | `127.0.0.1:8545` | Local only. Never `0.0.0.0` | | `network` → `libp2p_addr` | `0.0.0.0:1478` | Peer-to-peer, must be reachable from the internet | | `tx_pool` → `price_limit` | `800000000000` | Minimum gas price in wei (800 Gwei) | | `seal` | `true` | Required for a validator | The relevant lines look like this: ```json title="default-config.json" "chain_config": "/home/ubuntu/w-chain/genesis.json", "data_dir": "/home/ubuntu/w-chain/main-chain", "grpc_addr": "127.0.0.1:9632", "jsonrpc_addr": "127.0.0.1:8545", "network": { ... "libp2p_addr": "0.0.0.0:1478", ... }, "seal": true, "tx_pool": { "price_limit": 800000000000, ... } ``` A validator should never serve RPC to the internet: an open RPC port gives anyone a direct line into a consensus machine. If you need a public RPC endpoint, run a separate [Non-Validator Node](/docs/working-with-a-node/node/non-validator-node-setup). ### Step 8: Utilizing Blockchain Backup File [#step-8-utilizing-blockchain-backup-file] Syncing from scratch takes days and gets slower as the chain grows. Start from the published snapshot instead. The `mainnet/latest` links always point to the newest snapshot. The current one is from 7 September 2026; your node syncs the remaining blocks from peers after it starts. ```bash cd ~/w-chain/main-chain B=https://wchain-sanpshot-677276113339-eu-central-1-an.s3.eu-central-1.amazonaws.com/mainnet/latest curl -fL -O $B/trie.tar.gz curl -fL -O $B/blockchain.tar.gz curl -fL -O $B/SHA256SUMS ``` This is the slowest step: about 16 GB in total. #### Verify before unpacking [#verify-before-unpacking] A truncated download gives a corrupt database that fails in confusing ways later, so check both archives first: ```bash sha256sum -c SHA256SUMS ``` Both lines must read `OK`. If one doesn't, delete that archive, download it again and re-check. #### Unpack [#unpack] ```bash tar -xzf trie.tar.gz && rm trie.tar.gz tar -xzf blockchain.tar.gz && rm blockchain.tar.gz ``` `main-chain` now holds four directories: the new `blockchain` and `trie`, plus `consensus` and `libp2p` from Step 6. #### Fix ownership [#fix-ownership] The files must belong to the user the service runs as: ```bash sudo chown -R ubuntu:ubuntu /home/ubuntu/w-chain/main-chain ``` Replace `ubuntu:ubuntu` with your user and group if they differ. `ls -ld /home/ubuntu/w-chain` shows them. ### Step 9: Staking Contract [#step-9-staking-contract] Every validator must stake at least **10,000,000 WCO**. Misbehaviour can be slashed, which keeps operators honest. Clone the staking scripts and install their dependencies: ```bash cd ~/w-chain git clone https://github.com/w-chain/staking-contract.git cd staking-contract npm i ``` Create the environment file: ```bash cp .env.example .env chmod 600 .env nano .env ``` You will see: ``` #JUST ADD YOUR PRIVATE KEY HERE PRIVATE_KEY=your_private_key_here # KEEP THIS AS IS CONTRACT_ADDRESS=0xfAc510D5dB8cadfF323D4b979D898dc38F3FB6dF RPC_URL=https://rpc.w-chain.com ``` Replace `your_private_key_here` with the private key from [Step 6](#step-6-initialize-keys-and-blockchain-data-directories). Change nothing else, then save and exit. This file now holds a key that controls 10 million WCO. Never commit it to Git, and delete it once staking is done. The node itself does not need it. ### Step 10: Load up the Stake [#step-10-load-up-the-stake] First fund your validator address (the public key from Step 6). You need the stake plus gas, so hold at least **10,000,001 WCO**. #### Stake [#stake] ```bash cd ~/w-chain/staking-contract npm run cli stake 10000000 ``` On success the script returns a transaction hash. #### Register your BLS public key [#register-your-bls-public-key] Use the BLS public key printed in Step 6. This value is only an example: ```bash npm run cli registerBLSPublicKey 0x800f1157a49bb59f5e5d790...fe349fa19a3c323f518a4bd4aa963 ``` #### Confirm [#confirm] ```bash npm run cli isValidator ``` It should return `true`. Both actions are required. A node that stakes but never registers its BLS key cannot take part in consensus. Once both are done, delete `.env`: ```bash rm ~/w-chain/staking-contract/.env ``` The new validator joins the active set at the next epoch boundary, which comes about every hour. ### Step 11: Create a System Service [#step-11-create-a-system-service] Run the node as a systemd service so it survives reboots and restarts if it crashes: ```bash sudo nano /etc/systemd/system/w-chain-node.service ``` Paste this in: ```ini title="/etc/systemd/system/w-chain-node.service" [Unit] Description=W Chain Validator Node After=network.target StartLimitIntervalSec=1 [Service] Type=simple User=ubuntu WorkingDirectory=/home/ubuntu/w-chain ExecStart=/home/ubuntu/w-chain/w-chain-node server --config /home/ubuntu/w-chain/default-config.json Restart=on-failure RestartSec=5 LimitNOFILE=65535 [Install] WantedBy=multi-user.target ``` Save and exit. Adjust `User` and the paths if your setup differs. | Line | Why it matters | | --- | --- | | `Restart=on-failure` | Restarts the node if the process dies. Without it, a crash leaves your validator offline until you notice. | | `RestartSec=5` | Waits 5 seconds between restart attempts. | | `LimitNOFILE=65535` | A node with many peers opens many files; the default limit can be hit under load. | ### Step 12: Enable and Run the Node Service [#step-12-enable-and-run-the-node-service] ```bash sudo systemctl daemon-reload sudo systemctl enable w-chain-node.service sudo systemctl start w-chain-node.service ``` Your node now catches up with the network from the snapshot. Watch it: ```bash journalctl -u w-chain-node -f ``` You want a steady stream of `block committed` lines with rising block numbers. ### Step 13: Firewall [#step-13-firewall] A validator needs **one** port open to the internet: **1478/tcp** (peer-to-peer). Everything else should be closed. Check what the node listens on: ```bash sudo ss -ltnp | grep w-chain-node ``` | You should see | Meaning | | --- | --- | | `0.0.0.0:1478` | P2P: must be public | | `127.0.0.1:8545` | JSON-RPC: local only ✔ | | `127.0.0.1:9632` | Admin API: local only ✔ | If 8545 or 9632 show `0.0.0.0` or `*`, fix `jsonrpc_addr` / `grpc_addr` in your config (Step 7) and restart. **Never expose 9632.** Allow SSH first, or you will lock yourself out. If your SSH port is not 22, use your port number. ```bash sudo apt-get install -y ufw sudo ufw allow 22/tcp sudo ufw allow 1478/tcp sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw --force enable sudo ufw status verbose ``` `ufw status` should list only your SSH port and 1478, for both IPv4 and IPv6. If Docker runs on the same machine, its published ports bypass ufw. Bind containers to `127.0.0.1`, or use your provider's firewall instead. In your provider's firewall (on AWS, the instance's Security Group), allow inbound only: - TCP **1478** from anywhere (IPv4 and IPv6) - TCP **22** (SSH) from your own IP Allow all outbound. #### Check from outside [#check-from-outside] Run this on **your own computer**, not on the server. The server's own firewall doesn't filter its own connections, so testing from the server proves nothing. ```bash nc -zv -G 5 1478 nc -zv -G 5 8545 nc -zv -G 5 9632 ``` ```bash nc -zv -w 5 1478 nc -zv -w 5 8545 nc -zv -w 5 9632 ``` ```powershell Test-NetConnection -Port 1478 Test-NetConnection -Port 8545 Test-NetConnection -Port 9632 ``` Port **1478** must succeed. **8545** and **9632** must be refused or time out. ### Important Commands to Maintain and Monitor Your Node [#important-commands-to-maintain-and-monitor-your-node] #### Service [#service] ```bash sudo systemctl start w-chain-node ``` ```bash sudo systemctl stop w-chain-node ``` ```bash sudo systemctl restart w-chain-node ``` ```bash sudo systemctl status w-chain-node ``` #### Logging [#logging] ```bash journalctl -u w-chain-node ``` ```bash journalctl -u w-chain-node -f ``` #### Is my validator actually working? [#is-my-validator-actually-working] A running service tells you little: a node can look healthy while contributing nothing. Count the blocks it committed in the last minute instead: ```bash sudo journalctl -u w-chain-node -S -1min | grep -c 'block committed' ``` Blocks come about every 2 seconds, so a healthy node shows about **20–35**. A number near **0** means it is not following the chain, even if the service is running. ### Troubleshooting [#troubleshooting] **The node does not start: `fork is not available: wchainv1…`** `genesis.json` is from v1.0.8 but the binary is older. Repeat Step 4 and check that `./w-chain-node version` says v1.0.8. **The node runs but commits no blocks** Check these in order: 1. Port **1478** is reachable from the internet (see [Check from outside](#check-from-outside)). Give it a minute after a restart. 2. `genesis.json` came from the **v1.0.8** release: `grep -c wchainv1 genesis.json` must print `4`. 3. `seal` is `true` and `./w-chain-node version` reports **v1.0.8**. 4. You completed **both** actions in Step 10. Check with `npm run cli isValidator `.