Skip to content

Commit

Permalink
Merge pull request #10 from Adamant-im/dev
Browse files Browse the repository at this point in the history
v1.6.0: Support LSK and new code style
  • Loading branch information
gost1k337 authored Aug 16, 2022
2 parents 1cb2bcd + 4dd94b0 commit 865b909
Show file tree
Hide file tree
Showing 52 changed files with 4,482 additions and 3,079 deletions.
4 changes: 2 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
tab_width = 4
indent_style = space
indent_size = 2
[*.md]
max_line_length = off
trim_trailing_whitespace = false
75 changes: 31 additions & 44 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,44 +1,31 @@
module.exports = {
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module"
},
"rules": {
quotes: ["error", "single"],
"semi": "warn", // обязательно ;
"semi-spacing": ["error", {"before": false, "after": true}],
"indent": ["error", "tab"],
"space-infix-ops": "error",// отступы вокруг + - * / = и тд
"eqeqeq": "error", // обязательно === и !== (нельзя == и !=)
// "no-eq-null": "error", // обязательно === и !== (нельзя == и !=) но тоько в отношении null
"curly": "error", // проверка шаблонов `${name}`
// "space-before-function-paren": [ // отступ до и после function
// "error", {
// "anonymous": "always",
// "named": "always",
// "asyncArrow": "ignore"
// }
// ],
"key-spacing": ["error", { "mode": "strict" }], // оформление обЪекта
"space-in-parens": ["error", "never"], // запрет отступов ( a,b)
"computed-property-spacing": ["error", "never"], // запрет лишних отступов в выражениях a[ i]
"array-bracket-spacing": ["error", "never"],
"no-multi-spaces": "error", // запрет лишних пробелов var a = 2
"no-sparse-arrays": "warn", // предупреждение при дырке в массиве
"no-mixed-spaces-and-tabs": "error", // нельзя миксовать табы и пробелы
"keyword-spacing": ["error", { "after": true }],
"comma-spacing": ["error", { "before": false, "after": true }], // отступ после запятой, а перед нельзя
"no-undef":"error",
"array-callback-return": "error" // коллбек методов массива типа arr.map arr.filter должны иметь return в коллбеке
},
"env": {
"browser": true,
"node": true
},
"globals": {
"Vue":true,
"Symbol":true,
"Promise":true,
},
"plugins": []
}
module.exports = {
env: {
commonjs: true,
es2021: true,
browser: true,
node: true,
'jest/globals': true,
},
extends: ['eslint:recommended', 'google'],
plugins: ['jest'],
parserOptions: {
ecmaVersion: 12,
},
rules: {
'max-len': [
'error',
{
code: 200,
ignoreTrailingComments: true,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
'require-jsdoc': 'off',
'quote-props': 'off',
'camelcase': 'off',
'no-empty': 'off',
},
};
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ logs/
package-lock.json
tests.js
config.test
.idea
.editorconfig
4 changes: 4 additions & 0 deletions .husky/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no -- commitlint --edit
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npm run lint
83 changes: 83 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Contributing Guide

Before submitting your contribution, please make sure to take a moment and read through the following guidelines:

- [Pull Request Guidelines](#pull-request-guidelines)
- [Development Setup](#development-setup)
- [Scripts](#scripts)
- [Project Structure](#project-structure)
- [Contributing Tests](#contributing-tests)

## Pull Request Guidelines

- 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.

- Checkout a topic branch from a base branch, e.g. `master`, and merge back against that branch.

- If adding a new feature add accompanying test case.

- It's OK to have multiple small commits as you work on the PR - GitHub can automatically squash them before merging.

- Make sure tests pass!

- Commit messages must follow the [commit message convention](https://github.com/conventional-changelog/commitlint/blob/master/README.md). Commit messages are automatically validated before commit (by invoking [Git Hooks](https://git-scm.com/docs/githooks) via [husky](https://github.com/typicode/husky)).

- No need to worry about code style as long as you have installed the dev dependencies - modified files are automatically formatted with Prettier on commit (by invoking [Git Hooks](https://git-scm.com/docs/githooks) via [husky](https://github.com/typicode/husky)).

## Development Setup

You will need [Node.js](https://nodejs.org) **version 16+**.

After cloning the repo, run:

```bash
$ npm i # install the dependencies of the project
```

A high level overview of tools used:

- [Jest](https://jestjs.io/) for unit testing

## Scripts

### `npm run lint`

The `lint` script runs linter.

```bash
# lint files
$ npm run lint
# fix linter errors
$ npm run lint:fix
```

### `npm run test`

The `test` script simply calls the `jest` binary, so all [Jest CLI Options](https://jestjs.io/docs/en/cli) can be used. Some examples:

```bash
# run all tests
$ npm run test
# run all tests under the runtime-core package
$ npm run test -- runtime-core
# run tests in a specific file
$ npm run test -- fileName
# run a specific test in a specific file
$ npm run test -- fileName -t 'test name'
```

## Project Structure

- **`modules`**: contains logic that handles requests to bounty-bot.

- **`helpers`**: contains utilities shared across the entire codebase.

- **`tests`**: contains tests for the application.

## Contributing Tests

Unit tests are collocated with the code being tested inside directories named `tests`. Consult the [Jest docs](https://jestjs.io/docs/en/using-matchers) and existing test cases for how to write new test specs. Here are some additional guidelines:

- Use the minimal API needed for a test case. For example, if a test can be written without involving the reactivity system or a component, it should be written so. This limits the test's exposure to changes in unrelated parts and makes it more stable.

- Only use platform-specific runtimes if the test is asserting platform-specific behavior.
49 changes: 14 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
ADAMANT Bounty Bot is a software that allows you to carry out bounty campaigns & crypto airdrops, with automatic task verifications and payouts.
ADAMANT Bounty Bot is a software that allows you to carry out bounty campaigns & crypto airdrops, with automatic task verification and payouts.

It is made for crypto projects and communities.
It's made for crypto projects and communities.

The bounty bot:

* Interactive and interesting for users. The bot talks to users in ADAMANT Messenger chat directly
* Works with Twitter campaigns: follow & retweet with comment (quote). You can set up mentions and hashtags.
* Interactive and interesting for users. The bot talks to users in ADAMANT Messenger chat directly.
* Works with Twitter campaigns: follow, retweet & retweet with comment (quote). You can set up mentions and hashtags.
* Set which Twitter accounts are eligible to participate: minimum followers, friends, statuses and lifetime
* Supports ADAMANT campaigns: users will invite other users
* Automatic task verifications and payouts
* Supports payouts in ADM, ETH and ERC-20 tokens
* Automatic task verification and payouts
* Supports payouts in ADM, LSK, ETH and ERC-20 tokens
* Easy to install and configure
* Free and open source
* Stores statistics

Read more: [Carry out a crypto Bounty campaign on ADAMANT platform]().

# Installation

User-friendly instructions: [Carry out a crypto Bounty campaign on ADAMANT platform](https://medium.com/adamant-im/adamants-interactive-bounty-bot-for-cryptocurrency-projects-51fec10f93b9).

## Requirements

* Ubuntu 16 / Ubuntu 18 (other OS had not been tested)
* NodeJS v 8+ (already installed if you have a node on your machine)
* Ubuntu 18, 20, 22 (we didn't test others)
* NodeJS v 14+
* MongoDB ([installation instructions](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/))

## Setup
Expand All @@ -35,37 +36,15 @@ npm i
## Pre-launch tuning

```
cp config.default.json config.json
nano config.json
```

Parameters:

* `passPhrase` <string> The exchange bot's secret phrase for concluding transactions. Obligatory. Bot's ADAMANT address will correspond this passPhrase.
* `node_ADM` <string, array> List of nodes for API work, obligatorily
* `node_ETH` <string, array> List of nodes for Ethereum API work, obligatorily
* `infoservice` <string, array> List of [ADAMANT InfoServices](https://github.com/Adamant-im/adamant-currencyinfo-services) for catching exchange rates, obligatorily
* `socket` <boolean> If to use WebSocket connection. Recommended for better user experience
* `ws_type` <string> Choose socket connection, "ws" or "wss" depending on your server
* `bot_name` <string> Bot's name for notifications
* `slack` <string> Token for Slack alerts for the bot’s administrator. No alerts if not set
* `adamant_notify` <string> ADM address for the bot’s administrator. Recommended
* `known_crypto` <string, array> List of cryptocurrencies bot can work with. Obligatorily
* `erc20` <string, array> List of cryptocurrencies of ERC-20 type. It is necessary to put all known ERC-20 tokens here.

* `twitter_follow` <string, array> List of Twitter account user should follow
* `twitter_retweet` <string, array> List of Twitter posts user should retweet
* `twitter_api` <string, object> Your Twitter API credentials. Get on https://apps.twitter.com/app/new

* `notifyTasksCompleted` <boolean> If you want to receive notifications when user completes Bounty tasks
* `notifyRewardReceived` <boolean> If you want to receive notifications when user receives a Bounty reward
* `rewards` <object, array> List rewards for a Bounty campaign: cryptos and amounts

* `welcome_string` <string> How to reply user in-chat, if first unknown command received
* `help_message` <string> How to reply to */help* command. Recommended to put Bounty rules here
Parameters: See descriptions in config file.

## Launching

You can start the Bot with the `node app` command, but it is recommended to use the process manager for this purpose.
You can start the Bot with the `node app` command, but it's recommended to use the process manager for this purpose.

```
pm2 start --name bountybot app.js
Expand Down
112 changes: 56 additions & 56 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
const notify = require('./helpers/notify');
const db = require('./modules/DB');
const Store = require('./modules/Store');
const checker = require('./modules/checkerTransactions');
const doClearDB = process.argv.includes('clear_db');
const config = require('./modules/configReader');
const txParser = require('./modules/incomingTxsParser');

// Socket connection
const api = require('./modules/api');
api.socket.initSocket({socket: config.socket, wsType: config.ws_type, onNewMessage: txParser, admAddress: Store.user.ADM.address});

setTimeout(init, 5000);

function init() {
require('./helpers/utils/erc20_utils');
require('./server');
require('./modules/checkTwitterFollow');
require('./modules/apiTester');
require('./modules/checkTwitterRetweet');
require('./modules/checkAdamantContacts');
require('./modules/checkAll');
require('./modules/outAddressFetcher');
require('./modules/rewardsPayer');
require('./modules/sentTxValidator');
try {

if (doClearDB) {
console.log('Clearing database..');
db.systemDb.db.drop();
db.incomingTxsDb.db.drop();
db.usersDb.db.drop();
db.paymentsDb.db.drop();
notify(`*${config.notifyName}: database cleared*. Manually stop the Bot now.`, 'info');
} else {

db.systemDb.findOne().then(system => {
if (system) {
Store.lastBlock = system.lastBlock;
} else { // if 1st start
Store.updateLastBlock();
}
checker();
notify(`*${config.notifyName} started* for address _${Store.user.ADM.address}_ (ver. ${Store.version}).`, 'info');
});
}

} catch (e) {
let message = `${config.notifyName} is not started. Error: ${e}`;
if (e.message.includes('findOne')) {
message = `${config.notifyName} is not started. Unable to connect to MongoDB. Check if Mongo server is running and available.`;
}
notify(message, 'error');
setTimeout(() => {process.exit(1);}, 2000);
}
}
const notify = require('./helpers/notify');
const db = require('./modules/DB');
const Store = require('./modules/Store');
const checker = require('./modules/checkerTransactions');
const doClearDB = process.argv.includes('clear_db');
const config = require('./modules/configReader');
const txParser = require('./modules/incomingTxsParser');

// Socket connection
const api = require('./modules/api');
api.socket.initSocket({socket: config.socket, wsType: config.ws_type, onNewMessage: txParser, admAddress: Store.user.ADM.address});

setTimeout(init, 5000);

function init() {
require('./helpers/cryptos/erc20_utils');
require('./server');
require('./modules/checkTwitterFollow');
require('./modules/apiTester');
require('./modules/checkTwitterReqs');
require('./modules/checkTwitterRetweet');
require('./modules/checkAdamantContacts');
require('./modules/checkAll');
require('./modules/outAddressFetcher');
require('./modules/rewardsPayer');
require('./modules/sentTxValidator');
try {
if (doClearDB) {
console.log('Clearing database');
db.systemDb.db.drop();
db.IncomingTxsDb.db.drop();
db.UsersDb.db.drop();
db.PaymentsDb.db.drop();
notify(`*${config.notifyName}: database cleared*. Manually stop the Bot now.`, 'info');
} else {
db.systemDb.findOne().then((system) => {
if (system) {
Store.lastBlock = system.lastBlock;
} else { // if 1st start
Store.updateLastBlock();
}
checker();
notify(`*${config.notifyName} started* for address _${Store.user.ADM.address}_ (ver. ${Store.version}).`, 'info');
});
}
} catch (e) {
let message = `${config.notifyName} is not started. Error: ${e}`;
if (e.message.includes('findOne')) {
message = `${config.notifyName} is not started. Unable to connect to MongoDB. Check if Mongo server is running and available.`;
}
notify(message, 'error');
setTimeout(() => {
process.exit(1);
}, 2000);
}
}
3 changes: 3 additions & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
};
Loading

0 comments on commit 865b909

Please sign in to comment.