{"id":50841052,"url":"https://github.com/tetherto/miningos-tpl-wrk-electricity","last_synced_at":"2026-06-14T06:35:27.029Z","repository":{"id":344367329,"uuid":"1129676362","full_name":"tetherto/miningos-tpl-wrk-electricity","owner":"tetherto","description":null,"archived":false,"fork":false,"pushed_at":"2026-05-21T12:15:38.000Z","size":233,"stargazers_count":0,"open_issues_count":0,"forks_count":4,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-21T20:52:41.682Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tetherto.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-07T12:28:52.000Z","updated_at":"2026-05-21T12:15:44.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/tetherto/miningos-tpl-wrk-electricity","commit_stats":null,"previous_names":["tetherto/miningos-tpl-wrk-electricity"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/tetherto/miningos-tpl-wrk-electricity","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tetherto%2Fminingos-tpl-wrk-electricity","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tetherto%2Fminingos-tpl-wrk-electricity/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tetherto%2Fminingos-tpl-wrk-electricity/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tetherto%2Fminingos-tpl-wrk-electricity/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tetherto","download_url":"https://codeload.github.com/tetherto/miningos-tpl-wrk-electricity/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tetherto%2Fminingos-tpl-wrk-electricity/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34312072,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-14T02:00:07.365Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-14T06:35:22.056Z","updated_at":"2026-06-14T06:35:27.021Z","avatar_url":"https://github.com/tetherto.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# miningos-tpl-wrk-electricity\n\nTemplate worker for electricity monitoring, spot price forecasting, and mining profitability calculations in MiningOS.\n\n## Table of Contents\n\n1. [Overview](#overview)\n2. [Prerequisites](#prerequisites)\n3. [Installation](#installation)\n4. [Configuration](#configuration)\n5. [Starting the Worker](#starting-the-worker)\n6. [Architecture](#architecture)\n7. [API Reference](#api-reference)\n8. [Development](#development)\n9. [Troubleshooting](#troubleshooting)\n10. [Contributing](#contributing)\n\n## Overview\n\nThe Electricity Worker Template provides a foundation for building electricity monitoring workers that:\n- Track electricity costs and revenue for mining operations\n- Process spot price forecast data\n- Calculate mining profitability based on hashrate and power consumption\n- Store and retrieve historical energy data\n- Provide 24-hour uptime range calculations\n\nThis is a **template repository** - most methods are no-ops designed to be overridden in concrete implementations for specific electricity providers or data sources.\n\n## Prerequisites\n\n- Node.js \u003e= 20.0\n- Understanding of Hyperswarm RPC (for P2P communication)\n- Access to electricity data sources (for concrete implementations)\n\n## Installation\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/tetherto/miningos-tpl-wrk-electricity.git\ncd miningos-tpl-wrk-electricity\n```\n\n2. Install dependencies:\n```bash\nnpm install\n```\n\n3. Setup configuration files:\n```bash\nbash setup-config.sh\n# For test configurations as well:\nbash setup-config.sh --test\n```\n\n## Configuration\n\n### Common Configuration (config/common.json)\n\nBasic worker configuration:\n\n```json\n{\n  \"dir_log\": \"logs\",\n  \"debug\": 0\n}\n```\n\n### Network Configuration (config/facs/net.config.json)\nConfigure Hyperswarm network settings for RPC communication with other workers.\n\n### Storage Configuration (config/facs/store.config.json)\nConfigure Hyperbee database settings for persistent storage.\n\n**Note**: After running `setup-config.sh`, edit the generated config files with your specific settings.\n\n## Starting the Worker\n\n### Development Mode\n```bash\nnode worker.js --wtype wrk-electricity-rack --env development --rack rack-0\n```\n\n### Production Mode\n```bash\nnode worker.js --wtype wrk-electricity-rack --env production --rack rack-1\n```\n\n### Parameters\n- `--wtype`: Worker type identifier (e.g., `wrk-electricity-rack`)\n- `--env`: Environment (`development`, `production`)\n- `--rack`: Rack identifier (e.g., `rack-0`, `rack-1`)\n\n## Architecture\n\n### Core Components\n\n#### Worker Class: `WrkElectricityRack`\nMain worker class that extends `TetherWrkBase` from `tether-wrk-base`.\n\n**File**: `workers/rack.electricity.wrk.js`\n\nKey responsibilities:\n- Exposes RPC endpoints for electricity data retrieval\n- Manages worker settings persistence\n- Handles data queries via `getWrkExtData` method\n\n#### Settings Management\n**File**: `workers/lib/wrk-fun-settings.js`\n\nProvides:\n- `getSettings()` - Retrieve worker settings from Hyperbee storage\n- `saveSettingsEntries(entries)` - Update and persist settings\n\n### Data Storage\n\nUses **Hyperbee** (SQLite-backed key-value store) via `hp-svc-facs-store`:\n- Storage location: `store/${rack}-db`\n- Settings key: `settings_00`\n- Provides fast, persistent storage for worker configuration\n\n### RPC Communication\n\nWorkers communicate via Hyperswarm RPC:\n- Uses public keys for peer discovery\n- Exposes `getWrkExtData` method for data queries\n- Supports `getWrkSettings` and `saveWrkSettings` for configuration\n\n## API Reference\n\n### Primary RPC Method: `getWrkExtData`\n\nThe main endpoint for retrieving electricity data. All requests must include a `query` object with a `key` property.\n\n**Request Structure:**\n```javascript\n{\n  query: {\n    key: string,        // Required: determines operation\n    // Additional properties depend on key type\n  },\n  data?: any           // Optional: used for certain operations\n}\n```\n\n### Supported Query Keys\n\n#### 1. `margin`\nRetrieves the configured margin value for profitability calculations.\n\n**Payload:**\n```javascript\n{\n  query: { key: 'margin' }\n}\n```\n\n**Returns:** Number representing margin percentage or 0 if not configured.\n\n---\n\n#### 2. `revenue-estimates`\nRetrieves weekly revenue estimates from the database.\n\n**Payload:**\n```javascript\n{\n  query: {\n    key: 'revenue-estimates',\n    start: number,        // Unix timestamp (ms) - range start\n    end: number,          // Unix timestamp (ms) - range end\n    fields?: object       // Optional: projection fields\n  }\n}\n```\n\n**Returns:** Array of weekly revenue estimate objects.\n\n---\n\n#### 3. `spot-price`\nRetrieves spot price forecast data for a given time range.\n\n**Payload:**\n```javascript\n{\n  query: {\n    key: 'spot-price',\n    start: number,        // Unix timestamp (ms) - range start\n    end: number,          // Unix timestamp (ms) - range end\n    fields?: object       // Optional: projection fields\n  }\n}\n```\n\n**Returns:** Array of spot price forecast objects (timestamp, USD/MWh).\n\n---\n\n#### 4. `uptimeRange`\nCalculates 24-hour uptime range metrics based on provided data.\n\n**Payload:**\n```javascript\n{\n  query: { key: 'uptimeRange' },\n  data: any              // Required: uptime data to analyze\n}\n```\n\n**Returns:** Calculated 24-hour uptime range metrics.\n\n**Note:** This is the only fully implemented method in the template.\n\n---\n\n#### 6. `stats`\nRetrieves current electricity statistics.\n\n**Payload:**\n```javascript\n{\n  query: {\n    key: 'stats',\n    fields?: object       // Optional: projection fields\n  }\n}\n```\n\n**Returns:** Comprehensive stats object containing:\n- Active and reactive energy (1-hour and 15-minute intervals)\n- UTE energy data\n- Spot prices\n- Next hour energy values\n- Hashrate and consumption metrics\n\n---\n\n#### 7. `cost-revenue`\nRetrieves historical hourly cost and revenue data with optional aggregation.\n\n**Payload:**\n```javascript\n{\n  query: {\n    key: 'cost-revenue',\n    start: number,        // Unix timestamp (ms) - range start\n    end: number,          // Unix timestamp (ms) - range end\n    fields?: object,      // Optional: projection fields\n    aggrDaily?: boolean,  // Optional: aggregate by day\n    aggrHourly?: boolean  // Optional: aggregate by hour\n  }\n}\n```\n\n**Returns:** Array of cost-revenue objects (raw or aggregated).\n\n---\n\n#### 8. `stats-history`\nRetrieves aggregated historical statistics grouped by day or month.\n\n**Payload:**\n```javascript\n{\n  query: {\n    key: 'stats-history',\n    start: number,        // Unix timestamp (ms) - range start\n    end: number,          // Unix timestamp (ms) - range end\n    groupRange: string,   // Required: 'D1' (daily) or 'MONTH1' (monthly)\n    dataInterval: string, // Required: '15min' or '1h'\n    fields?: object       // Optional: projection fields\n  }\n}\n```\n\n**Returns:** Array of aggregated statistics containing:\n- Aggregated active and reactive energy values\n- Aggregated spot price (averaged)\n- Aggregated UTE energy\n- Timestamp and grouping label\n- Count of records aggregated\n\n---\n\n### Error Handling\n\nThe method throws errors for invalid inputs:\n- `ERR_QUERY_INVALID`: Missing or invalid query object\n- `ERR_KEY_INVALID`: Missing key property in query\n\n### Using the RPC CLI\n\nInteract with the worker using `hp-rpc-cli`:\n\n```bash\n# Get margin value\nhp-rpc-cli -s RPC_KEY \\\n  -m 'getWrkExtData' \\\n  -d '{\"query\": {\"key\": \"margin\"}}'\n\n# Get cost-revenue with daily aggregation\nhp-rpc-cli -s RPC_KEY \\\n  -m 'getWrkExtData' \\\n  -d '{\"query\": {\"key\": \"cost-revenue\", \"start\": 1697500800000, \"end\": 1697587200000, \"aggrDaily\": true}}'\n\n# Get stats history grouped by day\nhp-rpc-cli -s RPC_KEY \\\n  -m 'getWrkExtData' \\\n  -d '{\"query\": {\"key\": \"stats-history\", \"start\": 1697500800000, \"end\": 1700179200000, \"groupRange\": \"D1\", \"dataInterval\": \"1h\"}}'\n\n## Development\n\n### Running Tests\n```bash\nnpm test              # Run all tests (currently runs lint)\nnpm run lint          # Check code style (Standard.js)\nnpm run lint:fix      # Auto-fix linting issues\n```\n\n### Project Structure\n```\n.\n├── config/              # Configuration files\n│   ├── common.json.example\n│   └── facs/            # Facility configs (net, store, etc.)\n├── workers/\n│   ├── rack.electricity.wrk.js  # Main worker class\n│   └── lib/\n│       ├── wrk-fun-settings.js  # Settings persistence\n│       └── utils.js             # Utility functions\n├── mock/\n│   └── mock-control-agent.js    # Mock service for testing\n├── setup-config.sh      # Config file generator\n└── worker.js            # Entry point\n```\n\n### Implementing a Concrete Worker\n\nThis is a template - override the no-op methods in your implementation:\n\n1. Extend `WrkElectricityRack` class\n2. Implement the query methods:\n   - `getRevenueEstimates(req)`\n   - `getSpotPrice(req)`\n   - `calcCostAndRevenue(req)`\n   - `getStats(req)`\n   - `getCostRevenue(req)`\n   - `getStatsHistory(req)`\n3. Add your electricity data source integration\n4. Configure data polling/fetching schedules\n5. Add appropriate error handling and logging\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Configuration files missing**\n   - Run `bash setup-config.sh` to generate from templates\n   - Verify all `.example` files have been processed\n\n2. **Worker fails to start**\n   - Check that `--rack` parameter is provided\n   - Verify Node.js version \u003e= 16.0\n   - Review logs in `logs/` directory (if configured)\n\n3. **RPC connection failures**\n   - Verify network configuration in `config/facs/net.config.json`\n   - Check that Hyperswarm network is accessible\n   - Ensure RPC public keys are correct\n\n4. **Storage errors**\n   - Check `store/${rack}-db` directory exists and is writable\n   - Verify storage configuration in `config/facs/store.config.json`\n   - Ensure sufficient disk space\n\n5. **Methods returning undefined**\n   - Remember: most methods are no-ops in this template\n   - Implement concrete methods in your derived class\n   - Only `uptimeRange` is fully implemented\n\n## Contributing\n\nContributions are welcome and appreciated!\n\n### How to Contribute\n\n1. **Fork** the repository\n2. **Create a new branch** for your feature or fix:\n   ```bash\n   git checkout -b feature/your-feature-name\n   ```\n3. **Make your changes** and ensure tests pass:\n   ```bash\n   npm test\n   ```\n4. **Push** to your fork:\n   ```bash\n   git push origin feature/your-feature-name\n   ```\n5. **Open a Pull Request** describing what you changed and why\n\n### Guidelines\n\n- Follow Standard.js code style (`npm run lint`)\n- Add tests for new functionality\n- Keep PRs focused—one feature or fix per pull request\n- Update documentation as needed\n- Ensure all tests pass before submitting\n- Consider backward compatibility for template users\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftetherto%2Fminingos-tpl-wrk-electricity","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftetherto%2Fminingos-tpl-wrk-electricity","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftetherto%2Fminingos-tpl-wrk-electricity/lists"}