├── server ├── .eslintignore ├── .gitignore ├── jest.config.js ├── db │ └── .gitignore ├── src │ ├── helpers │ │ ├── index.js │ │ ├── api.js │ │ ├── config │ │ │ ├── validate.js │ │ │ ├── schema.js │ │ │ └── reader.js │ │ ├── DB.js │ │ ├── const.js │ │ ├── cron.js │ │ ├── log.js │ │ ├── notify.js │ │ ├── sync_db.js │ │ └── utils.js │ ├── modules │ │ ├── blocks_checker.js │ │ ├── block_parser.js │ │ ├── distribute_rewards.js │ │ ├── store.js │ │ └── pay_out.js │ ├── app.js │ └── server │ │ └── index.js ├── package.json ├── .eslintrc.cjs └── tests │ ├── helpers │ ├── cron.test.js │ └── DB.test.js │ └── modules │ ├── block_parser.test.js │ └── reward_distributor.test.js ├── web ├── .env.production ├── public │ ├── favicon.ico │ ├── icons │ │ ├── favicon.ico │ │ ├── favicon-128.png │ │ ├── mstile-70x70.png │ │ ├── offpool-favi.png │ │ ├── favicon-16x16.png │ │ ├── favicon-196x196.png │ │ ├── favicon-32x32.png │ │ ├── favicon-96x96.png │ │ ├── mstile-144x144.png │ │ ├── mstile-310x150.png │ │ ├── mstile-310x310.png │ │ ├── apple-touch-icon.png │ │ ├── android-chrome-36x36.png │ │ ├── android-chrome-48x48.png │ │ ├── android-chrome-72x72.png │ │ ├── android-chrome-96x96.png │ │ ├── android-chrome-144x144.png │ │ ├── android-chrome-192x192.png │ │ ├── android-chrome-256x256.png │ │ ├── android-chrome-384x384.png │ │ ├── android-chrome-512x512.png │ │ ├── apple-touch-icon-57x57.png │ │ ├── apple-touch-icon-60x60.png │ │ ├── apple-touch-icon-72x72.png │ │ ├── apple-touch-icon-76x76.png │ │ ├── android-chrome-1024x1024.png │ │ ├── apple-touch-icon-114x114.png │ │ ├── apple-touch-icon-120x120.png │ │ ├── apple-touch-icon-144x144.png │ │ ├── apple-touch-icon-152x152.png │ │ ├── apple-touch-icon-180x180.png │ │ ├── site.webmanifest │ │ ├── code.txt │ │ └── safari-pinned-tab.svg │ ├── mstile-150x150.png │ ├── browserconfig.xml │ └── manifest.json ├── src │ ├── assets │ │ └── logo.png │ ├── vite-env.d.ts │ ├── lib │ │ ├── icons │ │ │ ├── DotIcon.svelte │ │ │ ├── VoteIcon.svelte │ │ │ ├── TransactionIcon.svelte │ │ │ ├── GithubIcon.svelte │ │ │ └── UpdateIcon.svelte │ │ ├── Button.svelte │ │ ├── TheHeader.svelte │ │ ├── DashboardItem.svelte │ │ ├── TheFooter.svelte │ │ ├── Dashboard.svelte │ │ ├── TransactionTable.svelte │ │ └── VoterTable.svelte │ ├── main.js │ ├── api.js │ ├── utils.js │ ├── App.svelte │ └── app.css ├── vite.config.js ├── .gitignore ├── package.json ├── .eslintrc.cjs ├── jsconfig.json ├── windi.config.js └── index.html ├── scripts ├── start.sh ├── utils │ └── banner.js └── migrate.mjs ├── assets ├── logo.png └── logo-dark.png ├── .gitignore ├── commitlint.config.js ├── .husky ├── commit-msg └── pre-commit ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── CONTRIBUTING.md ├── package.json ├── config.default.jsonc ├── README.md └── LICENSE /server/.eslintignore: -------------------------------------------------------------------------------- 1 | ./config.json -------------------------------------------------------------------------------- /web/.env.production: -------------------------------------------------------------------------------- 1 | VITE_BASE_URL=/api -------------------------------------------------------------------------------- /scripts/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | npm run start 3 | -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | logs/ 2 | node_modules/ 3 | tests.js 4 | -------------------------------------------------------------------------------- /server/jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | transform: {}, 3 | }; 4 | -------------------------------------------------------------------------------- /assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/assets/logo.png -------------------------------------------------------------------------------- /assets/logo-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/assets/logo-dark.png -------------------------------------------------------------------------------- /web/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/favicon.ico -------------------------------------------------------------------------------- /web/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/src/assets/logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | config.test.jsonc 3 | config.json 4 | config.jsonc 5 | logs 6 | .vscode 7 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'] 3 | }; 4 | -------------------------------------------------------------------------------- /web/src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /server/db/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /web/public/icons/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon.ico -------------------------------------------------------------------------------- /web/public/mstile-150x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/mstile-150x150.png -------------------------------------------------------------------------------- /web/public/icons/favicon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon-128.png -------------------------------------------------------------------------------- /web/public/icons/mstile-70x70.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/mstile-70x70.png -------------------------------------------------------------------------------- /web/public/icons/offpool-favi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/offpool-favi.png -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no-install commitlint --edit 5 | -------------------------------------------------------------------------------- /web/public/icons/favicon-16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon-16x16.png -------------------------------------------------------------------------------- /web/public/icons/favicon-196x196.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon-196x196.png -------------------------------------------------------------------------------- /web/public/icons/favicon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon-32x32.png -------------------------------------------------------------------------------- /web/public/icons/favicon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/favicon-96x96.png -------------------------------------------------------------------------------- /web/public/icons/mstile-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/mstile-144x144.png -------------------------------------------------------------------------------- /web/public/icons/mstile-310x150.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/mstile-310x150.png -------------------------------------------------------------------------------- /web/public/icons/mstile-310x310.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/mstile-310x310.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-36x36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-36x36.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-48x48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-48x48.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-72x72.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-96x96.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-144x144.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-192x192.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-256x256.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-384x384.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-512x512.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-57x57.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-57x57.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-60x60.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-60x60.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-72x72.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-76x76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-76x76.png -------------------------------------------------------------------------------- /web/public/icons/android-chrome-1024x1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/android-chrome-1024x1024.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-114x114.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-114x114.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-120x120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-120x120.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-144x144.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-152x152.png -------------------------------------------------------------------------------- /web/public/icons/apple-touch-icon-180x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Adamant-im/pool/HEAD/web/public/icons/apple-touch-icon-180x180.png -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npm run --prefix ./web lint && npm run --prefix ./server lint 5 | -------------------------------------------------------------------------------- /web/src/lib/icons/DotIcon.svelte: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/src/main.js: -------------------------------------------------------------------------------- 1 | import './app.css'; 2 | import App from './App.svelte'; 3 | import 'virtual:windi.css'; 4 | 5 | const app = new App({ 6 | target: document.getElementById('app'), 7 | }); 8 | 9 | export default app; 10 | -------------------------------------------------------------------------------- /web/src/lib/icons/VoteIcon.svelte: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /server/src/helpers/index.js: -------------------------------------------------------------------------------- 1 | export {default as api} from './api.js'; 2 | export {default as log} from './log.js'; 3 | export {default as utils} from './utils.js'; 4 | export {default as notifier} from './notify.js'; 5 | export {default as config} from './config/reader.js'; 6 | -------------------------------------------------------------------------------- /web/vite.config.js: -------------------------------------------------------------------------------- 1 | import {defineConfig} from 'vite'; 2 | import {svelte} from '@sveltejs/vite-plugin-svelte'; 3 | import windiCSS from 'vite-plugin-windicss'; 4 | 5 | // https://vitejs.dev/config/ 6 | export default defineConfig({ 7 | plugins: [svelte(), windiCSS()], 8 | }); 9 | -------------------------------------------------------------------------------- /web/public/browserconfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | #da532c 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /web/src/lib/Button.svelte: -------------------------------------------------------------------------------- 1 |
17 | 18 |
-------------------------------------------------------------------------------- /server/src/helpers/api.js: -------------------------------------------------------------------------------- 1 | import adamantApi from 'adamant-api'; 2 | 3 | import config from './config/reader.js'; 4 | import log from './log.js'; 5 | 6 | const api = adamantApi({ 7 | node: config.node_ADM, 8 | logLevel: config.log_level, 9 | checkHealthAtStartup: process.env.NODE_ENV !== 'test', 10 | }, log); 11 | 12 | export default api; 13 | -------------------------------------------------------------------------------- /web/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | .env 15 | 16 | # Editor directories and files 17 | .vscode/* 18 | !.vscode/extensions.json 19 | .idea 20 | .DS_Store 21 | *.suo 22 | *.ntvs* 23 | *.njsproj 24 | *.sln 25 | *.sw? 26 | -------------------------------------------------------------------------------- /web/src/lib/icons/TransactionIcon.svelte: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/public/icons/site.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "", 3 | "short_name": "", 4 | "icons": [ 5 | { 6 | "src": "/android-chrome-192x192.png", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | }, 10 | { 11 | "src": "/android-chrome-512x512.png", 12 | "sizes": "512x512", 13 | "type": "image/png" 14 | } 15 | ], 16 | "theme_color": "#ffffff", 17 | "background_color": "#ffffff", 18 | "display": "standalone" 19 | } 20 | -------------------------------------------------------------------------------- /web/src/api.js: -------------------------------------------------------------------------------- 1 | const baseURL = import.meta.env.VITE_BASE_URL; 2 | 3 | export const request = (methodName) => { 4 | const controller = new AbortController(); 5 | 6 | const timeoutId = setTimeout(() => controller.abort(), 10000); 7 | 8 | const response = fetch(`${baseURL}/${methodName}`, { 9 | signal: controller.signal, 10 | }).then((res) => res.json()); 11 | 12 | clearTimeout(timeoutId); 13 | 14 | return response; 15 | }; 16 | 17 | export function getAll() { 18 | return Promise.all([ 19 | request('get-voters'), 20 | request('get-transactions'), 21 | request('get-delegate'), 22 | request('get-config'), 23 | ]); 24 | } 25 | -------------------------------------------------------------------------------- /web/src/lib/icons/GithubIcon.svelte: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "src/app.js", 3 | "type": "module", 4 | "scripts": { 5 | "start": "node src/app.js", 6 | "lint": "eslint .", 7 | "lint:fix": "eslint --fix .", 8 | "test": "NODE_OPTIONS=--experimental-vm-modules jest --detectOpenHandles --silent" 9 | }, 10 | "dependencies": { 11 | "adamant-api": "^1.8.0", 12 | "axios": "^1.2.2", 13 | "cors": "^2.8.5", 14 | "cron": "^2.2.0", 15 | "eslint-plugin-jest": "^27.2.1", 16 | "express": "^4.18.2", 17 | "jsonminify": "^0.4.2", 18 | "lowdb": "^5.0.5" 19 | }, 20 | "devDependencies": { 21 | "eslint": "^8.31.0", 22 | "eslint-config-google": "^0.14.0", 23 | "jest": "^29.3.1" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /web/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adamant-pool", 3 | "short_name": "adamant-pool", 4 | "icons": [ 5 | { 6 | "src": "/icons/android-chrome-192x192.png", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | }, 10 | { 11 | "src": "/icons/android-chrome-512x512.png", 12 | "sizes": "512x512", 13 | "type": "image/png" 14 | }, 15 | { 16 | "src": "/icons/apple-touch-icon-152x152.png", 17 | "sizes": "152x152", 18 | "type": "image/png" 19 | } 20 | ], 21 | "start_url": "icons/", 22 | "display": "standalone", 23 | "background_color": "#000000", 24 | "theme_color": "#4DBA87" 25 | } 26 | -------------------------------------------------------------------------------- /web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "type": "module", 4 | "scripts": { 5 | "dev": "vite", 6 | "lint": "npx eslint .", 7 | "build": "vite build", 8 | "preview": "vite preview" 9 | }, 10 | "devDependencies": { 11 | "@smui/button": "^6.1.4", 12 | "@smui/data-table": "^6.2.0", 13 | "@sveltejs/vite-plugin-svelte": "^2.0.2", 14 | "eslint": "^8.31.0", 15 | "eslint-config-google": "^0.14.0", 16 | "eslint-plugin-svelte3": "^4.0.0", 17 | "svelte": "^3.55.1", 18 | "vite": "^4.0.4", 19 | "vite-plugin-windicss": "^1.8.10", 20 | "windicss": "^3.5.6" 21 | }, 22 | "dependencies": { 23 | "svelte-material-ui": "^6.2.0" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /web/src/lib/icons/UpdateIcon.svelte: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /server/src/helpers/config/validate.js: -------------------------------------------------------------------------------- 1 | export default (config, schema) => { 2 | Object.keys(schema).forEach((fieldName) => { 3 | const configProperty = config[fieldName]; 4 | const field = schema[fieldName]; 5 | 6 | if (!configProperty && field.isRequired) { 7 | return `Pool's ${config.address} config is wrong. Field _${field}_ is not valid. Cannot start Pool.`; 8 | } else if (!configProperty && configProperty !== 0 && field.default) { 9 | config[fieldName] = field.default; 10 | } 11 | 12 | if (configProperty && field.type !== configProperty.__proto__.constructor) { 13 | return `Pool's ${config.address} config is wrong. Field type _${field}_ is not valid, expected type is _${field.type.name}_. Cannot start Pool.`; 14 | } 15 | }); 16 | }; 17 | -------------------------------------------------------------------------------- /server/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | commonjs: true, 4 | es2021: true, 5 | browser: true, 6 | node: true, 7 | 'jest/globals': true, 8 | }, 9 | extends: ['eslint:recommended', 'google'], 10 | plugins: ['jest'], 11 | parserOptions: { 12 | ecmaVersion: 'latest', 13 | sourceType: 'module', 14 | }, 15 | ignorePatterns: ['src/server/public/**/*.js'], 16 | rules: { 17 | 'max-len': [ 18 | 'error', 19 | { 20 | code: 200, 21 | ignoreTrailingComments: true, 22 | ignoreUrls: true, 23 | ignoreStrings: true, 24 | ignoreTemplateLiterals: true, 25 | ignoreRegExpLiterals: true, 26 | }, 27 | ], 28 | 'require-jsdoc': 'off', 29 | 'quote-props': 'off', 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /web/src/lib/TheHeader.svelte: -------------------------------------------------------------------------------- 1 | 8 | 9 |
10 |
11 |
12 | ADAMANT Logo 13 |
14 | ADAMANT Forging Pool 15 | 16 | {version} 17 | 18 |
19 |
20 | 21 | 22 | 23 | 24 |
25 |
26 | -------------------------------------------------------------------------------- /server/src/helpers/DB.js: -------------------------------------------------------------------------------- 1 | import {Low, MemorySync} from 'lowdb'; 2 | import {JSONFileSync} from 'lowdb/node'; 3 | 4 | import {join, dirname} from 'path'; 5 | import {fileURLToPath} from 'url'; 6 | 7 | import syncDB from './sync_db.js'; 8 | 9 | const __dirname = dirname(fileURLToPath(import.meta.url)); 10 | 11 | const createAdapter = (fileName) => ( 12 | process.env.NODE_ENV === 'test' ? 13 | new MemorySync() : 14 | new JSONFileSync( 15 | join(__dirname, `../../db/${fileName}.json`), 16 | ) 17 | ); 18 | 19 | export const dbTrans = syncDB(new Low( 20 | createAdapter('transactions'), 21 | )); 22 | 23 | export const dbBlocks = syncDB(new Low( 24 | createAdapter('blocks'), 25 | )); 26 | 27 | export const dbVoters = syncDB(new Low( 28 | createAdapter('voters'), 29 | ), 60 * 1000 * 60); 30 | -------------------------------------------------------------------------------- /web/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parserOptions: { 3 | ecmaVersion: 'latest', 4 | sourceType: 'module', 5 | }, 6 | env: { 7 | es2021: true, 8 | browser: true, 9 | }, 10 | extends: ['eslint:recommended', 'google'], 11 | plugins: [ 12 | 'svelte3', 13 | ], 14 | ignorePatterns: ['dist/**/*'], 15 | overrides: [ 16 | { 17 | files: ['src/*.svelte'], 18 | processor: 'svelte3/svelte3', 19 | }, 20 | ], 21 | rules: { 22 | 'max-len': [ 23 | 'error', 24 | { 25 | code: 200, 26 | ignoreTrailingComments: true, 27 | ignoreUrls: true, 28 | ignoreStrings: true, 29 | ignoreTemplateLiterals: true, 30 | ignoreRegExpLiterals: true, 31 | }, 32 | ], 33 | 'require-jsdoc': 'off', 34 | 'quote-props': 'off', 35 | }, 36 | }; 37 | -------------------------------------------------------------------------------- /web/src/lib/DashboardItem.svelte: -------------------------------------------------------------------------------- 1 | 6 | 7 |
8 |
9 | {name} 10 |
11 |
12 | {value} {isADM ? 'ADM': ''} 13 | 14 | {#if needAttention} 15 |
16 | 17 |
18 | {/if} 19 |
20 |
21 | 22 | 33 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adamant-pool", 3 | "version": "3.0.0", 4 | "description": "ADAMANT Forging Pool", 5 | "main": "server/src/app.js", 6 | "scripts": { 7 | "start": "node .", 8 | "prepare": "husky install", 9 | "postinstall": "npm --prefix ./server install && npm --prefix ./web install", 10 | "build:web": "npm --prefix ./web run build" 11 | }, 12 | "keywords": [ 13 | "forging", 14 | "pool", 15 | "mining", 16 | "rewards", 17 | "dpos", 18 | "adm", 19 | "adamant", 20 | "blockchain", 21 | "crypto", 22 | "cryptocurrency" 23 | ], 24 | "author": "ADAMANT Tech Labs ", 25 | "license": "GPL-3.0", 26 | "devDependencies": { 27 | "@commitlint/cli": "^17.4.2", 28 | "@commitlint/config-conventional": "^17.4.2", 29 | "husky": "^8.0.3" 30 | }, 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/Adamant-im/pool.git" 34 | }, 35 | "bugs": { 36 | "url": "https://github.com/Adamant-im/pool/issues" 37 | }, 38 | "homepage": "https://github.com/Adamant-im/pool#readme" 39 | } 40 | -------------------------------------------------------------------------------- /server/src/modules/blocks_checker.js: -------------------------------------------------------------------------------- 1 | import BlockParser from './block_parser.js'; 2 | 3 | import {api, config, log} from '../helpers/index.js'; 4 | import {UPDATE_BLOCKS_INTERVAL} from '../helpers/const.js'; 5 | 6 | const blockParser = new BlockParser(); 7 | 8 | async function getBlocks() { 9 | try { 10 | // FIX ME: use generatorPublicKey parameter instead of filtering 11 | const blocks = await api.get('blocks', {limit: 100}); 12 | 13 | if (blocks.success) { 14 | const delegateBlocks = blocks.data.blocks.filter( 15 | (block) => block.generatorPublicKey === config.publicKey, 16 | ); 17 | 18 | delegateBlocks.forEach((block) => blockParser.enqueue(block)); 19 | 20 | blockParser.run(); 21 | } else { 22 | log.warn(`Failed to get blocks. ${blocks.errorMessage}.`); 23 | } 24 | } catch (error) { 25 | log.error(`Error while checking new blocks: ${error}`); 26 | } 27 | } 28 | 29 | export default () => { 30 | getBlocks(); 31 | if (process.env.NODE_ENV !== 'test') { 32 | setInterval(getBlocks, UPDATE_BLOCKS_INTERVAL); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /web/src/lib/TheFooter.svelte: -------------------------------------------------------------------------------- 1 | 25 | 26 | 38 | -------------------------------------------------------------------------------- /server/src/helpers/config/schema.js: -------------------------------------------------------------------------------- 1 | export default { 2 | passPhrase: { 3 | type: String, 4 | isRequired: true, 5 | }, 6 | node_ADM: { 7 | type: Array, 8 | isRequired: true, 9 | }, 10 | reward_percentage: { 11 | type: Number, 12 | default: 80, 13 | }, 14 | donate_percentage: { 15 | type: Number, 16 | default: 0, 17 | }, 18 | minpayout: { 19 | type: Number, 20 | default: 10, 21 | }, 22 | port: { 23 | type: Number, 24 | default: 36667, 25 | }, 26 | payoutperiod: { 27 | type: String, 28 | default: '10d', 29 | }, 30 | maintenancewallet: { 31 | type: String, 32 | default: '', 33 | }, 34 | donatewallet: { 35 | type: String, 36 | default: '', 37 | }, 38 | considerownvote: { 39 | type: Boolean, 40 | default: false, 41 | }, 42 | adamant_notify: { 43 | type: String, 44 | default: null, 45 | }, 46 | slack: { 47 | type: String, 48 | default: null, 49 | }, 50 | log_level: { 51 | type: String, 52 | default: 'log', 53 | }, 54 | silent_mode: { 55 | type: Boolean, 56 | default: false, 57 | }, 58 | }; 59 | -------------------------------------------------------------------------------- /scripts/utils/banner.js: -------------------------------------------------------------------------------- 1 | // Generated by the following code: 2 | // 3 | // require('gradient-string').cristal('ADAMANT Pool Migration Script') 4 | // 5 | // Use the output directly here to keep the bundle small. 6 | 7 | const banner = '\u001b[38;2;189;255;243mA\u001b[39m\u001b[38;2;184;253;239mD\u001b[39m\u001b[38;2;180;250;236mA\u001b[39m\u001b[38;2;175;248;232mM\u001b[39m\u001b[38;2;171;245;229mA\u001b[39m\u001b[38;2;166;243;225mN\u001b[39m\u001b[38;2;161;240;222mT\u001b[39m \u001b[38;2;157;238;218mP\u001b[39m\u001b[38;2;152;235;215mo\u001b[39m\u001b[38;2;148;233;211mo\u001b[39m\u001b[38;2;143;231;207ml\u001b[39m \u001b[38;2;138;228;204mM\u001b[39m\u001b[38;2;134;226;200mi\u001b[39m\u001b[38;2;129;223;197mg\u001b[39m\u001b[38;2;125;221;193mr\u001b[39m\u001b[38;2;120;218;190ma\u001b[39m\u001b[38;2;115;216;186mt\u001b[39m\u001b[38;2;111;214;182mi\u001b[39m\u001b[38;2;106;211;179mo\u001b[39m\u001b[38;2;102;209;175mn\u001b[39m \u001b[38;2;97;206;172mS\u001b[39m\u001b[38;2;92;204;168mc\u001b[39m\u001b[38;2;88;201;165mr\u001b[39m\u001b[38;2;83;199;161mi\u001b[39m\u001b[38;2;79;196;158mp\u001b[39m\u001b[38;2;74;194;154mt\u001b[39m'; 8 | 9 | console.log(banner); 10 | -------------------------------------------------------------------------------- /web/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "Node", 4 | "target": "ESNext", 5 | "module": "ESNext", 6 | /** 7 | * svelte-preprocess cannot figure out whether you have 8 | * a value or a type, so tell TypeScript to enforce using 9 | * `import type` instead of `import` for Types. 10 | */ 11 | "importsNotUsedAsValues": "error", 12 | "isolatedModules": true, 13 | "resolveJsonModule": true, 14 | /** 15 | * To have warnings / errors of the Svelte compiler at the 16 | * correct position, enable source maps by default. 17 | */ 18 | "sourceMap": true, 19 | "esModuleInterop": true, 20 | "skipLibCheck": true, 21 | "forceConsistentCasingInFileNames": true, 22 | "baseUrl": ".", 23 | /** 24 | * Typecheck JS in `.svelte` and `.js` files by default. 25 | * Disable this if you'd like to use dynamic types. 26 | */ 27 | "checkJs": true 28 | }, 29 | /** 30 | * Use global.d.ts instead of compilerOptions.types 31 | * to avoid limiting type declarations. 32 | */ 33 | "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"] 34 | } 35 | -------------------------------------------------------------------------------- /server/src/helpers/const.js: -------------------------------------------------------------------------------- 1 | export const UPDATE_BLOCKS_INTERVAL = 60 * 1000; // get new blocks every minute 2 | export const UPDATE_DELEGATE_INTERVAL = 3 * 60 * 1000; // update delegate info; balance and voters every 3 minutes 3 | export const RETRY_WHEN_UPDATING_VOTERS_TIMEOUT = 10 * 1000; // if a pool is updating voters; postpone distributing rewards for 10 seconds 4 | export const RETRY_PAYOUTS_TIMEOUT = 10 * 60 * 1000; // if not all of payouts processed; re-try in 10 minutes. Next re-try it will be RETRY_PAYOUTS_TIMEOUT * retryNo 5 | export const RETRY_PAYOUTS_COUNT = 3; // re-tries for payouts. Total tries RETRY_PAYOUTS_COUNT + 1; 6 | export const UPDATE_AFTER_PAYMENT_DELAY = 60 * 1000; // Wait 1 minute to update pool's balance and notify 7 | export const SAT = 100000000; // 1 ADM = 100000000 8 | export const DEVIATION = 100000; // consider balance is zero when it is lower; then 0.001 ADM 9 | export const FEE = 0.5; // Transfer (Type 0) Tx fee; 10 | export const MIN_PAYOUT = 0.51; // check minpayout in config to be not less; than 0.51 ADM; 11 | export const EPOCH = Date.UTC(2017, 8, 2, 17, 0, 0, 0); // ADAMANT's epoch time 12 | export const FORMAT_PAYOUT ='yyyy-MM-dd'; 13 | -------------------------------------------------------------------------------- /server/src/helpers/cron.js: -------------------------------------------------------------------------------- 1 | import cron from 'cron'; 2 | import Payer from '../modules/pay_out.js'; 3 | import config from './config/reader.js'; 4 | import log from './log.js'; 5 | 6 | const payer = new Payer(); 7 | 8 | // sec(optional) min(0-59) hours(0-23) d_mon(1-31) mon(1-12/names) d_week(0-7/names) 9 | const patterns = { 10 | '1h': '0 * * * *', 11 | '1d': '0 0 * * *', 12 | '5d': '0 0 */5 * *', 13 | '10d': '0 0 */10 * *', 14 | '15d': '0 0 */15 * *', 15 | '30d': '0 0 1 * *', 16 | }; 17 | 18 | const daysOfTheWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; 19 | 20 | export default { 21 | payoutCronJob: {}, 22 | initCron(payoutperiod) { 23 | let pattern; 24 | 25 | if (daysOfTheWeek.includes(payoutperiod)) { 26 | pattern = `0 0 * * ${payoutperiod}`; 27 | } else { 28 | pattern = patterns[payoutperiod]; 29 | } 30 | 31 | if (!pattern) { 32 | return exit(); 33 | } 34 | 35 | try { 36 | const payoutCronJob = new cron.CronJob(pattern, payer.payOut.bind(payer)); 37 | 38 | payoutCronJob.start(); 39 | 40 | this.payoutCronJob = payoutCronJob; 41 | } catch (e) { 42 | return exit(e); 43 | } 44 | }, 45 | }; 46 | 47 | function exit(additionalInfo) { 48 | log.error( 49 | `Pool's ${config.address} config is wrong. Failed to validate payoutperiod: `+ 50 | `${config.payoutperiod}${additionalInfo ? ', ' + additionalInfo : ''}. Cannot start Pool.`, 51 | ); 52 | 53 | return -1; 54 | } 55 | -------------------------------------------------------------------------------- /server/src/app.js: -------------------------------------------------------------------------------- 1 | import store from './modules/store.js'; 2 | import blocksChecker from './modules/blocks_checker.js'; 3 | 4 | import {notifier, config, log, api} from './helpers/index.js'; 5 | import cron from './helpers/cron.js'; 6 | 7 | import server from './server/index.js'; 8 | 9 | log.start(); 10 | 11 | const cronStatusCode = cron.initCron(config.payoutperiod); 12 | 13 | if (cronStatusCode === -1) { 14 | process.exit(-1); 15 | } 16 | 17 | server.listen(config.port, () => ( 18 | log.log(`Pool ${config.address} successfully started a web server.`) 19 | )); 20 | 21 | // Wait for first API health check 22 | api.setStartupCallback(async () => { 23 | await initDelegate(); 24 | 25 | blocksChecker(); 26 | }); 27 | 28 | async function initDelegate() { 29 | const pool = await store.updateDelegate(); 30 | 31 | if (pool) { 32 | config.poolName = pool.username; 33 | } else { 34 | log.error(`Failed to get delegate for ${config.address}. Cannot start Pool.`); 35 | process.exit(-1); 36 | } 37 | 38 | config.logName = `_${config.poolName}_ (${config.address})`; 39 | config.infoString = `distributes _${config.reward_percentage}_% rewards to voters` + 40 | `${config.donate_percentage ? ' and donates ' + config.donate_percentage + '% to ADAMANT Foundation' : ''} ` + 41 | `with payouts every _${config.payoutperiod}_. Minimum payout is _${config.minpayout}_ ADM.`; 42 | 43 | notifier( 44 | `Pool ${config.logName} started on v${config.version} software and listens port ${config.port}. It ${config.infoString}`, 45 | 'info', 46 | ); 47 | 48 | store.updateAll(); 49 | } 50 | -------------------------------------------------------------------------------- /server/src/helpers/log.js: -------------------------------------------------------------------------------- 1 | import config from './config/reader.js'; 2 | import utils from './utils.js'; 3 | 4 | import fs from 'fs'; 5 | 6 | if (!fs.existsSync('./logs')) { 7 | fs.mkdirSync('./logs'); 8 | } 9 | 10 | const infoStr = fs.createWriteStream(`./logs/${date()}.log`, { 11 | flags: 'a', 12 | }); 13 | 14 | export default { 15 | start() { 16 | infoStr.write(`\n\n[The pool started] _________________${fullTime()}_________________\n`); 17 | }, 18 | error(str) { 19 | if (['error', 'warn', 'info', 'log'].includes(config.log_level)) { 20 | infoStr.write(`\n ` + 'error|' + fullTime() + '|' + str); 21 | console.log('\x1b[31m', 'error|' + fullTime(), '\x1b[0m', str); 22 | } 23 | }, 24 | warn(str) { 25 | if (['warn', 'info', 'log'].includes(config.log_level)) { 26 | console.log('\x1b[33m', 'warn|' + fullTime(), '\x1b[0m', str); 27 | infoStr.write(`\n ` + 'warn|' + fullTime() + '|' + str); 28 | } 29 | }, 30 | info(str) { 31 | if (['info', 'log'].includes(config.log_level)) { 32 | console.log('\x1b[32m', 'info|' + fullTime(), '\x1b[0m', str); 33 | infoStr.write(`\n ` + 'info|' + fullTime() + '|' + str); 34 | } 35 | }, 36 | log(str) { 37 | if (['log'].includes(config.log_level)) { 38 | console.log('\x1b[34m', 'log|' + fullTime(), '\x1b[0m', str); 39 | infoStr.write(`\n ` + 'log|[' + fullTime() + '|' + str); 40 | } 41 | }, 42 | }; 43 | 44 | function time() { 45 | return utils.formatDate(Date.now()).hh_mm_ss; 46 | } 47 | 48 | function date() { 49 | return utils.formatDate(Date.now()).YYYY_MM_DD; 50 | } 51 | 52 | function fullTime() { 53 | return date() + ' ' + time(); 54 | } 55 | -------------------------------------------------------------------------------- /server/src/server/index.js: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import cors from 'cors'; 3 | 4 | import {dirname, join} from 'path'; 5 | import {fileURLToPath} from 'url'; 6 | 7 | import store from '../modules/store.js'; 8 | 9 | import {dbVoters, dbTrans} from '../helpers/DB.js'; 10 | import config from '../helpers/config/reader.js'; 11 | 12 | const __dirname = dirname(fileURLToPath(import.meta.url)); 13 | 14 | const publicDir = join(__dirname, '../../../web/dist/'); 15 | 16 | const app = express(); 17 | 18 | app.use(cors()); 19 | 20 | app.use('*.js', (req, res, next) => { 21 | res.set('Content-Type', 'text/javascript'); 22 | next(); 23 | }); 24 | 25 | app.use('/', express.static(publicDir)); 26 | 27 | app.get('/', (req, res) => res.sendFile(join(publicDir, 'index.html'))); 28 | 29 | app.get('/api/get-transactions', async (req, res) => { 30 | const transactions = await dbTrans.find({}); 31 | 32 | return res.send(transactions); 33 | }); 34 | 35 | app.get('/api/get-voters', async (req, res) => { 36 | const voters = await dbVoters.find({}); 37 | 38 | return res.send(voters); 39 | }); 40 | 41 | app.get('/api/get-delegate', async (req, res) => res.send(store)); 42 | 43 | app.get('/api/get-config', async (req, res) => res.send({ 44 | version: config.version, 45 | reward_percentage: config.reward_percentage, 46 | donate_percentage: config.donate_percentage, 47 | minpayout: config.minpayout, 48 | payoutperiod: config.payoutperiod, 49 | payoutperiodForged: store.periodInfo.totalForgedADM, 50 | payoutperiodRewards: store.delegate.pendingRewardsADM, 51 | payoutperiodPreviousRunTimestamp: store.periodInfo.previousRunTimestamp, 52 | payoutperiodNextRunTimestamp: store.periodInfo.nextRunTimestamp, 53 | })); 54 | 55 | export default app; 56 | -------------------------------------------------------------------------------- /server/tests/helpers/cron.test.js: -------------------------------------------------------------------------------- 1 | import cron from '../../src/helpers/cron.js'; 2 | import utils from '../../src/helpers/utils.js'; 3 | 4 | describe('Initializing a cron using the day of the week', () => { 5 | afterEach(() => cron.payoutCronJob.stop()); 6 | 7 | const daysOfTheWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; 8 | 9 | test.each(daysOfTheWeek)('should call a cron job with correct pattern', (day) => { 10 | const cronResponseCode = cron.initCron(day); 11 | 12 | expect(cronResponseCode).not.toBe(-1); 13 | expect(cron.payoutCronJob.cronTime.source).toBe(`0 0 * * ${day}`); 14 | }); 15 | }); 16 | 17 | describe('Initializing a cron using a pattern', () => { 18 | afterEach(() => cron.payoutCronJob.stop()); 19 | 20 | const patternTable = [ 21 | ['1h', '0 * * * *'], 22 | ['1d', '0 0 * * *'], 23 | ['5d', '0 0 */5 * *'], 24 | ['10d', '0 0 */10 * *'], 25 | ['15d', '0 0 */15 * *'], 26 | ['30d', '0 0 1 * *'], 27 | ]; 28 | 29 | test.each(patternTable)('should init a cron with correct pattern based on the period', (period, pattern) => { 30 | const cronResponseCode = cron.initCron(period); 31 | 32 | expect(cronResponseCode).not.toBe(-1); 33 | expect(cron.payoutCronJob.cronTime.source).toBe(pattern); 34 | }); 35 | }); 36 | 37 | describe('Invalid period', () => { 38 | beforeAll(() => cron.payoutCronJob = {}); 39 | 40 | const invalidPeriods = [ 41 | '32d', 42 | '2h', 43 | 'Sar', 44 | '', 45 | null, 46 | ]; 47 | 48 | test.each(invalidPeriods)('should return -1', (period) => { 49 | const cronResponseCode = cron.initCron(period); 50 | 51 | expect(cronResponseCode).toBe(-1); 52 | expect(utils.isPlainObject(cron.payoutCronJob)).toBeTruthy(); 53 | }); 54 | }); 55 | -------------------------------------------------------------------------------- /scripts/migrate.mjs: -------------------------------------------------------------------------------- 1 | import './utils/banner.js'; 2 | 3 | import * as readline from 'node:readline'; 4 | import { existsSync, createReadStream } from 'node:fs'; 5 | 6 | import path from 'node:path'; 7 | 8 | import { 9 | dbTrans, 10 | dbBlocks, 11 | dbVoters 12 | } from '../server/src/helpers/DB.js'; 13 | 14 | let [,, targetPath] = process.argv; 15 | 16 | if (!targetPath) { 17 | console.error('❌ No target database or pool path specified'); 18 | process.exit(0); 19 | } 20 | 21 | const dbPath = path.join(targetPath, 'db'); 22 | 23 | if (existsSync(dbPath)) { 24 | targetPath = dbPath; 25 | } 26 | 27 | console.log(`🔍️ Searching inside "${targetPath}" for DB files to migrate...`); 28 | 29 | const dbFiles = [ 30 | { 31 | fileName: 'blocks', 32 | dbApi: dbBlocks, 33 | uniqueKey: 'id' 34 | }, 35 | { 36 | fileName: 'transactions', 37 | dbApi: dbTrans, 38 | uniqueKey: 'transactionId' 39 | }, 40 | { 41 | fileName: 'voters', 42 | dbApi: dbVoters, 43 | uniqueKey: 'address' 44 | } 45 | ]; 46 | 47 | for (const {fileName, dbApi, uniqueKey} of dbFiles) { 48 | const filePath = path.join(targetPath, fileName); 49 | 50 | if (!existsSync(filePath)) { 51 | console.warn(`⚠️ The filename "${fileName}" doesn't exist in specified path, skipping.`); 52 | continue; 53 | } 54 | 55 | const input = createReadStream(filePath, { encoding: 'utf-8' }); 56 | 57 | const rl = readline.createInterface({ 58 | input, 59 | crlfDelay: Infinity 60 | }); 61 | 62 | for await (const line of rl) { 63 | if (!line.trim()) { 64 | continue; 65 | } 66 | 67 | const valueToMigrate = JSON.parse(line); 68 | 69 | const savedValue = await dbApi.findOne({ 70 | [uniqueKey]: valueToMigrate[uniqueKey] 71 | }); 72 | 73 | if (savedValue) { 74 | console.log(`⚪️ Value with "${valueToMigrate[uniqueKey]}" ${uniqueKey} already exists in ${fileName}, skipping.`); 75 | continue; 76 | } 77 | 78 | await dbApi.insert(valueToMigrate); 79 | } 80 | 81 | rl.close(); 82 | } 83 | 84 | console.log('✅ The database successfully migrated.'); 85 | 86 | process.exit(0); 87 | -------------------------------------------------------------------------------- /web/src/lib/Dashboard.svelte: -------------------------------------------------------------------------------- 1 | 66 | 67 |
68 |
69 | {#each items as item (item.name)} 70 | 75 | {/each} 76 |
77 |
78 | {#each smallItems as item (item.name)} 79 | 86 | {/each} 87 |
88 |
89 | -------------------------------------------------------------------------------- /web/public/icons/code.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /web/windi.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | shortcuts: { 3 | center: 'flex justify-center items-center', 4 | }, 5 | theme: { 6 | colors: { 7 | 'primary': '#0c8ce9', 8 | 'transparent': 'transparent', 9 | 'primary-disable': '#DD96FF', 10 | 'primary-light': '#D170FF', 11 | 'primary-dark': '#D170FF', 12 | 'secondary': '#EBEBF0', 13 | 'secondary-dark': '#575a62', 14 | 'light': '#ffffff', 15 | 'light-300': '#d1d1d1', 16 | 'yellow': '#fcd34d', 17 | 'yellow-500': '#f9c830', 18 | 'yellow-600': '#d78215', 19 | 'green': '#29d23b', 20 | 'black': '#000', 21 | 'red': '#bf3939', 22 | 'red-light': '#bf3989', 23 | }, 24 | borderColor: (theme) => ({ 25 | ...theme('colors'), 26 | 'secondary': '#F2F1F6', 27 | }), 28 | textColor: (theme) => ({ 29 | ...theme('colors'), 30 | 'secondary': '#b8b8b8', 31 | 'primary-green': '#178736', 32 | }), 33 | placeholderColor: (theme) => ({ 34 | ...theme('textColor'), 35 | secondary: '#828793', 36 | }), 37 | backgroundColor: (theme) => ({ 38 | ...theme('colors'), 39 | 'default': '#fff', 40 | 'secondary': 'rgb(213,215,219)', 41 | 'secondary-dark': '#424242', 42 | 'primary': { 43 | 100: '#fcfcff', 44 | 200: '#fafaff', 45 | 500: '#0c8ce9', 46 | }, 47 | 'light': { 48 | 100: '#f9f9f9', 49 | 300: '#fdfdfd', 50 | 400: '#fafafa', 51 | 200: '#F9FBFC', 52 | 500: 'rgb(240, 240, 240)', 53 | }, 54 | }), 55 | boxShadow: (theme) => ({ 56 | 'sm': '0 1px 2px 0 rgba(0, 0, 0, 0.05)', 57 | 'DEFAULT': '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)', 58 | 'md': '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)', 59 | 'lg': '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)', 60 | 'xl': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)', 61 | '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)', 62 | '3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)', 63 | 'outline': `inset 0px 0px 0px 1px ${theme('colors').primary}`, 64 | 'outline-error': `inset 0px 0px 0px 1px ${theme('colors').red}`, 65 | 'none': 'none', 66 | }), 67 | }, 68 | }; 69 | -------------------------------------------------------------------------------- /server/src/helpers/notify.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | import api from './api.js'; 4 | import log from './log.js'; 5 | import config from './config/reader.js'; 6 | 7 | const { 8 | adamant_notify: adamantNotify, 9 | slack, 10 | } = config; 11 | 12 | export default (message, type, silentMode = false) => { 13 | try { 14 | log[type](removeMarkdown(message)); 15 | 16 | if (!silentMode) { 17 | if (!slack && !adamantNotify) { 18 | return; 19 | } 20 | 21 | const colors = { 22 | error: '#FF0000', 23 | warn: '#FFFF00', 24 | info: '#00FF00', 25 | log: '#FFFFFF', 26 | }; 27 | 28 | const color = colors[type]; 29 | 30 | const params = { 31 | 'attachments': [{ 32 | 'fallback': message, 33 | 'color': color, 34 | 'text': makeBoldForSlack(message), 35 | 'mrkdwn_in': ['text'], 36 | }], 37 | }; 38 | 39 | if (slack && slack.length > 34) { 40 | axios.post(slack, params) 41 | .catch((error) => { 42 | log.log(`Request to Slack with message ${message} failed. ${error}.`); 43 | }); 44 | } 45 | 46 | if (adamantNotify && adamantNotify.length > 5 && adamantNotify.startsWith('U') && config.passPhrase && config.passPhrase.length > 30) { 47 | const mdMessage = makeBoldForMarkdown(message); 48 | 49 | api.sendMessage(config.passPhrase, adamantNotify, `${type}| ${mdMessage}`) 50 | .then((response) => { 51 | if (!response.success) { 52 | log.warn(`Failed to send notification messsage '${mdMessage}' to ${adamantNotify}. ${response.errorMessage}.`); 53 | } 54 | }); 55 | } 56 | } 57 | } catch (e) { 58 | log.error('Notifier error: ' + e); 59 | } 60 | }; 61 | 62 | function removeMarkdown(text) { 63 | return doubleAsterisksToSingle(text).replace(/([_*]\b|\b[_*])/g, ''); 64 | } 65 | 66 | function doubleAsterisksToSingle(text) { 67 | return text.replace(/(\*\*\b|\b\*\*)/g, '*'); 68 | } 69 | 70 | function singleAsteriskToDouble(text) { 71 | return text.replace(/(\*\b|\b\*)/g, '**'); 72 | } 73 | 74 | function makeBoldForMarkdown(text) { 75 | return singleAsteriskToDouble(doubleAsterisksToSingle(text)); 76 | } 77 | 78 | function makeBoldForSlack(text) { 79 | return doubleAsterisksToSingle(text); 80 | } 81 | -------------------------------------------------------------------------------- /config.default.jsonc: -------------------------------------------------------------------------------- 1 | { 2 | /** 3 | List of nodes to fetch forging information. 4 | If one become unavailable, a pool will choose live one. 5 | **/ 6 | "node_ADM": [ 7 | "https://bid.adamant.im", 8 | "http://localhost:36666", 9 | "https://endless.adamant.im", 10 | "https://clown.adamant.im", 11 | "https://unusual.adamant.im", 12 | "https://debate.adamant.im", 13 | "http://23.226.231.225:36666", 14 | "http://78.47.205.206:36666", 15 | "https://lake.adamant.im", 16 | "https://sunshine.adamant.im" 17 | ], 18 | 19 | /** 20 | The pool's secret phrase. Pool's ADM address/account will correspond this passPhrase. 21 | The account should be a delegate of the ADAMANT blockchain. 22 | **/ 23 | "passPhrase": "", 24 | 25 | /** Percentage of rewards to distribute to voters **/ 26 | "reward_percentage": 80, 27 | 28 | /** Percentage of rewards to donate to the ADAMANT Foundation **/ 29 | "donate_percentage": 0, 30 | 31 | /** 32 | Wallet for donation. 33 | Make sure it's the same as on https://adamant.im/donate 34 | **/ 35 | "donatewallet": "U380651761819723095", 36 | 37 | /** 38 | Maintenance wallet to receive (100 - reward_percentage - donate_percentage) rewards. 39 | If you wish to leave it on the pool's wallet, set to empty string. 40 | **/ 41 | "maintenancewallet": "", 42 | 43 | /** 44 | How often the pool will do payouts. All at 00:00. 45 | 1d -> every day 46 | 5d -> days 1, 5, 10, 15, 20, 25 of the month 47 | 10d -> days 1, 10, 20 of the month 48 | 15d -> days 1, 15 of the month 49 | 30d -> 30th of each month 50 | Mon, Tue, Wed, Thu, Fri, Sat or Sun -> every week 51 | **/ 52 | "payoutperiod": "Sun", 53 | 54 | /** 55 | Minimum amount in ADM for a payout. Must be not less, than 0.51. 56 | If at the end of a payoutperiod a voter's reward is less than minpayout, it will be pending for the next period. 57 | Voter pays a transaction fee. 58 | **/ 59 | "minpayout": 10, 60 | 61 | /** If delegate can vote for himself and this will account in reward distribution **/ 62 | "considerownvote": false, 63 | 64 | /** ADAMANT address for monitoring notifications **/ 65 | "adamant_notify": "", 66 | 67 | /** Slack key for monitoring notifications **/ 68 | "slack": "", 69 | 70 | /** 71 | The software will use verbosity according to log_level. 72 | It can be none < error < warn < info < log. 73 | **/ 74 | "log_level": "log", 75 | 76 | /** Port for pool's public Web panel **/ 77 | "port": 36667 78 | } 79 | -------------------------------------------------------------------------------- /server/tests/modules/block_parser.test.js: -------------------------------------------------------------------------------- 1 | import {jest} from '@jest/globals'; 2 | import {dbBlocks} from '../../src/helpers/DB.js'; 3 | 4 | const mockDistribute = jest.fn(); 5 | 6 | jest.unstable_mockModule('../../src/modules/distribute_rewards.js', () => ({ 7 | __esModule: true, 8 | default: jest.fn().mockImplementation(() => { 9 | return {distribute: mockDistribute}; 10 | }), 11 | })); 12 | 13 | const BlockParser = (await import('../../src/modules/block_parser.js')).default; 14 | const RewardDistributor = (await import('../../src/modules/distribute_rewards.js')).default; 15 | 16 | beforeEach(() => { 17 | RewardDistributor.mockClear(); 18 | mockDistribute.mockClear(); 19 | }); 20 | 21 | describe('BlockParser', () => { 22 | const blockParser = new BlockParser(); 23 | 24 | it('should enqueue all blocks', () => { 25 | for (let id = 0; id < 3; id += 1) { 26 | blockParser.enqueue({id}); 27 | } 28 | 29 | expect(blockParser.length).toBe(3); 30 | expect(blockParser.head.value.id).toBe(0); 31 | expect(blockParser.tail.value.id).toBe(2); 32 | }); 33 | 34 | it('should dequeue a block', () => { 35 | const headNode = blockParser.dequeue(); 36 | 37 | expect(headNode.id).toBe(0); 38 | expect(blockParser.length).toBe(2); 39 | expect(blockParser.head.value.id).toBe(1); 40 | expect(blockParser.tail.value.id).toBe(2); 41 | }); 42 | }); 43 | 44 | describe('blockParser.parse', () => { 45 | beforeEach(() => { 46 | dbBlocks.data = {values: []}; 47 | return dbBlocks.write(); 48 | }); 49 | 50 | const blockParser = new BlockParser(); 51 | const id = 1; 52 | 53 | it('should not distribute rewards for processed block', async () => { 54 | await dbBlocks.insert({id, processed: true}); 55 | 56 | await blockParser.parse({id}); 57 | 58 | expect(RewardDistributor).toHaveBeenCalledTimes(1); 59 | expect(mockDistribute).toHaveBeenCalledTimes(0); 60 | }); 61 | 62 | it('should distribute rewards for not processed block', async () => { 63 | await dbBlocks.insert({id}); 64 | 65 | await blockParser.parse({id}); 66 | 67 | expect(RewardDistributor).toHaveBeenCalledTimes(1); 68 | expect(mockDistribute).toHaveBeenCalledTimes(1); 69 | }); 70 | 71 | it('should save new block to DB and distribute', async () => { 72 | const savedBlockBeforeParsing = await dbBlocks.findOne({id}); 73 | 74 | await blockParser.parse({id}); 75 | 76 | const savedBlockAfterParsing = await dbBlocks.findOne({id}); 77 | 78 | expect(RewardDistributor).toHaveBeenCalledTimes(1); 79 | expect(mockDistribute).toHaveBeenCalledTimes(1); 80 | expect(savedBlockBeforeParsing).toBeUndefined(); 81 | expect(savedBlockAfterParsing.id).toBe(id); 82 | }); 83 | }); 84 | -------------------------------------------------------------------------------- /web/src/utils.js: -------------------------------------------------------------------------------- 1 | const ADM_DENOMINATION = 100000000; 2 | 3 | function replaceWithDate(text, dateObject) { 4 | return text.replace(/{([a-zA-Z_]*)}/g, (_, digit) => dateObject[digit]); 5 | } 6 | 7 | /** 8 | * Formats a unix timestamp to string 9 | * @param {number} timestamp Timestamp to format 10 | * @return {object} Contains different formatted strings 11 | */ 12 | export function formatDate(timestamp) { 13 | if (!timestamp) { 14 | return false; 15 | } 16 | 17 | const dateObject = new Date(timestamp); 18 | 19 | const formattedDate = { 20 | year: dateObject.getFullYear(), 21 | month: dateObject.getMonth() + 1, 22 | date: dateObject.getDate(), 23 | hours: dateObject.getHours(), 24 | minutes: dateObject.getMinutes(), 25 | seconds: dateObject.getSeconds(), 26 | }; 27 | 28 | for (const digit in formattedDate) { 29 | if ({}.hasOwnProperty.call(formattedDate, digit)) { 30 | formattedDate[digit] = String(formattedDate[digit]).padStart(2, '0'); 31 | } 32 | } 33 | 34 | formattedDate.YYYY_MM_DD = replaceWithDate('{year}-{month}-{date}', formattedDate); 35 | formattedDate.YYYY_MM_DD_hh_mm = replaceWithDate('{YYYY_MM_DD} {hours}:{minutes}', formattedDate); 36 | formattedDate.hh_mm_ss = replaceWithDate('{hours}:{minutes}:{seconds}', formattedDate); 37 | 38 | return formattedDate; 39 | } 40 | 41 | /** 42 | * Formats a number using fixed-point notation and digit grouping 43 | * @example 44 | * formatNumber(1234.54321) // '1,234.5432' 45 | * @param {number} num number to format 46 | * @param {number} maximumFractionDigits 47 | * @return {string} formatted number 48 | */ 49 | export function formatNumber(num, maximumFractionDigits = 4) { 50 | const number = +num; 51 | 52 | if (typeof number === 'number' && !isNaN(number)) { 53 | if (number > 0 && number < 0.01) { 54 | return '< 0.01'; 55 | } 56 | 57 | return number.toLocaleString('en-US', {maximumFractionDigits}); 58 | } 59 | 60 | return ''; 61 | } 62 | 63 | export function parseADM(adm) { 64 | return formatNumber(adm / ADM_DENOMINATION, 2); 65 | } 66 | 67 | 68 | /** 69 | * Sorts the given array by sortDirection property sort 70 | * @param {string} sortDirection - sort direction 71 | * @param {string | number} prop - property to sort 72 | * @param {any[]} array - array to sort 73 | * @return {any[]} 74 | */ 75 | export function sortBy(sortDirection, prop, array) { 76 | return array.sort((a, b) => { 77 | const [aVal, bVal] = [a[prop], b[prop]][ 78 | sortDirection === 'ascending' ? 'slice' : 'reverse' 79 | ](); 80 | 81 | if (typeof aVal === 'string' && typeof bVal === 'string') { 82 | return aVal.localeCompare(bVal); 83 | } 84 | return Number(aVal) - Number(bVal); 85 | }); 86 | } 87 | -------------------------------------------------------------------------------- /server/src/helpers/sync_db.js: -------------------------------------------------------------------------------- 1 | import log from './log.js'; 2 | 3 | const getFilter = (query = {}) => { 4 | const queryType = typeof query; 5 | 6 | if (queryType === 'function') { 7 | return query; 8 | } else if (queryType === 'object') { 9 | const filter = (val) => { 10 | for (const property in query) { 11 | if (Object.hasOwnProperty.call(query, property)) { 12 | if (val[property] !== query[property]) { 13 | return false; 14 | } 15 | } 16 | } 17 | return true; 18 | }; 19 | 20 | return filter; 21 | } else { 22 | throw new Error(`query should be a function or object, but got a ${queryType}`); 23 | } 24 | }; 25 | 26 | export default (db, updateInterval) => { 27 | db.read(); 28 | 29 | db.insert = async function(data) { 30 | try { 31 | if (!db.data?.values) { 32 | db.data = {values: []}; 33 | } 34 | 35 | db.data.values.push(data); 36 | 37 | await db.write(); 38 | 39 | return data; 40 | } catch (error) { 41 | log.warn(error); 42 | 43 | return false; 44 | } 45 | }; 46 | 47 | db.find = async function(query) { 48 | try { 49 | const filter = getFilter(query); 50 | 51 | if (!db.data) { 52 | return []; 53 | } 54 | 55 | const value = db.data.values.filter(filter); 56 | 57 | return value; 58 | } catch (error) { 59 | log.warn(error); 60 | 61 | return false; 62 | } 63 | }; 64 | 65 | db.findOne = async function(query) { 66 | try { 67 | const filter = getFilter(query); 68 | 69 | if (!db.data) { 70 | return; 71 | } 72 | 73 | const value = db.data.values.find(filter); 74 | 75 | return value; 76 | } catch (error) { 77 | log.warn(error); 78 | 79 | return false; 80 | } 81 | }; 82 | 83 | db.update = async function(query, data) { 84 | try { 85 | const filter = getFilter(query); 86 | 87 | if (!db.data) { 88 | return; 89 | } 90 | 91 | const {values} = db.data; 92 | 93 | const index = values.findIndex(filter); 94 | 95 | if (index === -1) { 96 | return false; 97 | } 98 | 99 | values[index] = { 100 | ...values[index], 101 | ...data, 102 | }; 103 | 104 | await db.write(); 105 | 106 | return values[index]; 107 | } catch (error) { 108 | log.warn(error); 109 | 110 | return false; 111 | } 112 | }; 113 | 114 | if (updateInterval && process.env.NODE_ENV !== 'test') { 115 | setInterval(() => db.write(), updateInterval); 116 | } 117 | 118 | return db; 119 | }; 120 | -------------------------------------------------------------------------------- /web/src/App.svelte: -------------------------------------------------------------------------------- 1 | 48 | 49 | 50 | 51 |
52 |
53 |
54 |
55 | Dashboard 56 |
57 | 58 | 66 |
67 | 68 |

69 | Delegate 70 | 71 | 72 | {store?.delegate.username} 73 | 74 | 75 | distributes {system?.reward_percentage}% rewards to 76 | voters {system?.donate_percentage ? `and donates ${system?.donate_percentage}% to ADAMANT Foundation` : '' } with 77 | payouts every {system?.payoutperiod}. Minimum payout is {system?.minpayout} ADM. 78 |

79 | 80 | 84 |
85 | 86 | 90 | 91 | 94 |
95 | 96 | 97 | -------------------------------------------------------------------------------- /web/src/app.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Exo+2:wght@400;500&display=swap'); 2 | 3 | :root { 4 | font-family: Exo 2,sans-serif; 5 | font-size: 16px; 6 | line-height: 24px; 7 | font-weight: 400; 8 | 9 | font-synthesis: none; 10 | text-rendering: optimizeLegibility; 11 | -webkit-font-smoothing: antialiased; 12 | -moz-osx-font-smoothing: grayscale; 13 | -webkit-text-size-adjust: 100%; 14 | 15 | --mdc-theme-primary: #2e7eed; 16 | --mdc-theme-secondary: #676778; 17 | --mdc-theme-background: #424242; 18 | --mdc-theme-surface: #424242; 19 | --mdc-theme-error: #b71c1c; 20 | --mdc-theme-on-primary: #fff; 21 | --mdc-theme-on-secondary: hsla(0,0%,100%,.7); 22 | --mdc-theme-on-surface: hsla(0,0%,100%,.7); 23 | --mdc-theme-on-error: hsla(0,0%,100%,.7); 24 | --mdc-theme-text-primary-on-background: rgba(0, 0, 0, 0.87); 25 | --mdc-theme-text-secondary-on-background: rgba(0, 0, 0, 0.54); 26 | --mdc-theme-text-hint-on-background: hsla(0,0%,100%,.7); 27 | --mdc-theme-text-disabled-on-background: hsla(0,0%,100%,.7); 28 | --mdc-theme-text-icon-on-background: hsla(0,0%,100%,.7); 29 | --mdc-theme-text-primary-on-light: rgba(0, 0, 0, 0.87); 30 | --mdc-theme-text-secondary-on-light: rgba(0, 0, 0, 0.54); 31 | --mdc-theme-text-hint-on-light: hsla(0,0%,100%,.7); 32 | --mdc-theme-text-disabled-on-light: hsla(0,0%,100%,.7); 33 | --mdc-theme-text-icon-on-light: hsla(0,0%,100%,.7); 34 | --mdc-theme-text-primary-on-dark: #424242; 35 | --mdc-theme-text-secondary-on-dark: rgba(255, 255, 255, 0.7); 36 | --mdc-theme-text-hint-on-dark: rgba(255, 255, 255, 0.5); 37 | --mdc-theme-text-disabled-on-dark: rgba(255, 255, 255, 0.5); 38 | --mdc-theme-text-icon-on-dark: rgba(255, 255, 255, 0.5); 39 | } 40 | 41 | html { 42 | overflow-x: hidden; 43 | } 44 | 45 | body { 46 | background: repeating-linear-gradient(140deg,#191919,#191919 .7px,#212121 0,#212121 5px); 47 | color: #ffffff; 48 | } 49 | 50 | .mdc-data-table, .mdc-data-table__cell, .mdc-data-table__header-cell { 51 | border-color: hsla(0,0%,100%,.12); 52 | } 53 | 54 | .mdc-data-table__header-cell, .mdc-data-table__cell, 55 | .mdc-data-table__pagination-rows-per-page-label, 56 | .mdc-data-table__pagination-total, .mdc-select:not(.mdc-select--disabled) 57 | .mdc-select__selected-text, .mdc-menu .mdc-deprecated-list { 58 | color: hsla(0,0%,100%,.7); 59 | } 60 | 61 | .mdc-data-table__cell { 62 | color: #fff; 63 | } 64 | 65 | .mdc-data-table__sort-icon-button { 66 | color: hsla(0,0%,100%,.12); 67 | } 68 | 69 | .mdc-button--raised:disabled { 70 | background-color: #43484F; 71 | } 72 | 73 | .mdc-data-table__header-cell--sorted .mdc-data-table__sort-icon-button { 74 | color: hsla(0,0%,100%,.7);; 75 | } 76 | 77 | a { 78 | color: rgb(189, 183, 175) !important; 79 | } 80 | 81 | a:hover { 82 | color: rgb(117, 178, 208) !important; 83 | } 84 | -------------------------------------------------------------------------------- /web/public/icons/safari-pinned-tab.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /server/src/modules/block_parser.js: -------------------------------------------------------------------------------- 1 | import RewardDistributor from './distribute_rewards.js'; 2 | 3 | import {dbBlocks} from '../helpers/DB.js'; 4 | import {log} from '../helpers/index.js'; 5 | 6 | class QueueNode { 7 | constructor(value) { 8 | this.value = value; 9 | this.next = null; 10 | } 11 | } 12 | 13 | class BlockParser { 14 | constructor() { 15 | this.queue = {}; 16 | this.length = 0; 17 | 18 | this.tail = null; 19 | this.head = null; 20 | 21 | this.isLocked = false; 22 | } 23 | 24 | get isEmpty() { 25 | return this.length === 0; 26 | } 27 | 28 | queued(blockId) { 29 | return !!this.queue[blockId]; 30 | } 31 | 32 | enqueue(block) { 33 | const {id} = block; 34 | 35 | if (!this.queued(id)) { 36 | const node = new QueueNode(block); 37 | 38 | if (this.head) { 39 | this.tail.next = id; 40 | } else { 41 | this.head = node; 42 | } 43 | 44 | this.tail = node; 45 | 46 | this.queue[id] = node; 47 | this.length += 1; 48 | } 49 | } 50 | 51 | dequeue() { 52 | if (!this.isEmpty) { 53 | const {value: block} = this.head; 54 | 55 | delete this.queue[block.id]; 56 | 57 | const nextHead = this.queue[this.head.next]; 58 | 59 | if (nextHead) { 60 | this.head = nextHead; 61 | } else { 62 | this.head = null; 63 | this.tail = null; 64 | } 65 | 66 | this.length -= 1; 67 | 68 | return block; 69 | } 70 | } 71 | 72 | async run() { 73 | if (!this.isEmpty && !this.isLocked) { 74 | this.isLocked = true; 75 | 76 | const block = this.dequeue(); 77 | 78 | try { 79 | await this.parse(block); 80 | } catch (error) { 81 | const errorTemplate = `Error while processing ${block.id} (height ${block.height})`; 82 | 83 | log.error(`${errorTemplate}: ${error}`); 84 | } 85 | 86 | this.isLocked = false; 87 | 88 | return this.run(); 89 | } 90 | } 91 | 92 | async parse(block) { 93 | const {id} = block; 94 | 95 | const savedBlock = await dbBlocks.findOne({id}); 96 | 97 | const rewardDistributer = new RewardDistributor(block); 98 | 99 | if (savedBlock) { 100 | if (!savedBlock.processed) { 101 | log.info(`Re-trying to distribute rewards for block ${block.id} (height ${block.height})…`); 102 | 103 | return rewardDistributer.distribute(); 104 | } 105 | } else { 106 | log.info(`New block forged: ${block.id} (height ${block.height}).`); 107 | 108 | const insertBlock = await dbBlocks.insert(block); 109 | 110 | if (insertBlock) { 111 | log.info( 112 | `Block successfully saved: ${block.id} (height ${block.height}). Distributing rewards…`, 113 | ); 114 | 115 | return rewardDistributer.distribute(); 116 | } else { 117 | log.warn(`Failed to save block ${block.id} (height ${block.height}).`); 118 | } 119 | } 120 | } 121 | } 122 | 123 | export default BlockParser; 124 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | Hi! We are really excited that you are interested in contributing to ADAMANT. Before submitting your contribution, please make sure to take a moment and read through the following guidelines: 4 | 5 | - [Issue Reporting Guidelines](#issue-reporting-guidelines) 6 | - [Pull Request Guidelines](#pull-request-guidelines) 7 | - [Development Setup](#development-setup) 8 | - [Project Structure](#project-structure) 9 | 10 | ## Issue Reporting Guidelines 11 | 12 | - Always use https://github.com/Adamant-im/pool/issues to create new issues. 13 | 14 | ## Pull Request Guidelines 15 | 16 | - The `master` branch is just a snapshot of the latest stable release. All development should be done in dedicated branches. **Do not submit PRs against the `master` branch.** 17 | 18 | - Checkout a topic branch from the relevant branch, e.g. `dev`, and merge back against that branch. 19 | 20 | - Work in the `src` folder and **DO NOT** check-in `dist` in the commits. 21 | 22 | - It's OK to have multiple small commits as you work on the PR - GitHub will automatically squash it before merging. 23 | 24 | - Make sure `npm run lint` passes. (see [development setup](#development-setup)) 25 | 26 | - If adding a new feature: 27 | - Add accompanying test case. 28 | - Provide a convincing reason to add this feature. Ideally, you should open a suggestion issue first and have it approved before working on it. 29 | 30 | - If fixing bug: 31 | - If you are resolving a special issue, add `(fix #xxxx[,#xxxx])` (#xxxx is the issue id) in your PR title for a better release log, e.g. `update entities encoding/decoding (fix #3899)`. 32 | - Provide a detailed description of the bug in the PR. Live demo preferred. 33 | - Add appropriate test coverage if applicable. 34 | 35 | ## Development Setup 36 | 37 | You will need [NodeJS](http://nodejs.org/) and npm. 38 | 39 | After cloning the repo, run: 40 | 41 | ``` bash 42 | $ npm install # install the dependencies of the project and husky 43 | ``` 44 | 45 | If you are only going to work with server logic, you can build the web part: 46 | 47 | ```bash 48 | $ npm run build:web 49 | ``` 50 | 51 | ## Project Structure 52 | 53 | This repository employs a [monorepo](https://en.wikipedia.org/wiki/Monorepo) setup which hosts a number of associated packages under the root directory: 54 | 55 | - **`server`**: contains server logic 56 | 57 | - Commonly used npm commands: 58 | 59 | ```bash 60 | # start the server 61 | $ npm run start 62 | 63 | # run linter 64 | $ npm run lint 65 | 66 | # run all tests 67 | $ npm run test 68 | ``` 69 | 70 | - Create and use `config.test.jsonc` config file instead of default one 71 | 72 | - **`web`**: contains front-end part 73 | 74 | - Commonly used npm commands: 75 | 76 | ```bash 77 | # start dev server 78 | $ npm run dev 79 | 80 | # run linter 81 | $ npm run lint 82 | 83 | # build the web 84 | $ npm run build 85 | ``` 86 | 87 | - You can create `.env` file to use custom API base url, e.g.: 88 | 89 | ```bash 90 | VITE_BASE_URL=http://localhost:36667/api 91 | ``` 92 | -------------------------------------------------------------------------------- /web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ADAMANT Forging Pool 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 41 | 42 | 46 | 47 | 51 | 52 | 56 | 57 | 58 |
59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ADAMANT Forging Pool 2 | 3 | > Read more about [Forging, delegates, Fair dPoS, and how to run your Forging pool](https://medium.com/adamant-im/earning-money-on-adm-forging-4c7b6eb15516) 4 | 5 | > This software is a successor of outdated [v2 Forging pool](https://github.com/Adamant-im/adamant-pool) 6 | 7 |
8 | 9 |

10 | 11 | 12 |

13 | 14 |

15 | Calculate and transfer voters’ rewards automatically. 16 |

17 | 18 |

19 | 20 | - :rainbow: Easy to install 21 | - :handshake: Reliable, uses decentralized network advantages 22 | - :hammer_and_wrench: Customizable (using config file) 23 | - :scroll: History stored in local files (powered by [lowdb](https://github.com/typicode/lowdb)) 24 | - :rocket: Minimum server requirements: 1 vCPU and 512 MB of RAM 25 | - :carpentry_saw: You can setup the pool on a separate machine without a node 26 | - :chart_with_upwards_trend: Dashboard for voters with mobile version support 27 | - :bell: Notification system via ADAMANT or Slack for admin 28 | 29 | ## Installation 30 | 31 | ### Requirements 32 | 33 | - NodeJS v16+ (already installed if you have a node on your machine) 34 | 35 | ### Setup 36 | 37 | Clone the repository with pool into a newly created directory: 38 | 39 | ``` 40 | git clone https://github.com/Adamant-im/pool 41 | ``` 42 | 43 | Move to directory with the cloned repository: 44 | 45 | ``` 46 | cd pool 47 | ``` 48 | 49 | Install dependencies using npm or any other package manager: 50 | 51 | ``` 52 | npm install 53 | ``` 54 | 55 | Build a website: 56 | 57 | ``` 58 | npm run build:web 59 | ``` 60 | 61 | ### Pre-launch tuning 62 | 63 | Copy default config as `config.jsonc`: 64 | 65 | ``` 66 | cp config.default.jsonc config.jsonc 67 | ``` 68 | 69 | And edit that file by inserting the pool's secret phrase as the minimum configuration, e.g. using `nano`: 70 | 71 | ``` 72 | nano config.jsonc 73 | ``` 74 | 75 | > See comments in `config.default.jsonc` for more parameters. 76 | 77 | ### Migration from v2 78 | 79 | To migrate a database from v2 run the migration script with the specified path to the target pool or database: 80 | 81 | ```sh 82 | # or ~/adamant-pool/db 83 | $ node scripts/migrate.mjs ~/adamant-pool 84 | ``` 85 | 86 | In order for the changes to take effect, you will need to restart your pool. 87 | 88 | ## Launching 89 | 90 | You can start the pool using `npm` command: 91 | 92 | ``` 93 | npm run start 94 | ``` 95 | 96 | but we recommend to use a process manager to start the pool, f.e. [`pm2`](https://pm2.keymetrics.io/): 97 | 98 | ``` 99 | pm2 start ./scripts/start.sh --name "adamantpool" 100 | ``` 101 | 102 | ## Add pool to cron 103 | 104 | Edit crontab file using the command below: 105 | 106 | ``` 107 | crontab -e 108 | ``` 109 | 110 | and paste the string: 111 | 112 | ``` 113 | @reboot cd /home/adamant/pool && pm2 start /home/adamant/pool/scripts/start.sh --name "adamantpool" 114 | ``` 115 | 116 | ## Contribution 117 | 118 | Please have a look at the [CONTRIBUTING.md](./.github/CONTRIBUTING.md) 119 | -------------------------------------------------------------------------------- /server/src/helpers/config/reader.js: -------------------------------------------------------------------------------- 1 | import jsonminify from 'jsonminify'; 2 | import keys from 'adamant-api/src/helpers/keys.js'; 3 | import fs from 'fs'; 4 | 5 | import {join, dirname} from 'path'; 6 | import {fileURLToPath} from 'url'; 7 | 8 | import validateConfig from './validate.js'; 9 | import configSchema from './schema.js'; 10 | 11 | import {MIN_PAYOUT} from '../const.js'; 12 | 13 | const __dirname = dirname(fileURLToPath(import.meta.url)); 14 | 15 | const {version} = JSON.parse( 16 | fs.readFileSync(join(__dirname, '../../../../package.json'), 'utf-8'), 17 | ); 18 | 19 | const getFullConfigPath = (configPath) => ( 20 | join(__dirname, '../../../../', configPath) 21 | ); 22 | 23 | const loadConfig = (configPath) => { 24 | return JSON.parse(jsonminify( 25 | fs.readFileSync(getFullConfigPath(configPath), 'utf-8'), 26 | )); 27 | }; 28 | 29 | let config = loadConfig('config.default.jsonc'); 30 | 31 | const configPaths = [ 32 | './config.test.jsonc', 33 | './config.jsonc', 34 | './config.json', 35 | ]; 36 | 37 | let loadedConfigPath; 38 | 39 | for (const configPath of configPaths) { 40 | if (fs.existsSync(getFullConfigPath(configPath))) { 41 | try { 42 | const loadedConfig = loadConfig(configPath); 43 | 44 | config = { 45 | ...config, 46 | ...loadedConfig, 47 | }; 48 | 49 | loadedConfigPath = configPath; 50 | 51 | break; 52 | } catch (error) { 53 | exit(`Cannot parse or read config file ${configPath}. Error:`, error); 54 | } 55 | } 56 | } 57 | 58 | config.version = version; 59 | 60 | if (!config.node_ADM) { 61 | exit(`Pool's config is wrong. ADM nodes are not set. Cannot start Pool.`); 62 | } 63 | 64 | if (!config.passPhrase) { 65 | exit(`Pool's config is wrong. No passPhrase. Cannot start Pool.`); 66 | } 67 | 68 | let keysPair; 69 | 70 | try { 71 | keysPair = keys.createKeypairFromPassPhrase(config.passPhrase); 72 | } catch (error) { 73 | exit('Pool\'s config is wrong. Invalid passPhrase. Cannot start Pool. Error: ', error); 74 | } 75 | 76 | const address = keys.createAddressFromPublicKey(keysPair.publicKey); 77 | 78 | config.publicKey = keysPair.publicKey.toString('hex'); 79 | config.address = address; 80 | 81 | const errorMessage = validateConfig(config, configSchema); 82 | 83 | if (errorMessage) { 84 | exit(errorMessage); 85 | } 86 | 87 | if (config.minpayout < MIN_PAYOUT) { 88 | exit(`Pool's ${address} config is wrong. Parameter minpayout cannot be less, than ${MIN_PAYOUT} (ADM). Cannot start Pool.`); 89 | } 90 | 91 | config.poolsShare = 100 - config.reward_percentage - config.donate_percentage; 92 | 93 | if (config.poolsShare < 0) { 94 | exit(`Pool's ${address} config is wrong. reward_percentage + donate_percentage must be <= 100. Cannot start Pool.`); 95 | } 96 | 97 | config.payoutperiod = config.payoutperiod[0].toUpperCase() + config.payoutperiod.slice(1).toLowerCase(); 98 | 99 | console.info(`Pool ${address} successfully read a config-file (${loadedConfigPath ? loadedConfigPath : 'default'}).`); 100 | 101 | function exit(...errorMessages) { 102 | console.error(...errorMessages); 103 | process.exit(-1); 104 | } 105 | 106 | export default config; 107 | -------------------------------------------------------------------------------- /server/src/helpers/utils.js: -------------------------------------------------------------------------------- 1 | import {SAT, EPOCH} from './const.js'; 2 | 3 | function replaceWithDate(text, dateObject) { 4 | return text.replace(/{([a-zA-Z_]*)}/g, (_, digit) => dateObject[digit]); 5 | } 6 | 7 | export default { 8 | /** 9 | * Strict object type check. Only returns true 10 | * for plain JavaScript objects. 11 | * @param {any} val Value to check 12 | * @return {boolean} 13 | */ 14 | isPlainObject(val) { 15 | const _toString = Object.prototype.toString; 16 | 17 | return _toString.call(val) === '[object Object]'; 18 | }, 19 | 20 | /** 21 | * Converts provided `time` to ADAMANT's epoch timestamp 22 | * @param {number=} time timestamp to convert 23 | * @return {number} 24 | */ 25 | epochTime(time) { 26 | if (!time) { 27 | time = Date.now(); 28 | } 29 | 30 | return Math.floor((time - EPOCH) / 1000); 31 | }, 32 | 33 | /** 34 | * Converts ADAMANT's epoch timestamp to a Unix timestamp 35 | * @param {number} epochTime timestamp to convert 36 | * @return {number} 37 | */ 38 | toTimestamp(epochTime) { 39 | return epochTime * 1000 + EPOCH; 40 | }, 41 | 42 | satsToADM(sats, decimals = 8) { 43 | const adm = (+sats / SAT).toFixed(decimals); 44 | 45 | return adm; 46 | }, 47 | 48 | unix() { 49 | return Date.now(); 50 | }, 51 | 52 | /** 53 | * Formats unix timestamp to string 54 | * @param {number} timestamp Timestamp to format 55 | * @return {object} Contains different formatted strings 56 | */ 57 | formatDate(timestamp) { 58 | if (!timestamp) { 59 | return false; 60 | } 61 | 62 | const dateObject = new Date(timestamp); 63 | 64 | const formattedDate = { 65 | year: dateObject.getFullYear(), 66 | month: dateObject.getMonth() + 1, 67 | date: dateObject.getDate(), 68 | hours: dateObject.getHours(), 69 | minutes: dateObject.getMinutes(), 70 | seconds: dateObject.getSeconds(), 71 | }; 72 | 73 | for (const digit in formattedDate) { 74 | if ({}.hasOwnProperty.call(formattedDate, digit)) { 75 | formattedDate[digit] = String(formattedDate[digit]).padStart(2, '0'); 76 | } 77 | } 78 | 79 | formattedDate.YYYY_MM_DD = replaceWithDate('{year}-{month}-{date}', formattedDate); 80 | formattedDate.YYYY_MM_DD_hh_mm = replaceWithDate('{YYYY_MM_DD} {hours}:{minutes}', formattedDate); 81 | formattedDate.hh_mm_ss = replaceWithDate('{hours}:{minutes}:{seconds}', formattedDate); 82 | 83 | return formattedDate; 84 | }, 85 | 86 | thousandSeparator(num, doBold) { 87 | const parts = (num + '').split('.'); 88 | const main = parts[0]; 89 | const len = main.length; 90 | let output = ''; 91 | let i = len - 1; 92 | 93 | while (i >= 0) { 94 | output = main.charAt(i) + output; 95 | if ((len - i) % 3 === 0 && i > 0) { 96 | output = ' ' + output; 97 | } 98 | --i; 99 | } 100 | if (parts.length > 1) { 101 | if (doBold) { 102 | output = `**${output}**.${parts[1]}`; 103 | } else { 104 | output = `${output}.${parts[1]}`; 105 | } 106 | } 107 | return output; 108 | }, 109 | 110 | getPrecision(decimals) { 111 | return +(Math.pow(10, -decimals).toFixed(decimals)); 112 | }, 113 | 114 | getModuleName(id) { 115 | let n = id.lastIndexOf('\\'); 116 | 117 | if (n === -1) { 118 | n = id.lastIndexOf('/'); 119 | } 120 | 121 | if (n === -1) { 122 | return ''; 123 | } else { 124 | return id.substring(n + 1); 125 | } 126 | }, 127 | }; 128 | -------------------------------------------------------------------------------- /server/tests/modules/reward_distributor.test.js: -------------------------------------------------------------------------------- 1 | import {jest} from '@jest/globals'; 2 | import {config} from '../../src/helpers/index.js'; 3 | import {dbVoters, dbBlocks} from '../../src/helpers/DB.js'; 4 | 5 | jest.unstable_mockModule('../../src/modules/store.js', () => ({ 6 | __esModule: true, 7 | default: { 8 | delegate: { 9 | votesWeight: 100000, 10 | productivity: 100, 11 | voters: [ 12 | { 13 | username: 'test', 14 | address: config.address, 15 | publicKey: config.publicKey, 16 | balance: '50000', 17 | votesCount: 2, 18 | }, 19 | { 20 | username: 'thunder', 21 | address: 'U3247657843720097949', 22 | publicKey: 'fc7151dcc08bda712c075fbfc524e10828bbbaad56ac4001cd3f5a9b93b2ea27', 23 | balance: '5000', 24 | votesCount: 50, 25 | }, 26 | ], 27 | }, 28 | }, 29 | })); 30 | 31 | const RewardDistributor = (await import('../../src/modules/distribute_rewards.js')).default; 32 | 33 | const mockBlock = { 34 | id: 1, 35 | totalForged: 1000, 36 | height: 666, 37 | }; 38 | 39 | describe('RewardDistributor.distribute', () => { 40 | beforeEach(async () => { 41 | dbVoters.data = {values: []}; 42 | await dbVoters.write(); 43 | 44 | dbBlocks.data = {values: []}; 45 | await dbBlocks.write(); 46 | }); 47 | 48 | describe('when config.considerownvote === false', () => { 49 | it('should not consider own vote', () => { 50 | const rewardDistributor = new RewardDistributor(mockBlock); 51 | 52 | const findOwnVote = () => ( 53 | rewardDistributor.voters.find((voter) => voter.address === config.address) 54 | ); 55 | 56 | rewardDistributor.disregardOwnVote(); 57 | 58 | expect(rewardDistributor.votesWeight).toBe(75000); 59 | expect(findOwnVote()).toBeUndefined(); 60 | }); 61 | }); 62 | 63 | it('should distribute rewards for voter', async () => { 64 | const rewardDistributor = new RewardDistributor(mockBlock); 65 | 66 | await dbBlocks.insert(mockBlock); 67 | 68 | const mockVoter = { 69 | address: config.address, 70 | votesCount: 10, 71 | balance: '1000000', 72 | }; 73 | 74 | await rewardDistributor.distributeForVoter(mockVoter); 75 | 76 | expect(rewardDistributor.distributed).toStrictEqual({ 77 | votersCount: 1, 78 | rewardsADM: 0.000008, 79 | percent: 80, 80 | }); 81 | expect(rewardDistributor.isDistributionComplete).toBe(true); 82 | }); 83 | }); 84 | 85 | describe('RewardDistributor.findOrCreateVoter', () => { 86 | beforeEach(() => { 87 | dbVoters.data = {values: []}; 88 | return dbVoters.write(); 89 | }); 90 | 91 | const rewardDistributor = new RewardDistributor(mockBlock); 92 | const mockVoter = {address: config.address}; 93 | 94 | describe('when there is no saved voter', () => { 95 | it('should create a new voter and return it', async () => { 96 | const voter = await rewardDistributor.findOrCreateVoter(mockVoter); 97 | 98 | const savedVoter = await dbVoters.findOne(mockVoter); 99 | 100 | expect(voter).toStrictEqual({ 101 | ...mockVoter, 102 | pending: 0, 103 | received: 0, 104 | }); 105 | expect(savedVoter).toStrictEqual(voter); 106 | }); 107 | }); 108 | 109 | describe('when there is saved voter', () => { 110 | it('should return saved voter', async () => { 111 | await dbVoters.insert({...mockVoter, pending: 1, received: 0}); 112 | 113 | const voter = await rewardDistributor.findOrCreateVoter(mockVoter); 114 | 115 | expect(voter).toStrictEqual({ 116 | ...mockVoter, 117 | pending: 1, 118 | received: 0, 119 | }); 120 | }); 121 | }); 122 | }); 123 | -------------------------------------------------------------------------------- /web/src/lib/TransactionTable.svelte: -------------------------------------------------------------------------------- 1 | 29 | 30 |
31 |
32 | Transactions 33 | 34 | {transactions.length} 35 | 36 |
37 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | arrow_upward 53 | 54 | 55 | 56 | arrow_upward 57 | 58 | 59 | 60 | arrow_upward 61 | 62 | 70 | 71 | arrow_upward 72 | 73 | 74 | 75 | 76 | {#each slice as item, index} 77 | 78 | {index + 1 + currentPage * rowsPerPage} 79 | {item.address} 80 | {item.transactionId} 81 | {formatNumber(item.payoutcount)} 82 | {formatDate(item.timeStamp)?.YYYY_MM_DD_hh_mm} 83 | 84 | {/each} 85 | 86 | 87 | 88 | 89 | 90 | 95 | 96 | 97 | {start + 1}-{end} of {transactions.length} 98 | 99 | 100 | (currentPage = 0)} 105 | disabled={currentPage === 0}>first_page 107 | currentPage--} 112 | disabled={currentPage === 0}>chevron_left 114 | currentPage++} 119 | disabled={currentPage === lastPage}>chevron_right 121 | (currentPage = lastPage)} 126 | disabled={currentPage === lastPage}>last_page 128 | 129 | 130 |
-------------------------------------------------------------------------------- /server/tests/helpers/DB.test.js: -------------------------------------------------------------------------------- 1 | import {dbTrans as db} from '../../src/helpers/DB.js'; 2 | 3 | const accounts = [ 4 | { 5 | id: 1, 6 | balance: 100, 7 | }, { 8 | id: 2, 9 | balance: 200, 10 | }, { 11 | id: 3, 12 | balance: 300, 13 | }, { 14 | id: 4, 15 | balance: 100, 16 | }, { 17 | id: 5, 18 | balance: 1000, 19 | }, 20 | ]; 21 | 22 | const insertAccounts = () => { 23 | const promises = []; 24 | 25 | for (const account of accounts) { 26 | promises.push(db.insert(account)); 27 | } 28 | 29 | return Promise.all(promises); 30 | }; 31 | 32 | const clearDB = () => { 33 | db.data = {values: []}; 34 | return db.write(); 35 | }; 36 | 37 | describe('db.insert', () => { 38 | beforeEach(clearDB); 39 | 40 | test('db.insert should insert one object', async () => { 41 | await db.insert({}); 42 | 43 | expect(db.data.values.length).toBe(1); 44 | }); 45 | 46 | test(`db.insert should insert ${accounts.length} objects`, async () => { 47 | await insertAccounts(); 48 | 49 | expect(db.data.values.length).toBe(accounts.length); 50 | }); 51 | 52 | test('db.insert should create data object if it doesn\' exist', async () => { 53 | db.data = undefined; // no data 54 | await db.write(); 55 | 56 | await db.insert({}); 57 | 58 | expect(db.data.values.length).toBe(1); 59 | }); 60 | 61 | test('db.insert should create values array if it doesn\' exist', async () => { 62 | db.data = {}; // no values 63 | await db.write(); 64 | 65 | await db.insert({}); 66 | 67 | expect(db.data.values.length).toBe(1); 68 | }); 69 | }); 70 | 71 | describe('db.find', () => { 72 | beforeEach(clearDB); 73 | 74 | test('db.find on empty database should return []', async () => { 75 | const results = await db.find(); 76 | 77 | expect(Array.isArray(results)).toBeTruthy(); 78 | expect(results.length).toBe(0); 79 | }); 80 | 81 | test('db.find called with function should find all objects', async () => { 82 | await insertAccounts(); 83 | const results = await db.find((obj) => obj.balance >= 200); 84 | 85 | expect(Array.isArray(results)).toBeTruthy(); 86 | expect(results.length).toBe(3); 87 | expect(results).toContainEqual({balance: 200, id: 2}); 88 | expect(results).toContainEqual({balance: 300, id: 3}); 89 | expect(results).toContainEqual({balance: 1000, id: 5}); 90 | }); 91 | 92 | test('db.find called with query object should find all objects', async () => { 93 | await insertAccounts(); 94 | const results = await db.find({balance: 100}); 95 | 96 | expect(Array.isArray(results)).toBeTruthy(); 97 | expect(results.length).toBe(2); 98 | expect(results).toContainEqual({balance: 100, id: 1}); 99 | expect(results).toContainEqual({balance: 100, id: 4}); 100 | }); 101 | 102 | test('db.find called with a string should throw error', () => { 103 | return expect(db.find('a string')).resolves.toBe(false); 104 | }); 105 | 106 | test('db.find called with a number should throw error', () => { 107 | return expect(db.find(69)).resolves.toBe(false); 108 | }); 109 | }); 110 | 111 | describe('db.findOne', () => { 112 | beforeEach(clearDB); 113 | 114 | test('db.findOne on empty database should return undefined', async () => { 115 | const result = await db.findOne(); 116 | 117 | expect(result).toBeFalsy(); 118 | }); 119 | 120 | test('db.findOne called with function should find first object', async () => { 121 | await insertAccounts(); 122 | const result = await db.findOne((obj) => obj.balance >= 200); 123 | 124 | expect(result).toEqual({balance: 200, id: 2}); 125 | }); 126 | 127 | test('db.findOne called with query object should find first object', async () => { 128 | await insertAccounts(); 129 | const result = await db.findOne({balance: 100}); 130 | 131 | expect(result).toEqual({balance: 100, id: 1}); 132 | }); 133 | 134 | test('db.findOne called with a string should return false', () => { 135 | return expect(db.findOne('a string')).resolves.toBe(false); 136 | }); 137 | 138 | test('db.findOne called with a number should return false', () => { 139 | return expect(db.findOne(69)).resolves.toBe(false); 140 | }); 141 | }); 142 | 143 | describe('db.update', () => { 144 | beforeEach(clearDB); 145 | 146 | test('db.update on empty database should return undefined', async () => { 147 | const result = await db.update({}, {}); 148 | 149 | expect(result).toBeFalsy(); 150 | }); 151 | 152 | test('db.update called with function should update first object', async () => { 153 | await insertAccounts(); 154 | const result = await db.update((obj) => obj.id === 2, {balance: 100}); 155 | const dbItem = await db.findOne({id: 2}); 156 | 157 | expect(result).toEqual({balance: 100, id: 2}); 158 | expect(dbItem).toEqual({balance: 100, id: 2}); 159 | }); 160 | 161 | test('db.update called with query object should update first object', async () => { 162 | await insertAccounts(); 163 | const result = await db.update({id: 1}, {balance: 400}); 164 | const dbItem = await db.findOne({id: 1}); 165 | 166 | expect(result).toEqual({balance: 400, id: 1}); 167 | expect(dbItem).toEqual({balance: 400, id: 1}); 168 | }); 169 | }); 170 | -------------------------------------------------------------------------------- /web/src/lib/VoterTable.svelte: -------------------------------------------------------------------------------- 1 | 36 | 37 |
38 |
39 | Voters 40 | 41 | {voters.length} 42 | 43 |
44 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | arrow_upward 60 | 61 | 68 | 69 | arrow_upward 70 | 71 | 72 | 73 | arrow_upward 74 | 75 | 76 | 77 | arrow_upward 78 | 79 | 80 | 81 | arrow_upward 82 | 83 | 84 | 85 | arrow_upward 86 | 87 | 88 | 89 | arrow_upward 90 | 91 | 92 | 93 | 94 | {#each slice as voter, index} 95 | 96 | { index + 1 + currentPage * rowsPerPage } 97 | { voter.address } 98 | { voter.pending ? formatNumber(voter.pending) : '—' } 99 | { voter.received ? formatNumber(voter.received) : '—' } 100 | { voter.balanceADM ? formatNumber(voter.balanceADM) : '—' } 101 | { voter.votesCount ? formatNumber(voter.votesCount) : '—' } 102 | { voter.weightADM ? formatNumber(voter.weightADM) : '—' } 103 | { votesWeight && voter.weightADM ? calcWeightPercent(voter.weightADM) : '—' } 104 | 105 | {/each} 106 | 107 | 108 | 109 | 110 | 111 | 116 | 117 | 118 | {start + 1}-{end} of {voters.length} 119 | 120 | 121 | (currentPage = 0)} 126 | disabled={currentPage === 0}>first_page 128 | currentPage--} 133 | disabled={currentPage === 0}>chevron_left 135 | currentPage++} 140 | disabled={currentPage === lastPage}>chevron_right 142 | (currentPage = lastPage)} 147 | disabled={currentPage === lastPage}>last_page 149 | 150 | 151 |
152 | -------------------------------------------------------------------------------- /server/src/modules/distribute_rewards.js: -------------------------------------------------------------------------------- 1 | import store from './store.js'; 2 | 3 | import {dbVoters, dbBlocks} from '../helpers/DB.js'; 4 | import {notifier, config, utils, log} from '../helpers/index.js'; 5 | import { 6 | SAT, 7 | DEVIATION, 8 | } from '../helpers/const.js'; 9 | 10 | class RewardDistributor { 11 | constructor(block) { 12 | this.block = block; 13 | this.blockTotalForged = +block.totalForged; 14 | 15 | this.distributed = { 16 | rewardsADM: 0, 17 | votersCount: 0, 18 | percent: 0, 19 | }; 20 | 21 | this.voters = store.delegate.voters; 22 | this.votesWeight = store.delegate.votesWeight; 23 | this.eligibleVotersCount = 0; 24 | 25 | this.isDistributionComplete = false; 26 | } 27 | 28 | async distribute() { 29 | if (!config.considerownvote) { 30 | this.disregardOwnVote(); 31 | } 32 | 33 | const {voters, block, votesWeight} = this; 34 | 35 | if (votesWeight) { 36 | const distributionPromises = []; 37 | 38 | for (const voter of voters) { 39 | distributionPromises.push(this.distributeForVoter(voter)); 40 | } 41 | 42 | await Promise.all(distributionPromises); 43 | 44 | if (this.isDistributionComplete) { 45 | const {distributed, eligibleVotersCount, blockTotalForged} = this; 46 | const {votersCount, rewardsADM, percent} = distributed; 47 | 48 | if (distributed.votersCount === eligibleVotersCount) { 49 | log.info( 50 | `Block ${block.id} (height ${block.height}) rewards successfully updated — ` + 51 | `${votersCount} of ${eligibleVotersCount} eligible voters, ` + 52 | `distributedRewards: ${rewardsADM.toFixed(4)} ADM (${percent.toFixed(2)}%).`, 53 | ); 54 | } else { 55 | const blockTotalForgedInADM = utils.satsToADM(blockTotalForged * config.reward_percentage / 100, 4); 56 | 57 | this.notifyRewardsOnBlock( 58 | `distributed partially — ${votersCount} of ${eligibleVotersCount} eligible voters, ` + 59 | `distributedRewards: ${rewardsADM.toFixed(4)} of ${blockTotalForgedInADM} ADM.`, 60 | 'warn', 61 | ); 62 | } 63 | } else { 64 | this.notifyRewardsOnBlock('could not be distributed. Check logs.', 'error'); 65 | } 66 | } 67 | } 68 | 69 | disregardOwnVote() { 70 | const {voters} = this; 71 | const ownVoteIndex = voters.findIndex((voter) => voter.address === config.address); 72 | 73 | if (ownVoteIndex !== -1) { 74 | const ownVote = voters[ownVoteIndex]; 75 | 76 | this.votesWeight -= (+ownVote.balance / ownVote.votesCount); 77 | this.voters.splice(ownVoteIndex, 1); 78 | } 79 | } 80 | 81 | async distributeForVoter(voter) { 82 | const {block, distributed, votesWeight} = this; 83 | 84 | try { 85 | const {votesCount} = voter; 86 | const voterBalance = +voter.balance; 87 | 88 | const isVoterEligible = votesCount && voterBalance > DEVIATION; 89 | 90 | if (isVoterEligible) { 91 | this.eligibleVotersCount += 1; 92 | 93 | const dbVoter = await this.findOrCreateVoter(voter); 94 | 95 | if (dbVoter) { 96 | const user = this.calcVoterReward(voterBalance, votesCount, votesWeight); 97 | 98 | const pending = dbVoter.pending + user.reward; 99 | 100 | // TODO: name properties in db normalno 101 | const updatedVoter = await dbVoters.update( 102 | {address: voter.address}, 103 | { 104 | pending, 105 | votesCount, 106 | weightADM: user.weight / SAT, 107 | balanceADM: voterBalance / SAT, 108 | }); 109 | 110 | if (updatedVoter) { 111 | const userWeightInADM = utils.satsToADM(user.weight, 0); 112 | 113 | log.log( 114 | `Voter's rewards successfully updated on block ${block.id} (height ${block.height}): ` + 115 | `reward for this block ${user.reward.toFixed(8)} ADM, ${pending.toFixed(8)} ADM payouts pending for ` + 116 | `${voter.address}. userWeight: ${userWeightInADM} ADM (${user.percent.toFixed(2)}%).`, 117 | ); 118 | 119 | distributed.votersCount += 1; 120 | distributed.rewardsADM += user.reward; 121 | distributed.percent += user.percent; 122 | 123 | // Mark block processed, if any voter gets reward 124 | const updatedBlock = await dbBlocks.update( 125 | {id: block.id}, 126 | { 127 | processed: true, 128 | ...distributed, 129 | }); 130 | 131 | if (updatedBlock) { 132 | this.isDistributionComplete = true; 133 | } 134 | } else { 135 | log.error(`Failed to update rewards for ${voter.address} voter on block ${block.id}.`); 136 | } 137 | } 138 | } 139 | } catch (error) { 140 | log.error( 141 | `Error while distributing rewards for ${voter.address} on block ${block.id} (height ${block.height}): ${error}`, 142 | ); 143 | } 144 | } 145 | 146 | calcVoterReward(voterBalance, votesCount, votesWeight) { 147 | const weight = voterBalance / votesCount; 148 | const percent = ((weight / votesWeight) * config.reward_percentage * store.delegate.productivity) / 100; 149 | const reward = (this.blockTotalForged * percent) / (SAT * 100); 150 | 151 | return { 152 | weight, 153 | percent, 154 | reward, 155 | }; 156 | } 157 | 158 | async findOrCreateVoter(voter) { 159 | const {block} = this; 160 | const {address} = voter; 161 | 162 | const savedVoter = await dbVoters.findOne({address}); 163 | 164 | if (savedVoter) { 165 | log.info(`Successfully added new voter ${voter.address} on block ${block.id} (height ${block.height}).`); 166 | 167 | return savedVoter; 168 | } 169 | 170 | const addedVoter = await dbVoters.insert({ 171 | address, 172 | pending: 0, 173 | received: 0, 174 | }); 175 | 176 | if (!addedVoter) { 177 | this.notifyRewardsOnBlock(`could not be distributed. Failed to add voter ${voter.address}`, 'error'); 178 | } 179 | 180 | return addedVoter; 181 | } 182 | 183 | notifyRewardsOnBlock(message, logLevel) { 184 | const {block} = this; 185 | 186 | notifier( 187 | `Pool ${config.logName}: Rewards on block ${block.id} (height ${block.height}) ${message}`, 188 | logLevel, 189 | ); 190 | } 191 | } 192 | 193 | export default RewardDistributor; 194 | -------------------------------------------------------------------------------- /server/src/modules/store.js: -------------------------------------------------------------------------------- 1 | import {api, utils, config, log} from '../helpers/index.js'; 2 | import {dbVoters, dbTrans, dbBlocks} from '../helpers/DB.js'; 3 | import {UPDATE_DELEGATE_INTERVAL, SAT} from '../helpers/const.js'; 4 | 5 | const store = { 6 | isDistributingRewards: false, 7 | periodInfo: { 8 | totalForgedSats: 0, 9 | totalForgedADM: 0, 10 | userRewardsADM: 0, 11 | forgedBlocks: 0, 12 | previousRunTimestamp: 0, 13 | previousRunEpochtime: 0, 14 | nextRunMoment: {}, 15 | nextRunTimestamp: 0, 16 | nextRunDateString: '', 17 | }, 18 | delegate: { 19 | address: config.address, 20 | publicKey: config.publicKey, 21 | balance: 0, 22 | voters: [], 23 | votesWeight: 0, 24 | forged: 0, 25 | rewards: 0, 26 | fees: 0, 27 | rank: 0, 28 | approval: 0, 29 | productivity: 0, 30 | pendingRewardsADM: 0, 31 | }, 32 | 33 | updateAll() { 34 | const updates = [ 35 | this.updateDelegate(), 36 | this.updateVoters(), 37 | this.updateBalance(), 38 | this.updateStats(), 39 | ]; 40 | 41 | return Promise.all(updates); 42 | }, 43 | 44 | async updateStats() { 45 | try { 46 | const delegateForgedInfo = await api.get('delegates/forging/getForgedByAccount', { 47 | generatorPublicKey: config.publicKey, 48 | }); 49 | 50 | if (delegateForgedInfo.success) { 51 | const { 52 | forged, 53 | rewards, 54 | fees, 55 | } = delegateForgedInfo.data; 56 | 57 | this.delegate = { 58 | ...this.delegate, 59 | forged: +forged, 60 | rewards: +rewards, 61 | fees: +fees, 62 | }; 63 | 64 | const feesInADM = utils.satsToADM(fees); 65 | const rewardsInADM = utils.satsToADM(rewards); 66 | const totalADM = utils.satsToADM(forged); 67 | 68 | log.log( 69 | `Updated forged info for delegate ${this.delegate.username}: ` + 70 | `total ${totalADM} ADM, ` + 71 | `block rewards ${rewardsInADM} ADM, ` + 72 | `fees ${feesInADM} ADM.`, 73 | ); 74 | } else { 75 | log.warn( 76 | `Failed to get forged info for delegate for ${config.address}. ` + 77 | `${delegateForgedInfo.errorMessage}.`, 78 | ); 79 | } 80 | 81 | const cron = (await import('../helpers/cron.js')).default.payoutCronJob; 82 | 83 | const nextRunMoment = cron.nextDate(); 84 | 85 | this.periodInfo = { 86 | ...this.periodInfo, 87 | nextRunMoment, 88 | nextRunTimestamp: nextRunMoment.valueOf(), 89 | nextRunDateString: nextRunMoment.toISODate(), 90 | }; 91 | 92 | const transactions = await dbTrans.find({}); 93 | 94 | // Assume previous run is the last saved transaction 95 | const lastTransaction = transactions.sort((a, b) => b.timeStamp - a.timeStamp)[0]; 96 | 97 | if (lastTransaction) { 98 | const previousRunTimestamp = lastTransaction.timeStamp; 99 | 100 | this.periodInfo = { 101 | ...this.periodInfo, 102 | previousRunTimestamp, 103 | previousRunEpochtime: utils.epochTime(previousRunTimestamp), 104 | }; 105 | } 106 | 107 | const periodBlocks = await dbBlocks.find(({timestamp}) => ( 108 | timestamp > this.periodInfo.previousRunEpochtime 109 | )); 110 | 111 | if (periodBlocks) { 112 | const totalForgedSats = periodBlocks.reduce((sum, block) => sum + (+block.totalForged), 0); 113 | const totalForgedADM = totalForgedSats / SAT; 114 | const userRewardsADM = periodBlocks.reduce((sum, block) => ( 115 | sum + (block.rewardsADM ? +block.rewardsADM : 0) 116 | ), 0); 117 | 118 | this.periodInfo = { 119 | ...this.periodInfo, 120 | totalForgedSats, 121 | totalForgedADM, 122 | userRewardsADM, 123 | forgedBlocks: periodBlocks.length, 124 | }; 125 | } 126 | 127 | const voters = await dbVoters.find({}); 128 | 129 | this.delegate.pendingRewardsADM = voters.reduce((sum, voter) => sum + voter.pending, 0); 130 | } catch (error) { 131 | log.error(`Error while updating forging and period stats: ${error}`); 132 | } 133 | }, 134 | 135 | async updateVotes(address) { 136 | const votes = await api.get('accounts/delegates', { 137 | address, 138 | }); 139 | 140 | if (votes.success) { 141 | const votesCount = votes.data.delegates.length; 142 | 143 | return votesCount; 144 | } else { 145 | log.warn(`Failed to get votes for ${address}. ${votes.errorMessage}.`); 146 | } 147 | }, 148 | 149 | async updateVoters() { 150 | const voters = await api.get('delegates/voters', { 151 | publicKey: config.publicKey, 152 | }); 153 | 154 | if (voters.success) { 155 | this.delegate.voters = voters.data.accounts; 156 | 157 | for (const voter of this.delegate.voters) { 158 | voter.votesCount = await this.updateVotes(voter.address); 159 | } 160 | 161 | log.log(`Updated voters: ${this.delegate.voters.length} accounts`); 162 | } else { 163 | log.warn(`Failed to get voters for ${config.address}. ${voters.errorMessage}.`); 164 | } 165 | }, 166 | 167 | async updateBalance() { 168 | const account = await api.get('accounts', { 169 | publicKey: config.publicKey, 170 | }); 171 | 172 | if (account.success) { 173 | this.delegate = { 174 | ...this.delegate, 175 | ...account.data.account, 176 | }; 177 | 178 | this.delegate.balance = +this.delegate.balance; 179 | 180 | log.log(`Updated balance: ${utils.satsToADM(this.delegate.balance)} ADM`); 181 | } else { 182 | log.warn(`Failed to get account data for ${config.address}. ${account.errorMessage}.`); 183 | } 184 | }, 185 | 186 | async updateDelegate() { 187 | const delegate = await api.get('delegates/get', { 188 | publicKey: config.publicKey, 189 | }); 190 | 191 | if (delegate.success) { 192 | this.delegate = { 193 | ...this.delegate, 194 | ...delegate.data.delegate, 195 | }; 196 | this.delegate.votesWeight = +this.delegate.votesWeight; 197 | 198 | const votesWeightInADM = utils.satsToADM(this.delegate.votesWeight); 199 | 200 | log.log( 201 | `Updated delegate ${this.delegate.username}: ` + 202 | `rank ${this.delegate.rank}, ` + 203 | `productivity ${this.delegate.productivity}%, ` + 204 | `votesWeight ${votesWeightInADM} ADM`, 205 | ); 206 | 207 | return this.delegate; 208 | } else { 209 | log.warn(`Failed to get delegate for ${config.address}. ${delegate.errorMessage}.`); 210 | } 211 | }, 212 | }; 213 | 214 | if (process.env.NODE_ENV !== 'test') { 215 | setInterval(() => store.updateAll(), UPDATE_DELEGATE_INTERVAL); 216 | } 217 | 218 | export default store; 219 | -------------------------------------------------------------------------------- /server/src/modules/pay_out.js: -------------------------------------------------------------------------------- 1 | import store from './store.js'; 2 | 3 | import {notifier, api, config, log} from '../helpers/index.js'; 4 | import {dbVoters, dbTrans} from '../helpers/DB.js'; 5 | import { 6 | SAT, 7 | RETRY_PAYOUTS_TIMEOUT, 8 | RETRY_PAYOUTS_COUNT, 9 | FEE, 10 | } from '../helpers/const.js'; 11 | 12 | class Payer { 13 | constructor() { 14 | this.periodInfo = { 15 | donatePaid: false, 16 | maintenancePaid: false, 17 | }; 18 | 19 | this.retryNo = 0; 20 | } 21 | 22 | async payOut() { 23 | await this.updateVoters(); 24 | 25 | const {votersToReward, pendingUserRewards, periodInfo} = this; 26 | const balance = store.delegate.balance / SAT; 27 | 28 | const infoString = this.getBaseInfoString(balance); 29 | 30 | if (!votersToReward.length) { 31 | return notifier(`Pool ${config.logName}: No pending payouts.\n${infoString}`, 'warn'); 32 | } 33 | 34 | const {retryNo} = this; 35 | const nextRetryNo = retryNo + 1; 36 | 37 | if (pendingUserRewards > balance) { 38 | notifier( 39 | `Pool ${config.logName}: Unable to do payouts, retryNo: ${retryNo}. ` + 40 | `Balance of the pool is less, than pending payouts. Top up the pool's balance.\n${infoString}`, 41 | 'error', 42 | ); 43 | 44 | return this.retry(); 45 | } 46 | 47 | notifier( 48 | retryNo ? 49 | `Pool ${config.logName}: Re-tying (${nextRetryNo} of ${RETRY_PAYOUTS_COUNT + 1}) to do payouts.` : 50 | `Pool ${config.logName}: Ready to do periodical payouts.\n${infoString}`, 51 | 'log', 52 | ); 53 | 54 | const { 55 | payedUserRewards, 56 | paymentFees, 57 | payedCount, 58 | updatedVoters, 59 | savedTransactions, 60 | } = await this.payVoters(votersToReward); 61 | 62 | let maintenanceString = ''; 63 | let donateString = ''; 64 | 65 | if (payedCount === votersToReward.length) { 66 | maintenanceString = await this.payToMaintenanceWallet(); 67 | 68 | if (config.donatewallet && config.donate_percentage && !periodInfo.donatePaid) { 69 | donateString = await this.payDonation(); 70 | } 71 | } 72 | 73 | let payoutInfoString = ''; 74 | 75 | const isEveryVoterRewarded = payedCount === votersToReward.length; 76 | const isEveryRewardSaved = updatedVoters === payedCount && savedTransactions === payedCount; 77 | 78 | const notifyType = isEveryRewardSaved ? 'log' : 'warn'; 79 | 80 | payoutInfoString = `I've ${isEveryVoterRewarded ? 'successfully' : ''} payed ${isEveryRewardSaved ? 'and saved ' : ''}`; 81 | 82 | if (isEveryVoterRewarded) { 83 | if (isEveryRewardSaved) { 84 | payoutInfoString += 'all '; 85 | } 86 | 87 | payoutInfoString += ( 88 | `of ${payedCount} payouts, ${payedUserRewards.toFixed(4)} ADM plus ` + 89 | `${paymentFees.toFixed(1)} ADM fees in total.` 90 | ); 91 | } else { 92 | payoutInfoString += ( 93 | `only ${payedCount} of ${votersToReward.length} payouts, ` + 94 | `${(payedUserRewards + paymentFees).toFixed(4)} of ${pendingUserRewards.toFixed(4)} ADM.` 95 | ); 96 | } 97 | 98 | if (!isEveryRewardSaved) { 99 | payoutInfoString += `\nThere is an issue${!isEveryVoterRewarded ? ' with database also' : ''}.`; 100 | 101 | if (updatedVoters < payedCount) { 102 | payoutInfoString += ` I've updated only ${updatedVoters} voters.`; 103 | } 104 | if (savedTransactions < payedCount) { 105 | payoutInfoString += ` I've saved only ${savedTransactions} transactions.`; 106 | } 107 | 108 | payoutInfoString += ` You better do these updates in database manually. Check log file for details.`; 109 | } 110 | 111 | payoutInfoString += maintenanceString; 112 | payoutInfoString += donateString; 113 | 114 | payoutInfoString += `\nThe pool's balance — ${balance.toFixed(4)} ADM.`; 115 | 116 | if (!isEveryVoterRewarded) { 117 | const timeoutInMin = ((nextRetryNo * RETRY_PAYOUTS_TIMEOUT) / 1000 / 60).toFixed(1); 118 | 119 | payoutInfoString += `\nI'll re-try to pay the remaining voters in ${timeoutInMin} minutes, retryNo: ${nextRetryNo}.`; 120 | } 121 | 122 | notifier(`Pool ${config.logName}: ${payoutInfoString}`, notifyType); 123 | 124 | if (isEveryVoterRewarded) { 125 | this.retryNo = 0; 126 | this.periodInfo = { 127 | donatePaid: false, 128 | maintenancePaid: false, 129 | }; 130 | } else { 131 | this.retry(); 132 | } 133 | } 134 | 135 | async payVoters(voters) { 136 | let payedUserRewards = 0; 137 | let payedCount = 0; 138 | let paymentFees = 0; 139 | 140 | let updatedVoters = 0; 141 | let savedTransactions = 0; 142 | 143 | for (const voter of voters) { 144 | try { 145 | const res = await this.payVoter(voter); 146 | 147 | payedUserRewards += res.amount; 148 | paymentFees += FEE; 149 | payedCount += 1; 150 | 151 | if (res.isUpdated) { 152 | updatedVoters += 1; 153 | } 154 | 155 | if (res.isTransactionSaved) { 156 | savedTransactions += 1; 157 | } 158 | } catch (error) { 159 | log.error(`Error while doing payouts for ${voter.address}: ${error}`); 160 | } 161 | } 162 | 163 | return {payedUserRewards, paymentFees, payedCount, updatedVoters, savedTransactions}; 164 | } 165 | 166 | async payVoter(voter) { 167 | let {pending, address, received} = voter; 168 | const amount = voter.pending - FEE; 169 | 170 | const result = {amount}; 171 | 172 | log.log(`Processing payment of ${amount.toFixed(8)} ADM reward to ${address}…`); 173 | 174 | const payment = await api.sendTokens(config.passPhrase, address, amount); 175 | 176 | if (!payment.success) { 177 | return log.warn( 178 | `Failed to process payment of ${amount} ADM reward to ${address}. ${payment.errorMessage}.`, 179 | ); 180 | } 181 | 182 | log.log(`Successfully payed ${amount.toFixed(8)} ADM reward to ${address} with Tx ${payment.data.transactionId}.`); 183 | 184 | received += pending; 185 | 186 | const transaction = { 187 | ...payment.data, 188 | address, 189 | received, // user received in total, including fees 190 | payoutcount: pending, // user received this time, including Tx fee 191 | timeStamp: new Date().getTime(), 192 | }; 193 | delete transaction.success; 194 | 195 | const updateVoter = await dbVoters.update({address}, { 196 | received, pending: 0, 197 | }); 198 | 199 | if (updateVoter) { 200 | log.log( 201 | `Voter's rewards successfully updated after payout: ${received.toFixed(8)} ADM received in total, ` + 202 | `0 ADM pending for ${address}.`, 203 | ); 204 | result.isUpdated = true; 205 | } else { 206 | log.error( 207 | `Failed to update rewards for ${address} after successful payout. ` + 208 | `Do it manually: ${received.toFixed(8)} ADM received in total, 0 ADM pending.`, 209 | ); 210 | } 211 | 212 | const insertTransaction = await dbTrans.insert(transaction); 213 | 214 | if (insertTransaction) { 215 | log.log( 216 | `Successfully saved transaction ${transaction.transactionId} ` + 217 | `after payout: ${pending.toFixed(8)} ADM payed to ${address}.`, 218 | ); 219 | result.isTransactionSaved = true; 220 | } else { 221 | log.error( 222 | `Failed to save transaction ${transaction.transactionId} after successful payout. ` + 223 | `Do it manually: ${pending.toFixed(8)} ADM payed to ${address}.`, 224 | ); 225 | } 226 | 227 | return result; 228 | } 229 | 230 | async payToMaintenanceWallet() { 231 | try { 232 | const {periodInfo} = this; 233 | const {totalForgedADM, userRewardsADM} = store.periodInfo; 234 | 235 | const donateADM = (config.donate_percentage * totalForgedADM) / 100; 236 | const maintenanceADM = totalForgedADM - userRewardsADM - donateADM; 237 | 238 | const payAmount = `ADM (${config.poolsShare.toFixed(2)}%) pool's share to maintenance wallet ${config.maintenancewallet}`; 239 | const notifyPayAmount = `${maintenanceADM.toFixed(4)} ${payAmount}`; 240 | const logPayAmount = `${maintenanceADM.toFixed(8)} ${payAmount}`; 241 | 242 | let maintenanceString = ''; 243 | 244 | if (config.maintenancewallet) { 245 | if (!periodInfo.maintenancePaid) { 246 | if (maintenanceADM - FEE > 0) { 247 | log.log(`${logPayAmount}…`); 248 | 249 | const paymentMaintenance = await api.sendTokens( 250 | config.passPhrase, 251 | config.maintenancewallet, 252 | maintenanceADM - FEE, 253 | ); 254 | 255 | if (paymentMaintenance.success) { 256 | periodInfo.maintenancePaid = true; 257 | 258 | log.log(`Successfully payed ${logPayAmount} with Tx ${paymentMaintenance.data.transactionId}.`); 259 | maintenanceString = `\nSent ${notifyPayAmount}.`; 260 | } else { 261 | maintenanceString = `\nUnable to send ${notifyPayAmount}, do it manually. ${paymentMaintenance.errorMessage}.`; 262 | } 263 | } else { 264 | maintenanceString = ( 265 | `\nPool's share ${maintenanceADM.toFixed(4)} ADM ` + 266 | `(${config.poolsShare.toFixed(2)}%) is less, than Tx fee.` 267 | ); 268 | } 269 | } 270 | } else { 271 | if (maintenanceADM > 0) { 272 | maintenanceString = `\nMaintenance wallet is not set. Leaving pool's share of ${notifyPayAmount}.`; 273 | } else { 274 | maintenanceString = ( 275 | `\nMaintenance wallet is not set; Pool's share ${maintenanceADM.toFixed(4)} ` + 276 | `ADM (${config.poolsShare.toFixed(2)}%) is less, than Tx fee.` 277 | ); 278 | } 279 | } 280 | 281 | return maintenanceString; 282 | } catch (error) { 283 | log.warn(`Error in payToMaintenanceWallet(): ${error}`); 284 | 285 | return ''; 286 | } 287 | } 288 | 289 | async payDonation() { 290 | try { 291 | const {periodInfo} = this; 292 | const {totalForgedADM} = store.periodInfo; 293 | 294 | const donateADM = (config.donate_percentage * totalForgedADM) / 100; 295 | 296 | const donationAmount = `ADM (${config.donate_percentage.toFixed(2)}%) donation to ${config.donatewallet}`; 297 | const notifyDonationAmount = `${donateADM.toFixed(4)} ${donationAmount}`; 298 | const logDonationAmount = `${donateADM.toFixed(8)} ${donationAmount}`; 299 | 300 | let donateString = ''; 301 | 302 | if (donateADM - FEE > 0) { 303 | log.log(`Processing payment of ${logDonationAmount}…`); 304 | 305 | const paymentDonate = await api.sendTokens( 306 | config.passPhrase, 307 | config.donatewallet, 308 | donateADM - FEE, 309 | ); 310 | 311 | if (paymentDonate.success) { 312 | periodInfo.donatePaid = true; 313 | 314 | log.log(`Successfully payed ${logDonationAmount}.`); 315 | 316 | donateString = `\nSent ${notifyDonationAmount}.`; 317 | } else { 318 | donateString = `\nUnable to send ${notifyDonationAmount}, do it manually. ${paymentDonate.errorMessage}.`; 319 | } 320 | } else { 321 | donateString = ( 322 | `\nDonation amount ${donateADM.toFixed(4)} ADM ` + 323 | `(${config.donate_percentage.toFixed(2)}%) is less, than Tx fee.` 324 | ); 325 | } 326 | 327 | return donateString; 328 | } catch (error) { 329 | log.warn(`Error in payDonation(): ${error}`); 330 | 331 | return ''; 332 | } 333 | } 334 | 335 | retry() { 336 | this.retryNo += 1; 337 | 338 | const {retryNo} = this; 339 | const timeout = retryNo * RETRY_PAYOUTS_TIMEOUT; 340 | 341 | if (this.retryNo > RETRY_PAYOUTS_COUNT) { 342 | setTimeout(() => { 343 | notifier( 344 | `Pool ${config.logName}: After ${RETRY_PAYOUTS_COUNT + 1} tries, ` + 345 | 'I didn\'t finished with payouts. Check the log file.', 346 | 'error', 347 | ); 348 | }, 1000); 349 | } else { 350 | log.log(`Re-trying payouts ${retryNo} time in ${timeout / 1000} seconds.`); 351 | 352 | setTimeout(this.payOut.bind(this), timeout); 353 | } 354 | } 355 | 356 | async updateVoters() { 357 | const voters = await dbVoters.find({}); 358 | const { 359 | votersToReward, 360 | votersBelowMin, 361 | pendingUserRewards, 362 | belowMinRewards, 363 | } = getVotersRewards(voters); 364 | 365 | this.votersToReward = votersToReward; 366 | this.votersBelowMin = votersBelowMin; 367 | this.pendingUserRewards = pendingUserRewards; 368 | this.belowMinRewards = belowMinRewards; 369 | } 370 | 371 | getBaseInfoString(balance) { 372 | const {pendingUserRewards, votersToReward, votersBelowMin, belowMinRewards} = this; 373 | const {totalForgedADM, userRewardsADM, forgedBlocks} = store.periodInfo; 374 | 375 | let infoString = `Pending ${pendingUserRewards.toFixed(4)} ADM rewards for ${votersToReward.length} voters.`; 376 | infoString += `\n${votersBelowMin.length} voters forged less, than minimum ${config.minpayout} ADM, their pending rewards are ${belowMinRewards.toFixed(4)} ADM.`; 377 | infoString += `\nThis period the pool forged ${totalForgedADM.toFixed(4)} ADM from ${forgedBlocks} blocks; ${userRewardsADM.toFixed(4)} ADM distributed to users.`; 378 | infoString += `\nThe pool's balance — ${balance.toFixed(4)} ADM.`; 379 | 380 | return infoString; 381 | } 382 | } 383 | 384 | function getVotersRewards(voters) { 385 | const votersToReward = []; 386 | const votersBelowMin = []; 387 | 388 | let pendingUserRewards = 0; 389 | let belowMinRewards = 0; 390 | 391 | voters.forEach((voter) => { 392 | if (voter.pending >= config.minpayout) { 393 | votersToReward.push(voter); 394 | pendingUserRewards += voter.pending; 395 | } else { 396 | votersBelowMin.push(voter); 397 | belowMinRewards += voter.pending; 398 | } 399 | }); 400 | 401 | return {votersToReward, votersBelowMin, pendingUserRewards, belowMinRewards}; 402 | } 403 | 404 | export default Payer; 405 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------