├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .husky ├── commit-msg └── pre-commit ├── .prettierignore ├── .prettierrc.js ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── commitlint.config.js ├── examples ├── basic │ └── index.ts ├── getId │ └── index.ts └── socket │ └── index.ts ├── jest.config.js ├── package.json ├── pnpm-lock.yaml ├── src ├── api │ ├── generated.ts │ ├── index.ts │ ├── tests │ │ └── utils.test.ts │ └── utils.ts ├── coins │ ├── btc.ts │ ├── dash.ts │ ├── doge.ts │ ├── eth.ts │ ├── index.ts │ ├── lsk.ts │ └── tests │ │ ├── btc.test.ts │ │ ├── dash.test.ts │ │ ├── doge.test.ts │ │ ├── eth.test.ts │ │ ├── lsk.test.ts │ │ └── mock │ │ └── passphrase.ts ├── helpers │ ├── bignumber.ts │ ├── constants.ts │ ├── encryptor.ts │ ├── healthCheck.ts │ ├── keys.ts │ ├── logger.ts │ ├── tests │ │ ├── keys.test.ts │ │ ├── logger.test.ts │ │ ├── mock-data │ │ │ └── address.ts │ │ ├── time.test.ts │ │ ├── transactions.test.ts │ │ └── validator.test.ts │ ├── time.ts │ ├── transactions │ │ ├── hash.ts │ │ ├── id.ts │ │ ├── index.ts │ │ └── tests │ │ │ └── id.test.ts │ ├── url.ts │ ├── utils.ts │ ├── validator.ts │ └── wsClient.ts └── index.ts ├── tsconfig.json └── types ├── coininfo.d.ts ├── socket-io-client.d.ts └── sodium-browserify-tweetnacl.d.ts /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/", 3 | "overrides": [ 4 | { 5 | "files": ["*.test.ts"], 6 | "rules": { 7 | "@typescript-eslint/no-explicit-any": 0 8 | } 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules/ 3 | logs/ 4 | .idea/ 5 | .vscode/ 6 | test.js 7 | .editorconfig 8 | .DS_Store 9 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx --no -- commitlint --edit 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm run test 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | ...require('gts/.prettierrc.json') 3 | } 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [2.4.0] - 2024-05-30 4 | 5 | ### Fixed 6 | 7 | - Validation of public keys and delegate names for `api.voteForDelegate()` method 8 | 9 | ### Added 10 | 11 | - Check if an address is actually a delegate in `api.voteForDelegate()` 12 | - More validation error messages for `api.voteForDelegate()` 13 | 14 | ## [2.3.1] - 2024-04-26 15 | 16 | ### Fixed 17 | 18 | - A bug when only one random node was checked 19 | - Log messages for health checks 20 | 21 | ## [2.3.0] - 2024-03-01 22 | 23 | ### Added 24 | 25 | - `transformTransactionQuery` function: 26 | 27 | ```ts 28 | const transformed = transformTransactionQuery({ 29 | fromHeight: 7585271, 30 | and: { 31 | toHeight: 7586280, 32 | }, 33 | or: { 34 | senderId: 'U18132012621449491414', 35 | }, 36 | }); 37 | 38 | /** 39 | * { 40 | * and:fromHeight: 7585271, 41 | * and:toHeight: 7586280, 42 | * or:senderId: 'U18132012621449491414' 43 | * } 44 | */ 45 | console.log(transformed); 46 | ``` 47 | 48 | ### Fixed 49 | 50 | - TypeScript: `id` should have `string` type in the methods: `api.getTransaction()`, `api.getQueuedTransaction()`, `api.getUnconfirmedTransaction()` 51 | 52 | - Global installation of packages that use `adamant-api` as its dependency 53 | 54 | - Transaction query methods: 55 | 56 | ```ts 57 | const blocks = await api.getTransactions({ 58 | fromHeight: 7585271, 59 | and: { 60 | toHeight: 7586280, 61 | }, 62 | or: { 63 | senderId: 'U18132012621449491414', 64 | }, 65 | }); 66 | ``` 67 | 68 | ## [2.2.0] - 2023-12-01 69 | 70 | ## Added 71 | 72 | - Export validator utils: 73 | 74 | ```ts 75 | function isPassphrase(passphrase: unknown): passphrase is string; 76 | function isAdmAddress(address: unknown): address is AdamantAddress; 77 | function isAdmPublicKey(publicKey: unknown): publicKey is string; 78 | function isAdmVoteForPublicKey(publicKey: unknown): publicKey is string; 79 | function isAdmVoteForAddress(address: unknown): boolean; 80 | function isAdmVoteForDelegateName( 81 | delegateName: unknown 82 | ): delegateName is string; 83 | function validateMessage( 84 | message: string, 85 | messageType: MessageType = MessageType.Chat 86 | ): {success: false; error: string} | {success: true}; 87 | function isDelegateName(name: unknown): name is string; 88 | function admToSats(amount: number): number; 89 | ``` 90 | 91 | ## [2.1.0] - 2023-11-17 92 | 93 | ### Added 94 | 95 | - `api.initSocket()` now accepts an instance of `WebSocketClient` as an argument: 96 | 97 | ```js 98 | const socket = new WebSocketClient({ 99 | /* ... */ 100 | }); 101 | 102 | api.initSocket(socket); 103 | // instead of 104 | api.socket = socket; 105 | ``` 106 | 107 | - Improved the `encodeMessage()` and `decodeMessage()` functions to accept public keys as Uint8Array or Buffer 108 | 109 | ```js 110 | import {encodeMessage, createKeypairFromPassphrase} from 'adamant-api' 111 | 112 | const {publicKey} = createKeypairFromPassphrase('...') 113 | const message = encodeMessage(,, publicKey) // No need to convert public key to string 114 | ``` 115 | 116 | - `decodeMessage()` allows passing a key pair instead of a passphrase: 117 | 118 | ```js 119 | import {decodeMessage, createKeypairFromPassphrase} from 'adamant-api' 120 | 121 | const keyPair = createKeypairFromPassphrase('...') 122 | const message = decodeMessage(,, keyPair,) // <- It won't create a key pair from passphrase again 123 | ``` 124 | 125 | - TypeScript: Export transaction handlers TypeScript utils: `SingleTransactionHandler`, `AnyTransactionHandler`, `TransactionHandler` 126 | 127 | ### Fixed 128 | 129 | - TypeScript: Fixed typing for `AdamantApiOptions` by adding `LogLevelName` as possible value for `logLevel` property. 130 | 131 | For example, you can now use `'log'` instead of `LogLevel.Log` in TypeScript: 132 | 133 | ```ts 134 | const api = new AdamantApi({/* ... */ logLevel: 'log'}); 135 | ``` 136 | 137 | - TypeScript: Added missing declaration modules to npm that led to the error: 138 | 139 | ``` 140 | Could not find a declaration file for module 'coininfo'. 141 | /// 142 | ``` 143 | 144 | - TypeScript: `amount` property in `ChatTransactionData` (`createChatTransaction()` argument) is now truly optional: 145 | 146 | ```diff 147 | - amount: number | undefined; 148 | + amount?: number; 149 | ``` 150 | 151 | ## [2.0.0] - 2023-10-12 152 | 153 | ### Added 154 | 155 | - **TypeScript support** 156 | 157 | The project was fully rewritten in TypeScript, which means it supports typings now. 158 | 159 | _See [examples](./examples/) directory._ 160 | 161 | - **More API methods** 162 | 163 | Added more API methods: 164 | 165 | ```js 166 | // before 167 | const block = await api.get('blocks/get', {id}); 168 | 169 | // after 170 | const block = await api.getBlock(id); 171 | ``` 172 | 173 | and `post()` method: 174 | 175 | ```js 176 | await api.post('transactions/process', {transaction}); 177 | ``` 178 | 179 | - **getTransactionId()** method 180 | 181 | Pass signed transaction with signature to get a transaction id as a string: 182 | 183 | ```js 184 | import {getTransactionId} from 'adamant-api'; 185 | const id = getTransactionId(signedTransaction); 186 | ``` 187 | 188 | _See [documentation](https://github.com/Adamant-im/adamant-api-jsclient/wiki/Calculating-transaction-id) for more information._ 189 | 190 | ### Fixed 191 | 192 | - **Creating multiple instances** 193 | 194 | Previously, it was not possible to create multiple instances due to the storage of Logger and "Node Manager" data in the modules. 195 | 196 | - **Importing module several times** 197 | 198 | Fixed a bug where importing adamant-api-jsclient caused issues when it was also imported as a dependency. 199 | 200 | ### Changed 201 | 202 | - **API Initialization** 203 | 204 | Now you will create new instances of `adamant-api` using keyword `new`: 205 | 206 | ```js 207 | import {AdamantApi} from 'adamant-api'; 208 | 209 | const api = new AdamantApi({ 210 | nodes: [ 211 | /* ... */ 212 | ], 213 | }); 214 | ``` 215 | 216 | - **Socket Initialization** 217 | 218 | Replace `api.socket.initSocket()` with `api.initSocket()`. 219 | 220 | Use `api.socket.on()` instead of `.initSocket({ onNewMessage() {} })`. 221 | 222 | ```ts 223 | // before 224 | api.socket.initSocket({ 225 | admAddress: 'U1234..', 226 | onNewMessage(transaction) { 227 | // ... 228 | }, 229 | }); 230 | 231 | // after 232 | api.initSocket({admAddress: 'U1234..'}); 233 | 234 | api.socket.on((transaction: AnyTransaction) => { 235 | // ... 236 | }); 237 | ``` 238 | 239 | Or specify `socket` option when initializing API: 240 | 241 | ```ts 242 | // socket.ts 243 | import {WebSocketClient, TransactionType} from 'adamant-api'; 244 | 245 | const socket = new WebSocketClient({admAddress: 'U1234..'}); 246 | 247 | socket.on( 248 | [TransactionType.CHAT_MESSAGE, TransactionType.SEND], 249 | transaction => { 250 | // handle chat messages and transfer tokens transactions 251 | } 252 | ); 253 | 254 | socket.on(TransactionType.VOTE, transaction => { 255 | // handle vote for delegate transaction 256 | }); 257 | 258 | export {socket}; 259 | ``` 260 | 261 | ```ts 262 | // api.ts 263 | import {AdamantApi} from 'adamant-api'; 264 | import {socket} from './socket'; 265 | 266 | export const api = new AdamantApi({ 267 | socket, 268 | nodes: [ 269 | /* ... */ 270 | ], 271 | }); 272 | ``` 273 | 274 | ### Removed 275 | 276 | - `createTransaction()` 277 | 278 | Use `createSendTransaction`, `createStateTransaction`, `createChatTransaction`, `createDelegateTransaction`, `createVoteTransaction` methods instead. 279 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, caste, color, religion, or sexual 10 | identity and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the overall 26 | community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or advances of 31 | any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email address, 35 | without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [INSERT CONTACT METHOD]. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series of 86 | actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or permanent 93 | ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within the 113 | community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.1, available at 119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 120 | 121 | Community Impact Guidelines were inspired by 122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 123 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | Before submitting your contribution, please make sure to take a moment and read through the following guidelines: 4 | 5 | - [Code of Conduct](./CODE_OF_CONDUCT.md) 6 | - [Issue Reporting Guidelines](#issue-reporting-guidelines) 7 | - [Pull Request Guidelines](#pull-request-guidelines) 8 | - [Development Setup](#development-setup) 9 | - [Scripts](#scripts) 10 | - [Project Structure](#project-structure) 11 | - [Contributing Tests](#contributing-tests) 12 | 13 | ## Issue Reporting Guidelines 14 | 15 | - Always use [GitHub Issues](https://github.com/Adamant-im/adamant-api-jsclient/issues) to create new issues. 16 | 17 | ## Pull Request Guidelines 18 | 19 | - 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. 20 | 21 | - Checkout a topic branch from a base branch, e.g. `dev`, and merge back against that branch. 22 | 23 | - If adding a new feature add accompanying test case. 24 | 25 | - It's OK to have multiple small commits as you work on the PR - GitHub can automatically squash them before merging. 26 | 27 | - Make sure tests pass! 28 | 29 | - Commit messages must follow the [commit message convention](https://github.com/angular/angular/blob/68a6a07/CONTRIBUTING.md#commit). Commit messages are automatically validated before commit (by invoking [Git Hooks](https://git-scm.com/docs/githooks) via [husky](https://github.com/typicode/husky)). 30 | 31 | - 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)). 32 | 33 | ## Development Setup 34 | 35 | You will need [Node.js](https://nodejs.org) **version 18+** and [pnpm](https://pnpm.io/). 36 | 37 | After cloning the repo, run: 38 | 39 | ```bash 40 | $ pnpm i # install the dependencies of the project 41 | ``` 42 | 43 | A high level overview of tools used: 44 | 45 | - [Jest](https://jestjs.io) for unit testing 46 | - [gts](https://github.com/google/gts) for code formatting 47 | 48 | ## Scripts 49 | 50 | ### `npm run lint` 51 | 52 | The `lint` script runs linter. 53 | 54 | ```bash 55 | # lint files 56 | $ npm run lint 57 | # fix linter errors 58 | $ npm run fix 59 | ``` 60 | 61 | ### `npm run test` 62 | 63 | The `test` script simply calls the `jest` binary, so all [Jest CLI Options](https://jestjs.io/docs/en/cli) can be used. Some examples: 64 | 65 | ```bash 66 | # run all tests 67 | $ npm run test 68 | 69 | # run all tests under the runtime-core package 70 | $ npm run test -- runtime-core 71 | 72 | # run tests in a specific file 73 | $ npm run test -- fileName 74 | 75 | # run a specific test in a specific file 76 | $ npm run test -- fileName -t 'test name' 77 | ``` 78 | 79 | ### Generating API types 80 | 81 | To generate API types, run the following commands in the [`adamant-schema`](https://github.com/Adamant-im/adamant-schema/)'s master branch with the latest commit: 82 | 83 | ```bash 84 | # build OpenAPI schema 85 | $ npm run bundle 86 | # generate typescript from the schema 87 | $ npx swagger-typescript-api -p ./dist/schema.json -o ./dist -n generated.ts --no-client 88 | ``` 89 | 90 | Then, copy `dist/generated.ts` to `adamant-api-jsclient` at `src/api/generated.ts`. 91 | 92 | ## Project Structure 93 | 94 | - **`src`**: contains the source code 95 | 96 | - **`api`**: contains group of methods and methods for the API. 97 | 98 | - **`genearated.ts`**: contains auto-generated types for API. 99 | 100 | - **`coins`**: contains group of utils for coins. 101 | 102 | - **`helpers`**: contains utilities shared across the entire codebase. 103 | 104 | - **`tests`**: contains tests for the helpers directory. 105 | 106 | ## Contributing Tests 107 | 108 | 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: 109 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ADAMANT JavaScript API library 2 | 3 | ADAMANT JavaScript API is a library intended to interact with ADAMANT blockchain for JavaScript developers. Also [ADAMANT Console](https://github.com/Adamant-im/adamant-console/wiki) and [ADAMANT node Direct API](https://github.com/Adamant-im/adamant/wiki/) are available. 4 | 5 | Features: 6 | 7 | - High reliability 8 | - GET-requests to the blockchain 9 | - Sending tokens 10 | - Sending messages 11 | - Creating a delegate 12 | - Voting for delegates 13 | - Caching public keys 14 | - Encrypting and decrypting of messages 15 | - Forming and signing transactions 16 | - Working with ADM key pairs 17 | - Generating crypto wallets (addresses and keys), bound to ADM account 18 | - Working with ADAMANT epoch time 19 | - Support for WebSocket connections 20 | - Logging warnings, errors, info 21 | 22 | ## Reliability 23 | 24 | JS API shows decentralization in action—if a network node cannot fulfill your request, the library will redirect it to another node, and so on several times. You will get the result and you do not need to think about processing the request. 25 | 26 | Health Check system pings all nodes in the list using [`/status`](https://github.com/Adamant-im/adamant/wiki/API-Specification#get-blockchain-and-network-status) endpoint, and connects to a node with actual height. When the library unable to process request with current node, it forces to re-initialize Health Check. 27 | 28 | ## Usage 29 | 30 | Install library from npm: 31 | 32 | ```bash 33 | npm i adamant-api 34 | ``` 35 | 36 | Initialize the library: 37 | 38 | ```js 39 | const { AdamantApi } = require('adamant-api') 40 | 41 | const nodes = [ 42 | "http://localhost:36666", 43 | "https://endless.adamant.im", 44 | "https://clown.adamant.im", 45 | "http://23.226.231.225:36666", 46 | "http://88.198.156.44:36666", 47 | "https://lake.adamant.im" 48 | ]; 49 | 50 | const api = new AdamantApi({ 51 | nodes, 52 | }); 53 | ``` 54 | 55 | Request example: 56 | 57 | ```js 58 | const response = await api.getBlocks() 59 | 60 | console.log(response.data) 61 | ``` 62 | 63 | ## Documentation 64 | 65 | See [Wiki](https://github.com/Adamant-im/adamant-api-jsclient/wiki) for documentation and usage. 66 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | }; 4 | -------------------------------------------------------------------------------- /examples/basic/index.ts: -------------------------------------------------------------------------------- 1 | import {AdamantApi} from 'adamant-api'; 2 | 3 | const nodes = [ 4 | 'https://endless.adamant.im', 5 | 'https://clown.adamant.im', 6 | 'http://23.226.231.225:36666', 7 | 'http://88.198.156.44:36666', 8 | 'https://lake.adamant.im', 9 | ]; 10 | 11 | const api = new AdamantApi({ 12 | nodes, 13 | }); 14 | 15 | /** 16 | * Make sure we are using active node with least ping 17 | */ 18 | api.onReady(async () => { 19 | /** 20 | * Use API bind to make request, alternative you can use: 21 | * ```js 22 | * const response = await api.get('peers/version'); 23 | * ``` 24 | */ 25 | const response = await api.getNodeVersion(); 26 | 27 | if (!response.success) { 28 | console.log(`Something bad happened: ${response.errorMessage}`); 29 | return; 30 | } 31 | 32 | const {version} = response; 33 | 34 | console.log(`Connected node is using ADAMANT v${version}`); 35 | }); 36 | -------------------------------------------------------------------------------- /examples/getId/index.ts: -------------------------------------------------------------------------------- 1 | import {getTransactionId} from 'adamant-api'; 2 | 3 | const id = getTransactionId({ 4 | type: 8, 5 | amount: 0, 6 | timestamp: 194049840, 7 | asset: { 8 | chat: { 9 | message: '7189aba904138dd1d53948ed1e5b1d18a11ba1910834', 10 | own_message: '8b717d0a9142e697cafd342c8f79f042c47a9e712e8a61b6', 11 | type: 1, 12 | }, 13 | }, 14 | recipientId: 'U12605277787100066317', 15 | senderId: 'U8084717991279447871', 16 | senderPublicKey: 17 | '09c93f2667728c62d2279bbb8df34c3856088290167f557c33594dc212da054a', 18 | signature: 19 | '304a4cb7e11651d576e2c4dffb4100bef5385981807f18c3267c863daf60bd277706e6790157beacf5100c77b6798c4725f2f4e070ca78496ff53a4c2e437f02', 20 | }); 21 | 22 | // Transaction id: 5505818610983968576 23 | console.log(`Transaction id: ${id}`); 24 | -------------------------------------------------------------------------------- /examples/socket/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AdamantApi, 3 | TransactionType, 4 | decodeMessage, 5 | WebSocketClient, 6 | ChatMessageTransaction, 7 | } from 'adamant-api'; 8 | 9 | const nodes = [ 10 | 'https://endless.adamant.im', 11 | 'https://clown.adamant.im', 12 | 'http://23.226.231.225:36666', 13 | 'http://88.198.156.44:36666', 14 | 'https://lake.adamant.im', 15 | ]; 16 | 17 | /** 18 | * ADM address to subscribe to notifications 19 | */ 20 | const admAddress = process.env.ADAMANT_ADDRESS as `U${string}`; 21 | /** 22 | * Pass phrase to decode messages 23 | */ 24 | const passphrase = process.env.PASSPHRASE!; 25 | 26 | const socket = new WebSocketClient({admAddress}); 27 | 28 | function onChatTransaction(transaction: ChatMessageTransaction) { 29 | const {chat} = transaction.asset; 30 | 31 | const decoded = decodeMessage( 32 | chat.message, 33 | transaction.senderPublicKey, 34 | passphrase, 35 | chat.own_message 36 | ); 37 | 38 | console.log( 39 | `Got a new message from ${transaction.senderId}:\n "${decoded}"` 40 | ); 41 | } 42 | 43 | /** 44 | * Handle chat messages only 45 | */ 46 | socket.on(TransactionType.CHAT_MESSAGE, onChatTransaction); 47 | 48 | // or 49 | 50 | // socket.on((transaction: AnyTransaction) => { 51 | // if (transaction.type === TransactionType.CHAT_MESSAGE) { 52 | // console.log(transaction); 53 | // } 54 | // }); 55 | 56 | setTimeout(() => { 57 | console.log('the handler has been removed'); 58 | /** 59 | * Remove the handler from all types 60 | */ 61 | socket.off(onChatTransaction); 62 | }, 60 * 1000); 63 | 64 | const api = new AdamantApi({ 65 | nodes, 66 | socket, 67 | }); 68 | 69 | export default api; 70 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest').JestConfigWithTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | }; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adamant-api", 3 | "version": "2.4.0", 4 | "description": "JavaScript API library for the ADAMANT Blockchain", 5 | "keywords": [ 6 | "adm", 7 | "adamant", 8 | "blockchain", 9 | "messenger", 10 | "chat", 11 | "decentralized messenger", 12 | "anonymous messenger", 13 | "secure messenger", 14 | "wallet", 15 | "crypto wallet", 16 | "private keys", 17 | "communication", 18 | "decentralized", 19 | "decentralization", 20 | "anonymous", 21 | "anonymity", 22 | "secure", 23 | "encrypted", 24 | "encryption", 25 | "crypto", 26 | "cryptocurrency", 27 | "bitcoin", 28 | "ethereum" 29 | ], 30 | "homepage": "https://github.com/Adamant-im/adamant-api-jsclient#readme", 31 | "bugs": { 32 | "url": "https://github.com/Adamant-im/adamant-api-jsclient/issues" 33 | }, 34 | "repository": { 35 | "type": "git", 36 | "url": "git+https://github.com/Adamant-im/adamant-api-jsclient.git" 37 | }, 38 | "license": "GPL-3.0", 39 | "author": "ADAMANT Foundation (https://adamant.im)", 40 | "main": "dist/index.js", 41 | "src": "src/index.ts", 42 | "types": "dist/index.d.ts", 43 | "files": [ 44 | "dist/", 45 | "types/" 46 | ], 47 | "scripts": { 48 | "test": "jest", 49 | "lint": "gts lint", 50 | "prepare": "husky install", 51 | "clean": "gts clean", 52 | "compile": "tsc", 53 | "fix": "gts fix", 54 | "pretest": "npm run compile", 55 | "posttest": "npm run lint" 56 | }, 57 | "dependencies": { 58 | "@liskhq/lisk-cryptography": "4.1.0", 59 | "axios": "^1.7.2", 60 | "bignumber.js": "^9.1.2", 61 | "bip39": "^3.1.0", 62 | "bitcoinjs-lib": "^6.1.5", 63 | "bytebuffer": "^5.0.1", 64 | "coininfo": "^5.2.1", 65 | "ecpair": "^2.1.0", 66 | "ed2curve": "^0.3.0", 67 | "ethereumjs-util": "^7.1.5", 68 | "hdkey": "^2.1.0", 69 | "pbkdf2": "^3.1.2", 70 | "socket.io-client": "^4.7.5", 71 | "sodium-browserify-tweetnacl": "^0.2.6", 72 | "tiny-secp256k1": "^2.2.3", 73 | "tweetnacl": "^1.0.3" 74 | }, 75 | "devDependencies": { 76 | "@commitlint/cli": "^19.3.0", 77 | "@commitlint/config-conventional": "^19.2.2", 78 | "@types/bytebuffer": "^5.0.49", 79 | "@types/hdkey": "^2.0.3", 80 | "@types/ed2curve": "^0.2.4", 81 | "@types/jest": "^29.5.12", 82 | "@types/node": "20.12.13", 83 | "@types/pbkdf2": "^3.1.2", 84 | "eslint": "^8.54.0", 85 | "eslint-config-google": "^0.14.0", 86 | "eslint-plugin-jest": "^28.5.0", 87 | "husky": "^9.0.11", 88 | "jest": "^29.7.0", 89 | "prettier": "^3.2.5", 90 | "ts-jest": "^29.1.4", 91 | "gts": "^5.3.0", 92 | "typescript": "~5.1.0" 93 | }, 94 | "publishConfig": { 95 | "access": "public" 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/api/generated.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | /* tslint:disable */ 3 | /* 4 | * --------------------------------------------------------------- 5 | * ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ## 6 | * ## ## 7 | * ## AUTHOR: acacode ## 8 | * ## SOURCE: https://github.com/acacode/swagger-typescript-api ## 9 | * --------------------------------------------------------------- 10 | */ 11 | 12 | /** @example {"account":{"address":"U777355171330060015","unconfirmedBalance":"4509718944753","balance":"4509718944753","publicKey":"a9407418dafb3c8aeee28f3263fd55bae0f528a5697a9df0e77e6568b19dfe34","unconfirmedSignature":0,"secondSignature":0,"secondPublicKey":null,"multisignatures":[],"u_multisignatures":[]},"success":true,"nodeTimestamp":58030181} */ 13 | export interface GetAccountInfoResponseDto { 14 | account: AccountDto; 15 | success: boolean; 16 | nodeTimestamp: number; 17 | } 18 | 19 | /** @example {"balance":"4509718944753","unconfirmedBalance":"4509718944753","success":true,"nodeTimestamp":58043820} */ 20 | export interface GetAccountBalanceResponseDto { 21 | /** @format int64 */ 22 | balance: string; 23 | /** @format int64 */ 24 | unconfirmedBalance: string; 25 | success: boolean; 26 | nodeTimestamp: number; 27 | } 28 | 29 | /** @example {"publicKey":"a9407418dafb3c8aeee28f3263fd55bae0f528a5697a9df0e77e6568b19dfe34","balance":"4509718944753","unconfirmedBalance":"4509718944753"} */ 30 | export interface GetAccountPublicKeyResponseDto { 31 | /** 256 bit public key of ADAMANT address in hex format */ 32 | publicKey: PublicKey; 33 | success: boolean; 34 | nodeTimestamp: number; 35 | } 36 | 37 | /** @example {"publicKey":"a9407418dafb3c8aeee28f3263fd55bae0f528a5697a9df0e77e6568b19dfe34","balance":"4509718944753","unconfirmedBalance":"4509718944753"} */ 38 | export interface CreateNewAccountRequestBody { 39 | /** 256 bit public key of ADAMANT address in hex format */ 40 | publicKey: PublicKey; 41 | success: boolean; 42 | nodeTimestamp: number; 43 | } 44 | 45 | /** @example {"account":{"address":"U4697606961271319613","unconfirmedBalance":"0","balance":"0","publicKey":"bee368cc0ce2974adcbcc97e649ac18a031492a579034abed5f77d667001d450","unconfirmedSignature":0,"secondSignature":0,"secondPublicKey":null,"multisignatures":null,"u_multisignatures":null},"success":true,"nodeTimestamp":63205623} */ 46 | export interface CreateNewAccountResponseDto { 47 | account: AccountDto; 48 | success: boolean; 49 | nodeTimestamp: number; 50 | } 51 | 52 | export interface GetBlockInfoResponseDto { 53 | block: BlockInfoDto; 54 | success: boolean; 55 | nodeTimestamp: number; 56 | } 57 | 58 | export interface GetBlocksResponseDto { 59 | blocks: BlockInfoDto[]; 60 | success: boolean; 61 | nodeTimestamp: number; 62 | } 63 | 64 | export interface GetChatRoomsResponseDto { 65 | chats: { 66 | lastTransaction?: TokenTransferTransaction | ChatMessageTransaction; 67 | participants?: ChatParticipant[]; 68 | }[]; 69 | success: boolean; 70 | nodeTimestamp: number; 71 | } 72 | 73 | export interface GetChatMessagesResponseDto { 74 | messages: (TokenTransferTransaction | ChatMessageTransaction)[]; 75 | participants: ChatParticipant[]; 76 | success: boolean; 77 | nodeTimestamp: number; 78 | } 79 | 80 | export interface GetChatTransactionsResponseDto { 81 | transactions: ChatMessageTransaction[]; 82 | /** Number in string format */ 83 | count: string; 84 | success: boolean; 85 | nodeTimestamp: number; 86 | } 87 | 88 | export interface CreateNewChatMessageRequestBody { 89 | transaction: RegisterChatMessageTransaction; 90 | } 91 | 92 | /** @example {"success":true,"nodeTimestamp":63205623,"transactionId":"2515012750420367858"} */ 93 | export interface CreateNewChatMessageResponseDto { 94 | success: boolean; 95 | nodeTimestamp: number; 96 | transactionId: string; 97 | } 98 | 99 | export interface GetDelegatesResponseDto { 100 | delegates: DelegateDto[]; 101 | /** @example 254 */ 102 | totalCount: number; 103 | /** @example true */ 104 | success: boolean; 105 | /** @example 61762271 */ 106 | nodeTimestamp: number; 107 | } 108 | 109 | export interface GetDelegateResponseDto { 110 | delegate: DelegateDto; 111 | /** @example true */ 112 | success: boolean; 113 | /** @example 61762271 */ 114 | nodeTimestamp: number; 115 | } 116 | 117 | export type RegisterDelegateRequestBody = RegisterNewDelegateTransaction; 118 | 119 | export interface RegisterDelegateResponseDto { 120 | transaction: RegisterDelegateTransactionDto; 121 | /** @example true */ 122 | success: boolean; 123 | /** @example 61762271 */ 124 | nodeTimestamp: number; 125 | } 126 | 127 | export interface SearchDelegateResponseDto { 128 | delegates: SearchDelegateDto[]; 129 | /** @example true */ 130 | success: boolean; 131 | /** @example 61762271 */ 132 | nodeTimestamp: number; 133 | } 134 | 135 | export interface GetDelegatesCountResponseDto { 136 | /** @example 255 */ 137 | count: number; 138 | /** @example true */ 139 | success: boolean; 140 | /** @example 61762271 */ 141 | nodeTimestamp: number; 142 | } 143 | 144 | export interface GetDelegateStatsResponseDto { 145 | /** 146 | * Total sum of fees forged by delegate 147 | * @example "586039475511" 148 | */ 149 | fees: string; 150 | /** 151 | * Total sum of rewards made by delegate 152 | * @example "3943485000000" 153 | */ 154 | rewards: string; 155 | /** 156 | * Total sum of forged tokens 157 | * @example "4529524475511" 158 | */ 159 | forged: string; 160 | /** @example true */ 161 | success: boolean; 162 | /** @example 61762271 */ 163 | nodeTimestamp: number; 164 | } 165 | 166 | export interface GetNextForgersResponseDto { 167 | /** 168 | * Array of next forgers public keys 169 | * @example ["677c6db63548c99674fed0571da522a6a9569d0c1da9669734a3625645519641","150d638714f65845b50f1ff58f3da2c2baa3a1dc8bf59a9884c10da5a8e951c6"] 170 | */ 171 | delegates: string[]; 172 | /** 173 | * Current slot number 174 | * @example 11610423 175 | */ 176 | currentSlot: number; 177 | /** 178 | * Current blockchain height 179 | * @example 10146268 180 | */ 181 | currentBlock: number; 182 | /** 183 | * Current block slot number 184 | * @example 11610422 185 | */ 186 | currentBlockSlot: number; 187 | /** @example true */ 188 | success: boolean; 189 | /** @example 61762271 */ 190 | nodeTimestamp: number; 191 | } 192 | 193 | export interface GetVotersResponseDto { 194 | accounts: VoterDto[]; 195 | /** @example true */ 196 | success: boolean; 197 | /** @example 61762271 */ 198 | nodeTimestamp: number; 199 | } 200 | 201 | export interface GetAccountVotesResponseDto { 202 | /** List of delegates account voted for. */ 203 | delegates: DelegateDto[]; 204 | /** @example true */ 205 | success: boolean; 206 | /** @example 61762271 */ 207 | nodeTimestamp: number; 208 | } 209 | 210 | export type RegisterVotesRequestBody = RegisterVoteForDelegateTransaction; 211 | 212 | export interface RegisterVotesResponseDto { 213 | transaction: RegisterVotesTransactionDto; 214 | /** @example true */ 215 | success: boolean; 216 | /** @example 61762271 */ 217 | nodeTimestamp: number; 218 | } 219 | 220 | export interface GetPeersResponseDto { 221 | peers: PeerDto[]; 222 | success: boolean; 223 | nodeTimestamp: number; 224 | } 225 | 226 | /** @example {"loaded":true,"now":10144343,"blocksCount":0,"success":true,"nodeTimestamp":58052355} */ 227 | export interface GetLoadingStatusResponseDto { 228 | loaded: boolean; 229 | now: number; 230 | blocksCount: number; 231 | success: boolean; 232 | nodeTimestamp: number; 233 | } 234 | 235 | /** @example {"success":true,"nodeTimestamp":58052355,"syncing":false,"blocks":0,"height":10146332,"broadhash":"09f2f5614cf7209979dc1df2dd92d16aade904dae6c9b68bccaeb234647b3c18","consensus":94.32} */ 236 | export interface GetSyncStatusResponseDto { 237 | success: boolean; 238 | nodeTimestamp: number; 239 | syncing: boolean; 240 | blocks: number; 241 | height: number; 242 | broadhash: string; 243 | consensus: number; 244 | } 245 | 246 | /** @example {"success":true} */ 247 | export interface GetPingStatusResponseDto { 248 | success: boolean; 249 | } 250 | 251 | export type GetNodeVersionResponseDto = NodeVersion & { 252 | /** @example true */ 253 | success: boolean; 254 | /** @example 58052984 */ 255 | nodeTimestamp: number; 256 | }; 257 | 258 | /** @example {"success":true,"nodeTimestamp":58052355,"broadhash":"e1aedd2818679c174e3f6e31891c34f4069927f33f145e1b81fe5d978733e794"} */ 259 | export interface GetBroadhashResponseDto { 260 | success: boolean; 261 | nodeTimestamp: number; 262 | /** Broadhash is established as an aggregated rolling hash of the past five blocks present in the database */ 263 | broadhash: string; 264 | } 265 | 266 | /** @example {"success":true,"nodeTimestamp":58646306,"epoch":"2017-09-02T17:00:00.000Z"} */ 267 | export interface GetEpochResponseDto { 268 | success: boolean; 269 | nodeTimestamp: number; 270 | /** Time when blockchain epoch starts. Value `2017-09-02T17:00:00.000Z` is for mainnet. */ 271 | epoch: string; 272 | } 273 | 274 | /** @example {"success":true,"nodeTimestamp":58646306,"height":10145318} */ 275 | export interface GetHeightResponseDto { 276 | success: boolean; 277 | nodeTimestamp: number; 278 | /** Current node height. */ 279 | height: number; 280 | } 281 | 282 | /** @example {"success":true,"nodeTimestamp":58646306,"fee":50000000} */ 283 | export interface GetTokenTransferFeeResponseDto { 284 | success: boolean; 285 | nodeTimestamp: number; 286 | /** Current fee value for `type 0` (token transfer) transactions. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). */ 287 | fee: number; 288 | } 289 | 290 | export interface GetTransactionTypesFeesResponseDto { 291 | /** @example true */ 292 | success: boolean; 293 | /** @example 58646306 */ 294 | nodeTimestamp: number; 295 | fees: TransactionTypesFeesDto; 296 | } 297 | 298 | /** @example {"success":true,"nodeTimestamp":58646306,"nethash":"bd330166898377fb28743ceef5e43a5d9d0a3efd9b3451fb7bc53530bb0a6d64"} */ 299 | export interface GetNethashResponseDto { 300 | success: boolean; 301 | nodeTimestamp: number; 302 | /** The `nethash` describes e.g. the Mainnet or the Testnet, that the node is connecting to. */ 303 | nethash: string; 304 | } 305 | 306 | /** @example {"success":true,"nodeTimestamp":58646306,"milestone":1} */ 307 | export interface GetMilestoneResponseDto { 308 | success: boolean; 309 | nodeTimestamp: number; 310 | /** Current slot height, which determines reward a delegate will get for forging a block. */ 311 | milestone: number; 312 | } 313 | 314 | /** @example {"success":true,"nodeTimestamp":58646306,"reward":45000000} */ 315 | export interface GetRewardResponseDto { 316 | success: boolean; 317 | nodeTimestamp: number; 318 | /** The reward a delegate will get for forging a block. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). Depends on the slot height. */ 319 | reward: number; 320 | } 321 | 322 | /** @example {"success":true,"nodeTimestamp":58646306,"supply":10198038140000000} */ 323 | export interface GetTokensTotalSupplyResponseDto { 324 | success: boolean; 325 | nodeTimestamp: number; 326 | /** Total current supply of ADM tokens in the network. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). Total supply increases with every new forged block. */ 327 | supply: number; 328 | } 329 | 330 | export type GetNetworkInfoResponseDto = NetworkStatus & { 331 | success: boolean; 332 | nodeTimestamp: number; 333 | }; 334 | 335 | export interface GetNodeStatusResponseDto { 336 | /** @example true */ 337 | success: boolean; 338 | /** @example 58052984 */ 339 | nodeTimestamp: number; 340 | network: NetworkStatus; 341 | version: NodeVersion; 342 | wsClient: WsClient; 343 | } 344 | 345 | export interface GetKVSResponseDto { 346 | transactions: KVSTransaction[]; 347 | /** 348 | * Integer in string format 349 | * @example "1" 350 | */ 351 | count: string; 352 | /** @example true */ 353 | success: boolean; 354 | /** @example 63647706 */ 355 | nodeTimestamp: number; 356 | } 357 | 358 | export interface SetKVSRequestBody { 359 | transaction: RegisterKVSTransaction; 360 | } 361 | 362 | /** @example {"success":true,"nodeTimestamp":63410860,"transactionId":"3888802408802922744"} */ 363 | export interface SetKVSResponseDto { 364 | success: boolean; 365 | nodeTimestamp: number; 366 | transactionId: string; 367 | } 368 | 369 | export interface GetTransactionsResponseDto { 370 | transactions: AnyTransaction[]; 371 | /** 372 | * Integer in string format 373 | * @example "1" 374 | */ 375 | count: string; 376 | /** @example true */ 377 | success: boolean; 378 | /** @example 63647706 */ 379 | nodeTimestamp: number; 380 | } 381 | 382 | export interface GetTransactionByIdResponseDto { 383 | transaction: AnyTransaction; 384 | /** @example true */ 385 | success: boolean; 386 | /** @example 63647706 */ 387 | nodeTimestamp: number; 388 | } 389 | 390 | /** @example {"success":true,"nodeTimestamp":59979539,"confirmed":256953,"unconfirmed":44,"queued":4,"multisignature":0} */ 391 | export interface GetTransactionsCountResponseDto { 392 | success: boolean; 393 | nodeTimestamp: number; 394 | confirmed: number; 395 | unconfirmed: number; 396 | queued: number; 397 | multisignature: number; 398 | } 399 | 400 | export interface GetQueuedTransactionsResponseDto { 401 | transactions: QueuedTransaction[]; 402 | /** 403 | * Integer in string format 404 | * @example "1" 405 | */ 406 | count: string; 407 | /** @example true */ 408 | success: boolean; 409 | /** @example 63647706 */ 410 | nodeTimestamp: number; 411 | } 412 | 413 | export interface GetQueuedTransactionByIdResponseDto { 414 | transaction: QueuedTransaction; 415 | /** @example true */ 416 | success: boolean; 417 | /** @example 63647706 */ 418 | nodeTimestamp: number; 419 | } 420 | 421 | export interface GetUnconfirmedTransactionsResponseDto { 422 | transactions: QueuedTransaction[]; 423 | /** 424 | * Integer in string format 425 | * @example "1" 426 | */ 427 | count: string; 428 | /** @example true */ 429 | success: boolean; 430 | /** @example 63647706 */ 431 | nodeTimestamp: number; 432 | } 433 | 434 | export interface GetUnconfirmedTransactionByIdResponseDto { 435 | transaction: QueuedTransaction; 436 | /** @example true */ 437 | success: boolean; 438 | /** @example 63647706 */ 439 | nodeTimestamp: number; 440 | } 441 | 442 | export interface TransferTokenRequestBody { 443 | transaction: RegisterTokenTransferTransaction; 444 | } 445 | 446 | export interface TransferTokenResponseDto { 447 | /** @example "6146865104403680934" */ 448 | transactionId: string; 449 | /** @example true */ 450 | success: boolean; 451 | /** @example 63647706 */ 452 | nodeTimestamp: number; 453 | } 454 | 455 | export interface RegisterTransactionRequestBody { 456 | transaction: RegisterAnyTransaction; 457 | } 458 | 459 | export interface RegisterTransactionResponseDto { 460 | /** @example "6146865104403680934" */ 461 | transactionId: string; 462 | /** @example true */ 463 | success: boolean; 464 | /** @example 63647706 */ 465 | nodeTimestamp: number; 466 | } 467 | 468 | /** 469 | * 256 bit public key of ADAMANT address in hex format 470 | * @example "ef5e78a3d02e6d82f4ac0c5b8923c1b86185bd17c27c9ac027c20ec62db79a84" 471 | */ 472 | export type PublicKey = string; 473 | 474 | export interface AccountDto { 475 | address: string; 476 | /** @format int64 */ 477 | unconfirmedBalance: string; 478 | /** @format int64 */ 479 | balance: string; 480 | /** 256 bit public key of ADAMANT address in hex format */ 481 | publicKey: PublicKey; 482 | unconfirmedSignature: number; 483 | secondSignature: number; 484 | secondPublicKey: string | null; 485 | /** @example [] */ 486 | multisignatures: string[]; 487 | /** @example [] */ 488 | u_multisignatures: string[]; 489 | } 490 | 491 | /** @example {"id":"11114690216332606721","version":0,"timestamp":61741820,"height":10873829,"previousBlock":"11483763337863654141","numberOfTransactions":1,"totalAmount":10000000,"totalFee":50000000,"reward":45000000,"payloadLength":117,"payloadHash":"f7c0fa338a3a848119cad999d8035ab3fcb3d274a4555e141ebeb86205e41345","generatorPublicKey":"134a5de88c7da1ec71e75b5250d24168c6c6e3965ff16bd71497bd015d40ea6a","generatorId":"U3238410389688281135","blockSignature":"18607b15417a6b0a56b4c74cacd713ad7a10df16ec3ab45a697fa72b6f811f9213d895b7e0fbca71cf74323d60148d0991668e5368386408f4d841496ed2280d","confirmations":1093,"totalForged":"95000000"} */ 492 | export interface BlockInfoDto { 493 | /** @format int64 */ 494 | id: string; 495 | version: number; 496 | timestamp: number; 497 | height: number; 498 | /** @format int64 */ 499 | previousBlock: string; 500 | numberOfTransactions: number; 501 | totalAmount: number; 502 | totalFee: number; 503 | reward: number; 504 | payloadLength: number; 505 | payloadHash: string; 506 | generatorId: string; 507 | blockSignature: string; 508 | confirmations: number; 509 | /** @format int64 */ 510 | totalForged: string; 511 | } 512 | 513 | export interface BaseTransaction { 514 | id: string; 515 | height: number; 516 | blockId: string; 517 | /** 518 | * Type of transaction. See [Transaction Types](https://github.com/Adamant-im/adamant/wiki/Transaction-Types). 519 | * @min 0 520 | * @max 9 521 | * @example 0 522 | */ 523 | type: number; 524 | block_timestamp: number; 525 | timestamp: number; 526 | senderPublicKey: string; 527 | senderId: string; 528 | recipientId: string; 529 | recipientPublicKey: string; 530 | /** 531 | * Amount to transfer, 8 decimal points (100000000 equals to 1 ADM). For non-transfer transactions must be `0` 532 | * @format int64 533 | */ 534 | amount: number; 535 | /** Fee for operation. Depends on [Transaction Type](https://github.com/Adamant-im/adamant/wiki/Transaction-Types) */ 536 | fee: number; 537 | signature: string; 538 | signatures: string[]; 539 | confirmations: number; 540 | /** @example {} */ 541 | asset: object; 542 | } 543 | 544 | /** 545 | * An empty object 546 | * @example {} 547 | */ 548 | export type TokenTransferAsset = object; 549 | 550 | /** @example {"id":16682447412632443000,"height":10527806,"blockId":2635215585577611300,"type":0,"block_timestamp":59979295,"timestamp":59979276,"senderPublicKey":"632816f2c44a08f282e85532443d73286cadc6d9820d5d25c9d50d8e01c668e0","senderId":"U17362714543155685887","recipientId":"U17819800352812315500","recipientPublicKey":"28994b2cd075fd442e6ce78fa8c07966ed122932ff07411fed3c918e495586e2","amount":100000000,"fee":50000000,"signature":"1db7e9111eaca790b73d51c32572739c46fcba3962aff55ca47ecf9a8c9fcb82c323de39ed60bc87d81a1245d43b5351b9dd44ad70128d78536250168b64c408","signatures":[],"confirmations":18431929,"asset":{}} */ 551 | export type TokenTransferTransaction = BaseTransaction & { 552 | /** 553 | * Always equal to `0` 554 | * @example 0 555 | */ 556 | type: 0; 557 | /** An empty object */ 558 | asset: TokenTransferAsset; 559 | }; 560 | 561 | /** @example {"chat":{"message":"748e4e9cffc969dfa4c1d7b9b708cb171c9e","own_message":"96904970891b838c9a3ab1b9a6f31ec194ec94ffaa95d0cd","type":1}} */ 562 | export interface ChatMessageAsset { 563 | chat: { 564 | /** Encrypted message */ 565 | message: string; 566 | /** Nonce */ 567 | own_message: string; 568 | /** Type of chat message (1 - Basic Encrypted Message, 2 - Rich Content Message, 3 - Signal Message). See details https://github.com/Adamant-im/adamant/wiki/Message-Types */ 569 | type: 1 | 2 | 3; 570 | }; 571 | } 572 | 573 | /** @example {"id":17242227802580636000,"height":7583081,"blockId":10363608465961390000,"type":8,"block_timestamp":64874935,"timestamp":64874929,"senderPublicKey":"b34d48d8d70b3a91f766df34789abf0cad62da7207e171d997508a460217c5d3","senderId":"U13267906643444995032","recipientId":"U9203183357885757380","recipientPublicKey":"741d3d1f52e609eef981e9ab370ec1e7c3ff70cafad94691937a2bb6d84bbff2","amount":0,"fee":100000,"signature":"8803346cf43457aba3480311ee489706ec66493fa043c4d1732682eb86e88d96f36a7e87c1d0d00dd3963f75e763e5554df402ee0aa79bd59bd55185a6e49a03","signatures":[],"confirmations":23229462,"asset":{"chat":{"message":"2f045f1d4a5198843999e2948b0cc78806","own_message":"a7cd3fa21e543dcc9f0564387d83c4d862137a2da37f29d4","type":1}}} */ 574 | export type ChatMessageTransaction = BaseTransaction & { 575 | /** 576 | * Always equal to `8` 577 | * @example 8 578 | */ 579 | type: 8; 580 | asset: ChatMessageAsset; 581 | }; 582 | 583 | /** 584 | * ADAMANT address 585 | * @example "U8916295525136600565" 586 | */ 587 | export type AdamantAddress = string; 588 | 589 | export interface ChatParticipant { 590 | /** ADAMANT address */ 591 | address: AdamantAddress; 592 | /** 256 bit public key of ADAMANT address in hex format */ 593 | publicKey: PublicKey; 594 | } 595 | 596 | /** @example {"type":0,"amount":0,"senderId":"U14236667426471084862","senderPublicKey":"8cd9631f9f634a361ea3b85cbd0df882633e39e7d26d7bc615bbcf75e41524ef","signature":"b3982d603be8f0246fa663e9f012bf28b198cd28f82473db1eb4a342d890f7a2a2c1845db8d256bb5bce1e64a9425822a91e10bf960a2e0b55e20b4841e4ae0b","timestamp":63228852} */ 597 | export interface RegisterTransactionBase { 598 | type: number; 599 | amount: number; 600 | senderId: string; 601 | senderPublicKey: string; 602 | signature: string; 603 | timestamp: number; 604 | } 605 | 606 | export type RegisterChatMessageTransaction = RegisterTransactionBase & { 607 | /** 608 | * Always equal to `8` 609 | * @example 8 610 | */ 611 | type: 8; 612 | recipientId: string; 613 | asset: ChatMessageAsset; 614 | }; 615 | 616 | /** @example {"username":"galaxy","address":"U17457189553820283321","publicKey":"7e26562594685ba12c0bb99ae80692947828afb71962d54634795d78b3ea7023","vote":"248994436803629","votesWeight":"83910064952101","producedblocks":269879,"missedblocks":567,"rate":10,"rank":10,"approval":0.76,"productivity":99.79} */ 617 | export interface DelegateDto { 618 | /** Unique delegate's nickname */ 619 | username: string; 620 | /** Delegate address */ 621 | address: string; 622 | /** Delegate Public Key */ 623 | publicKey: string; 624 | /** Vote weight (obsolete, not used) */ 625 | vote: string; 626 | /** Vote weight (Fair Delegate System) */ 627 | votesWeight: string; 628 | /** Count of produced blocks */ 629 | producedlocks?: number; 630 | /** Count of missed blocks */ 631 | missedblocks: number; 632 | /** Current position in the Delegates List */ 633 | rate: number; 634 | /** Current position in the Delegates List */ 635 | rank: number; 636 | /** Share of votes of all votes in the system */ 637 | approval: number; 638 | /** Productivity / Uptime of a delegate. If `0`, delegate is not active now */ 639 | productivity: number; 640 | } 641 | 642 | /** @example {"type":2,"amount":0,"senderId":"U3031563782805250428","senderPublicKey":"a339974effc141f302bd3589c603bdc9468dd66bcc424b60025b36999eb69ca3","signature":"c2e4a3ef7f0d363611a2b22b96feff269f1a0cbb61741a2ce55756bb9324826092fd9bff6348145e3cc384c097f101a493b9136da5236292ecf8b1ed6657dd01","timestamp":166805250,"asset":{"delegate":{"username":"kpeo","publicKey":"a339974effc141f302bd3589c603bdc9468dd66bcc424b60025b36999eb69ca3"}}} */ 643 | export type RegisterNewDelegateTransaction = RegisterTransactionBase & { 644 | /** 645 | * Should be always equal to `2` 646 | * @example 2 647 | */ 648 | type: 2; 649 | asset: { 650 | delegate: { 651 | username: string; 652 | /** 256 bit public key of ADAMANT address in hex format */ 653 | publicKey: PublicKey; 654 | }; 655 | }; 656 | }; 657 | 658 | export interface QueuedTransaction { 659 | /** @example "U14236667426471084862" */ 660 | recipientId: string; 661 | /** @example 0 */ 662 | amount: number; 663 | /** 664 | * See [Transaction Types](https://github.com/Adamant-im/adamant/wiki/Transaction-Types) 665 | * @min 0 666 | * @max 9 667 | * @example 3 668 | */ 669 | type: number; 670 | /** @example "U14236667426471084862" */ 671 | senderId: string; 672 | /** @example "8cd9631f9f634a361ea3b85cbd0df882633e39e7d26d7bc615bbcf75e41524ef" */ 673 | senderPublicKey: string; 674 | /** @example 63394407 */ 675 | timestamp?: number; 676 | /** @example "7f4f5d240fc66da1cbdb3fe291d6fcec006848236355aebe346fcd1e3ba500caeac1ed0af6f3d7f912a889a1bbedc1d7bab17b6ebd36386b81df78189ddf7c07" */ 677 | signature: string; 678 | /** @example "13616514419605573351" */ 679 | id: string; 680 | /** @example 5000000000 */ 681 | fee: number; 682 | /** @example 1 */ 683 | relays: number; 684 | /** 685 | * Date and time in ISO 8601 format 686 | * @example "2019-09-06T10:33:28.054Z" 687 | */ 688 | receivedAt: string; 689 | } 690 | 691 | /** @example {"delegate":{"address":"U3031563782805250428","username":"kpeo","publicKey":"a339974effc141f302bd3589c603bdc9468dd66bcc424b60025b36999eb69ca3"}} */ 692 | export interface RegisterDelegateAsset { 693 | delegate: { 694 | /** ADAMANT address */ 695 | address: AdamantAddress; 696 | username: string; 697 | /** 256 bit public key of ADAMANT address in hex format */ 698 | publicKey: PublicKey; 699 | }; 700 | } 701 | 702 | export type RegisterDelegateTransactionDto = QueuedTransaction & { 703 | asset: RegisterDelegateAsset; 704 | /** 705 | * Always equal to `2` 706 | * @example 2 707 | */ 708 | type: 2; 709 | /** 710 | * Always equal to `300000000000` 711 | * @example 300000000000 712 | */ 713 | fee?: 300000000000; 714 | }; 715 | 716 | export type SearchDelegateDto = DelegateDto & { 717 | /** 718 | * Number of accounts who voted for delegate 719 | * @example 12 720 | */ 721 | voters_cnt: number; 722 | /** 723 | * Epoch timestamp of when delegate was registered 724 | * @example 45523238 725 | */ 726 | register_timestamp: number; 727 | }; 728 | 729 | /** @example {"username":"leg","address":"U12609717384103730908","publicKey":"559418798f67a81b7f893aa8eab1218b9838a6b0bcd2bc8968c6d490ae0d5d77","balance":"506697"} */ 730 | export interface VoterDto { 731 | /** Voter's delegate username. `null` if address is not a delegate. */ 732 | username: string | null; 733 | /** Voter's ADAMANT address */ 734 | address: string; 735 | /** Voter's ADAMANT public key */ 736 | publicKey: string; 737 | /** ADM balance of voter's ADAMANT wallet. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000) */ 738 | balance: string; 739 | } 740 | 741 | /** @example {"votes":["-c0c580c3fb89409f32181fef58935f286f0c1bbf61bd727084ed915b3a4bc95b","ac903ab58135cd5f0613a929d876953214d224034b73c33e63bc153d669447f4"]} */ 742 | export interface VoteForDelegateAsset { 743 | votes: string[]; 744 | } 745 | 746 | export type RegisterVoteForDelegateTransaction = RegisterTransactionBase & { 747 | asset: VoteForDelegateAsset; 748 | /** 749 | * ADAMANT address of account who votes. Same as `senderId` 750 | * @example "U14236667426471084862" 751 | */ 752 | recipientId: string; 753 | /** 754 | * Should be always equal to `3` 755 | * @example 3 756 | */ 757 | type: 3; 758 | /** 759 | * ADAMANT address of account who votes. Same as `recipientId` 760 | * @example "U14236667426471084862" 761 | */ 762 | senderId: string; 763 | }; 764 | 765 | export type RegisterVotesTransactionDto = QueuedTransaction & { 766 | asset: VoteForDelegateAsset; 767 | /** 768 | * Always equal to `3` 769 | * @example 3 770 | */ 771 | type: 3; 772 | /** @example true */ 773 | success: boolean; 774 | /** @example 61762271 */ 775 | nodeTimestamp: number; 776 | }; 777 | 778 | /** @example {"ip":"194.32.79.175","port":36666,"state":2,"os":"linux4.15.0-36-generic","version":"0.4.0","broadhash":"3dfdf6c7bbaf7537eac9c70432f7ba1cae835b9b15e4ecd97e147616dde67e62","height":10146365,"clock":null,"updated":1562424199553,"nonce":"jxXV6g0sHJhmDubq"} */ 779 | export interface PeerDto { 780 | /** IPv4 address of node */ 781 | ip: string; 782 | /** Port number of ADAMANT node. `36666` for mainnet or `36667` for testnet */ 783 | port: string; 784 | /** State of the peer. Available values: Connected (2), Disconnected, Banned */ 785 | state: number; 786 | /** Node's operating system */ 787 | os: string; 788 | /** ADAMANT node software version */ 789 | version: string; 790 | /** Broadhash on the peer node. Broadhash is established as an aggregated rolling hash of the past five blocks present in the database. */ 791 | broadhash: string; 792 | /** Current node's blockchain height */ 793 | height: number; 794 | clock: string | null; 795 | /** Unix timestamp based in ms, when peer updated */ 796 | updated: number; 797 | /** Unique Identifier for the peer. Random string. */ 798 | nonce: string; 799 | } 800 | 801 | /** @example {"build":"","commit":"b07aaf9580dffb5cc95cc65f303f6f1e5fca7d9c","version":"0.5.2"} */ 802 | export interface NodeVersion { 803 | build: string; 804 | commit: string; 805 | version: string; 806 | } 807 | 808 | /** @example {"send":50000000,"vote":5000000000,"delegate":300000000000,"old_chat_message":500000,"chat_message":100000,"state_store":100000,"profile_update":5000000,"avatar_upload":10000000} */ 809 | export interface TransactionTypesFeesDto { 810 | /** Token transfer, type 0 */ 811 | send: number; 812 | /** Voting for delegate, type 3 */ 813 | vote: number; 814 | /** Registration of a new delegate, type 2 */ 815 | delegate: number; 816 | /** Sending a message (not used for now) */ 817 | old_chat_message: number; 818 | /** Sending a message, type 8 */ 819 | chat_message: number; 820 | /** Storing data in KVS, type 9 */ 821 | state_store: number; 822 | profile_update: number; 823 | avatar_upload: number; 824 | } 825 | 826 | /** @example {"broadhash":"4a28272c915f74d118120bb47db547a18a7512e1d48092c48be86939a6d45b89","epoch":"2017-09-02T17:00:00.000Z","height":10145334,"fee":50000000,"milestone":1,"nethash":"bd330166898377fb28743ceef5e43a5d9d0a3efd9b3451fb7bc53530bb0a6d64","reward":45000000,"supply":10198040075000000} */ 827 | export interface NetworkStatus { 828 | /** Broadhash is established as an aggregated rolling hash of the past five blocks present in the database */ 829 | broadhash: string; 830 | /** Time when blockchain epoch starts. Value `2017-09-02T17:00:00.000Z` is for mainnet. */ 831 | epoch: string; 832 | height: number; 833 | fee: number; 834 | /** Current slot height, which determines reward a delegate will get for forging a block. */ 835 | milestone: number; 836 | /** The `nethash` describes e.g. the Mainnet or the Testnet, that the node is connecting to. */ 837 | nethash: string; 838 | /** The reward a delegate will get for forging a block. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). */ 839 | reward: number; 840 | /** Total current supply of ADM tokens in the network. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). */ 841 | supply: number; 842 | } 843 | 844 | /** @example {"enabled":true,"port":36668} */ 845 | export interface WsClient { 846 | enabled: boolean; 847 | port: number; 848 | } 849 | 850 | /** @example {"state":{"key":"eth:address","value":"0x2391EEaEc07B927D2BA4Fa5cB3cE4b490Fa6fffC","type":0}} */ 851 | export interface KVSTransactionAsset { 852 | state: { 853 | key: string; 854 | value: string; 855 | type: 0; 856 | }; 857 | } 858 | 859 | /** @example {"id":11325216963059857000,"height":3377231,"blockId":14121859709526400000,"type":9,"block_timestamp":23943500,"timestamp":23943500,"senderPublicKey":"ac903ab58135cd5f0613a929d876953214d224034b73c33e63bc153d669447f4","senderId":"U5517006347330072401","recipientId":null,"recipientPublicKey":null,"amount":0,"fee":100000,"signature":"4c3bcca1f6c921cef7ce07f4e641f668c5c0660bb6432335d5e2117c7a4d8378b352e7fa4fac3126bd7228f5b9ac5d57100bb161da02f7efc16df9f7e602b10d","signatures":[],"confirmations":7856415,"asset":{"state":{"key":"eth:address","value":"0x2391EEaEc07B927D2BA4Fa5cB3cE4b490Fa6fffC","type":0}}} */ 860 | export type KVSTransaction = BaseTransaction & { 861 | /** 862 | * Always equal to `9` 863 | * @example 9 864 | */ 865 | type: 9; 866 | /** There is no recipient for this type of transaction */ 867 | recipientId?: string | null; 868 | /** There is no recipient for this type of transaction */ 869 | recipientPublicKey?: string | null; 870 | asset: KVSTransactionAsset; 871 | }; 872 | 873 | export type RegisterKVSTransaction = RegisterTransactionBase & { 874 | /** 875 | * Should be always equal to `9` (Store in KVS transaction type) 876 | * @example 9 877 | */ 878 | type: 9; 879 | asset: KVSTransactionAsset; 880 | }; 881 | 882 | /** @example {"id":14674137414602658000,"height":31536741,"blockId":15921349202793791000,"type":2,"block_timestamp":166805152,"timestamp":166805152,"senderPublicKey":"a339974effc141f302bd3589c603bdc9468dd66bcc424b60025b36999eb69ca3","senderId":"U3031563782805250428","recipientId":null,"recipientPublicKey":null,"amount":0,"fee":300000000000,"relays":1,"signature":"1833a86e24d57ad6dbd30c47924500a03096fd06076fafe5bca4f23ab4629268f3b1a58a1ce275356bc0b79f64a11b8abe9bec6c3d55202d6393327f9278910b","signatures":[],"confirmations":427,"asset":{"delegate":{"username":"kpeo","publicKey":"a339974effc141f302bd3589c603bdc9468dd66bcc424b60025b36999eb69ca3","address":"U3031563782805250428"}}} */ 883 | export type RegisterDelegateTransaction = BaseTransaction & { 884 | /** 885 | * Always equal to `2` 886 | * @example 2 887 | */ 888 | type: 2; 889 | /** There is no recipient for this type of transaction */ 890 | recipientId?: string | null; 891 | /** There is no recipient for this type of transaction */ 892 | recipientPublicKey?: string | null; 893 | asset: RegisterDelegateAsset; 894 | }; 895 | 896 | /** @example {"id":9888167852341778000,"height":10488572,"blockId":16481510969712464000,"type":3,"block_timestamp":59782601,"timestamp":59782601,"senderPublicKey":"9560562121cdc41112a0b288101079346d9c67f5bbff1f4d5a29483258c9477a","senderId":"U9221911598904803004","recipientId":"U9221911598904803004","recipientPublicKey":"9560562121cdc41112a0b288101079346d9c67f5bbff1f4d5a29483258c9477a","amount":0,"fee":5000000000,"signature":"fe199a4a5790186c1c482c6f5c0de5b7baa0a66e4b97abcb96f47e197880ea8333dc57e1b497e32eabdb157ac834dbd85d58d7c550e8aabe208af79026279c04","signatures":[],"confirmations":745088,"asset":{"votes":["-c0c580c3fb89409f32181fef58935f286f0c1bbf61bd727084ed915b3a4bc95b"]},"votes":{"added":[],"deleted":["c0c580c3fb89409f32181fef58935f286f0c1bbf61bd727084ed915b3a4bc95b"]}} */ 897 | export type VoteForDelegateTransaction = BaseTransaction & { 898 | votes: { 899 | /** List of Upvoted delegates */ 900 | added?: string[]; 901 | /** List of Downvoted delegates */ 902 | deleted?: string[]; 903 | }; 904 | /** 905 | * Always equal to `3` 906 | * @example 3 907 | */ 908 | type: 3; 909 | asset: VoteForDelegateAsset; 910 | }; 911 | 912 | export type AnyTransaction = 913 | | TokenTransferTransaction 914 | | RegisterDelegateTransaction 915 | | VoteForDelegateTransaction 916 | | ChatMessageTransaction 917 | | KVSTransaction; 918 | 919 | export type RegisterTokenTransferTransaction = RegisterTransactionBase & { 920 | /** Can be `type 0 — Token transfer` or `type 8 — Chat/Message`. */ 921 | type: 0 | 8; 922 | recipientId: string; 923 | /** Amount of token to transfer */ 924 | amount: number; 925 | }; 926 | 927 | export type RegisterAnyTransaction = 928 | | RegisterVoteForDelegateTransaction 929 | | RegisterTokenTransferTransaction 930 | | RegisterKVSTransaction 931 | | RegisterChatMessageTransaction 932 | | RegisterNewDelegateTransaction; 933 | -------------------------------------------------------------------------------- /src/api/index.ts: -------------------------------------------------------------------------------- 1 | import axios, {AxiosError} from 'axios'; 2 | import {NodeManager, NodeManagerOptions} from '../helpers/healthCheck'; 3 | import { 4 | Logger, 5 | type CustomLogger, 6 | type LogLevel, 7 | type LogLevelName, 8 | } from '../helpers/logger'; 9 | import { 10 | AdamantApiResult, 11 | admToSats, 12 | badParameter, 13 | isAdmAddress, 14 | isAdmPublicKey, 15 | isAdmVoteForAddress, 16 | isAdmVoteForDelegateName, 17 | isAdmVoteForPublicKey, 18 | isDelegateName, 19 | isIntegerAmount, 20 | isMessageType, 21 | isPassphrase, 22 | validateMessage, 23 | } from '../helpers/validator'; 24 | import {DEFAULT_GET_REQUEST_RETRIES, MessageType} from '../helpers/constants'; 25 | 26 | import type { 27 | DelegateDto, 28 | GetAccountBalanceResponseDto, 29 | GetAccountInfoResponseDto, 30 | GetAccountPublicKeyResponseDto, 31 | GetAccountVotesResponseDto, 32 | GetBlockInfoResponseDto, 33 | GetBlocksResponseDto, 34 | GetBroadhashResponseDto, 35 | GetChatMessagesResponseDto, 36 | GetChatRoomsResponseDto, 37 | GetDelegateResponseDto, 38 | GetDelegateStatsResponseDto, 39 | GetDelegatesCountResponseDto, 40 | GetDelegatesResponseDto, 41 | GetEpochResponseDto, 42 | GetHeightResponseDto, 43 | GetLoadingStatusResponseDto, 44 | GetMilestoneResponseDto, 45 | GetNethashResponseDto, 46 | GetNetworkInfoResponseDto, 47 | GetNextForgersResponseDto, 48 | GetNodeStatusResponseDto, 49 | GetNodeVersionResponseDto, 50 | GetPeersResponseDto, 51 | GetPingStatusResponseDto, 52 | GetQueuedTransactionsResponseDto, 53 | GetRewardResponseDto, 54 | GetSyncStatusResponseDto, 55 | GetTokenTransferFeeResponseDto, 56 | GetTokensTotalSupplyResponseDto, 57 | GetTransactionByIdResponseDto, 58 | GetTransactionTypesFeesResponseDto, 59 | GetTransactionsCountResponseDto, 60 | GetTransactionsResponseDto, 61 | GetUnconfirmedTransactionByIdResponseDto, 62 | GetUnconfirmedTransactionsResponseDto, 63 | GetVotersResponseDto, 64 | SearchDelegateResponseDto, 65 | } from './generated'; 66 | import { 67 | createAddressFromPublicKey, 68 | createKeypairFromPassphrase, 69 | } from '../helpers/keys'; 70 | import { 71 | createChatTransaction, 72 | createDelegateTransaction, 73 | createSendTransaction, 74 | createVoteTransaction, 75 | } from '../helpers/transactions'; 76 | import {encodeMessage} from '../helpers/encryptor'; 77 | import { 78 | type VoteDirection, 79 | transformTransactionQuery, 80 | parseVote, 81 | isVoteDirection, 82 | } from './utils'; 83 | 84 | export type AdamantAddress = `U${string}`; 85 | 86 | export interface UsernameObject { 87 | username: string; 88 | } 89 | 90 | export interface PublicKeyObject { 91 | publicKey: string; 92 | } 93 | 94 | export interface AddressObject { 95 | address: string; 96 | } 97 | 98 | /** 99 | * Object that contains either `address` or `publicKey` field 100 | */ 101 | export type AddressOrPublicKeyObject = AddressObject | PublicKeyObject; 102 | 103 | /** 104 | * Object that contains either `username` or `publicKey` field 105 | */ 106 | export type UsernameOrPublicKeyObject = UsernameObject | PublicKeyObject; 107 | 108 | export type TransactionQuery = Partial & { 109 | or?: Partial; 110 | and?: Partial; 111 | }; 112 | 113 | export interface GetBlocksOptions { 114 | limit?: number; 115 | offset?: number; 116 | generatorPublicKey?: string; 117 | height?: number; 118 | } 119 | 120 | export interface GetDelegatesOptions { 121 | limit?: number; 122 | offset?: number; 123 | } 124 | 125 | export interface TransactionQueryParameters { 126 | blockId?: number; 127 | fromHeight?: number; 128 | toHeight?: number; 129 | minAmount?: number; 130 | maxAmount?: number; 131 | senderId?: string; 132 | recipientId?: string; 133 | inId?: string; 134 | limit?: number; 135 | offset?: number; 136 | orderBy?: string; 137 | } 138 | 139 | // parameters that available for /api/chatrooms 140 | export interface ChatroomsOptions extends TransactionQueryParameters { 141 | type?: number; 142 | withoutDirectTransfers?: boolean; 143 | } 144 | 145 | // parameters that available for /api/transactions 146 | export interface TransactionsOptions extends TransactionQueryParameters { 147 | senderIds?: string[]; 148 | recipientIds?: string[]; 149 | senderPublicKey?: string; 150 | senderPublicKeys?: string[]; 151 | recipientPublicKey?: string; 152 | recipientPublicKeys?: string[]; 153 | type?: number; 154 | types?: number[]; 155 | returnAsset?: 1 | 0; 156 | } 157 | 158 | export interface AdamantApiOptions extends NodeManagerOptions { 159 | nodes: string[]; 160 | 161 | maxRetries?: number; 162 | timeout?: number; 163 | 164 | logger?: CustomLogger; 165 | logLevel?: LogLevel | LogLevelName; 166 | } 167 | 168 | const publicKeysCache: { 169 | [address: string]: string; 170 | } = {}; 171 | 172 | export class AdamantApi extends NodeManager { 173 | maxRetries: number; 174 | 175 | constructor(options: AdamantApiOptions) { 176 | const customLogger = new Logger(options.logLevel, options.logger); 177 | 178 | super(customLogger, options); 179 | 180 | this.maxRetries = options.maxRetries ?? DEFAULT_GET_REQUEST_RETRIES; 181 | } 182 | 183 | private async request( 184 | method: 'GET' | 'POST', 185 | endpoint: string, 186 | data: unknown, 187 | retryNo = 1 188 | ): Promise> { 189 | const {logger, maxRetries} = this; 190 | 191 | const url = `${this.node}/api/${endpoint}`; 192 | 193 | try { 194 | const response = await axios>({ 195 | method, 196 | url, 197 | ...(method === 'POST' 198 | ? { 199 | data, 200 | } 201 | : { 202 | params: data, 203 | }), 204 | }); 205 | 206 | return response.data; 207 | } catch (error) { 208 | if (error instanceof AxiosError) { 209 | const {response} = error; 210 | 211 | const nodeStatus = response?.status 212 | ? `Request to ${url} failed with ${response.status} status code` 213 | : `Node ${url} hasn't returned its status`; 214 | 215 | const logMessage = `[ADAMANT js-api] Get-request: ${nodeStatus}, ${error}${ 216 | response?.data ? '. Message: ' + response.data.toString().trim() : '' 217 | }.`; 218 | 219 | if (retryNo <= maxRetries) { 220 | logger.log( 221 | `${logMessage} Try ${retryNo} of ${maxRetries}. Retrying…` 222 | ); 223 | 224 | await this.updateNodes(); 225 | return this.request(method, endpoint, data, retryNo + 1); 226 | } 227 | 228 | logger.warn(`${logMessage} No more attempts, returning error.`); 229 | 230 | return { 231 | success: false, 232 | errorMessage: `${error}`, 233 | }; 234 | } 235 | 236 | return { 237 | success: false, 238 | errorMessage: `${error}`, 239 | }; 240 | } 241 | } 242 | 243 | /** 244 | * Makes GET request to ADAMANT network. 245 | * 246 | * @details `endpoint` should be in `'accounts/getPublicKey'` format, excluding `'/api/'` 247 | */ 248 | async get(endpoint: string, params?: unknown) { 249 | return this.request('GET', endpoint, params); 250 | } 251 | 252 | /** 253 | * Makes POST request to ADAMANT network. 254 | * 255 | * @details `endpoint` should be in `'accounts/getPublicKey'` format, excluding `'/api/'` 256 | */ 257 | async post(endpoint: string, options: unknown) { 258 | return this.request('POST', endpoint, options); 259 | } 260 | 261 | /** 262 | * Get account Public Key 263 | */ 264 | async getPublicKey(address: AdamantAddress) { 265 | const cached = publicKeysCache[address]; 266 | if (cached) { 267 | return cached; 268 | } 269 | 270 | const response = await this.get( 271 | 'accounts/getPublicKey', 272 | { 273 | address, 274 | } 275 | ); 276 | 277 | if (response.success) { 278 | const {publicKey} = response; 279 | 280 | publicKeysCache[address] = publicKey; 281 | return publicKey; 282 | } 283 | 284 | this.logger.warn( 285 | `[ADAMANT js-api] Failed to get public key for ${address}. ${response.errorMessage}.` 286 | ); 287 | return ''; 288 | } 289 | 290 | /** 291 | * Register new delegate within given username 292 | * 293 | * @param username The new delegate's username 294 | */ 295 | async newDelegate(passphrase: string, username: string) { 296 | if (!isPassphrase(passphrase)) { 297 | return badParameter('passphrase'); 298 | } 299 | 300 | if (!isDelegateName(username)) { 301 | return badParameter('username'); 302 | } 303 | 304 | const keyPair = createKeypairFromPassphrase(passphrase); 305 | 306 | const data = { 307 | keyPair, 308 | username, 309 | }; 310 | 311 | const transaction = createDelegateTransaction(data); 312 | 313 | return this.post('delegates', transaction); 314 | } 315 | 316 | /** 317 | * Encrypt a message, creates Message transaction, signs it, and broadcasts to ADAMANT network. 318 | */ 319 | async sendMessage( 320 | passphrase: string, 321 | addressOrPublicKey: string, 322 | message: string, 323 | type = MessageType.Chat, 324 | amount?: number, 325 | isAmountInADM?: boolean 326 | ) { 327 | if (!isPassphrase(passphrase)) { 328 | return badParameter('passphrase'); 329 | } 330 | 331 | let address: AdamantAddress; 332 | let publicKey = ''; 333 | 334 | if (!isAdmAddress(addressOrPublicKey)) { 335 | if (!isAdmPublicKey(addressOrPublicKey)) { 336 | return badParameter('addressOrPublicKey', addressOrPublicKey); 337 | } 338 | 339 | publicKey = addressOrPublicKey; 340 | 341 | try { 342 | address = createAddressFromPublicKey(publicKey); 343 | } catch (error) { 344 | return badParameter('addressOrPublicKey', addressOrPublicKey); 345 | } 346 | } else { 347 | address = addressOrPublicKey; 348 | } 349 | 350 | if (!isMessageType(type)) { 351 | return badParameter('type', type); 352 | } 353 | 354 | const result = validateMessage(message, type); 355 | 356 | if (!result.success) { 357 | return badParameter('message', message, result.error); 358 | } 359 | 360 | let amountInSat: number | undefined; 361 | 362 | if (amount) { 363 | amountInSat = amount; 364 | 365 | if (isAmountInADM) { 366 | amountInSat = admToSats(amount); 367 | } 368 | 369 | if (!isIntegerAmount(amountInSat)) { 370 | return badParameter('amount', amount); 371 | } 372 | } 373 | 374 | if (!publicKey) { 375 | publicKey = await this.getPublicKey(address); 376 | } 377 | 378 | if (!publicKey) { 379 | return { 380 | success: false, 381 | errorMessage: `Unable to get public key for ${addressOrPublicKey}. It is necessary for sending an encrypted message. Account may be uninitialized (https://medium.com/adamant-im/chats-and-uninitialized-accounts-in-adamant-5035438e2fcd), or network error`, 382 | }; 383 | } 384 | 385 | const keyPair = createKeypairFromPassphrase(passphrase); 386 | const encryptedMessage = encodeMessage(message, keyPair, publicKey); 387 | 388 | const data = { 389 | ...encryptedMessage, 390 | keyPair, 391 | recipientId: address, 392 | message_type: type, 393 | amount: amountInSat, 394 | }; 395 | 396 | const transaction = createChatTransaction(data); 397 | 398 | return this.post('transactions/process', { 399 | transaction, 400 | }); 401 | } 402 | 403 | /** 404 | * Send tokens to an account 405 | */ 406 | sendTokens( 407 | passphrase: string, 408 | addressOrPublicKey: string, 409 | amount: number, 410 | isAmountInADM = true 411 | ) { 412 | if (!isPassphrase(passphrase)) { 413 | return badParameter('passphrase'); 414 | } 415 | 416 | let address: AdamantAddress; 417 | 418 | if (isAdmAddress(addressOrPublicKey)) { 419 | address = addressOrPublicKey; 420 | } else { 421 | if (!isAdmPublicKey(addressOrPublicKey)) { 422 | return badParameter('addressOrPublicKey', addressOrPublicKey); 423 | } 424 | 425 | try { 426 | address = createAddressFromPublicKey(addressOrPublicKey); 427 | } catch (error) { 428 | return badParameter('addressOrPublicKey', addressOrPublicKey); 429 | } 430 | } 431 | 432 | let amountInSat = amount; 433 | 434 | if (isAmountInADM) { 435 | amountInSat = admToSats(amount); 436 | } 437 | 438 | if (!isIntegerAmount(amountInSat)) { 439 | return badParameter('amount', amount); 440 | } 441 | 442 | const keyPair = createKeypairFromPassphrase(passphrase); 443 | 444 | const data = { 445 | keyPair, 446 | recipientId: address, 447 | amount: amountInSat, 448 | }; 449 | 450 | const transaction = createSendTransaction(data); 451 | 452 | return this.post('transactions/process', { 453 | transaction, 454 | }); 455 | } 456 | 457 | /** 458 | * Vote for specific delegates 459 | * 460 | * @param passphrase Account's passphrase 461 | * @param votes Array with public keys. For upvote, add leading `+` to delegate's public key. For downvote, add leading `-` to delegate's public key. 462 | * 463 | * @example 464 | * ``` 465 | * voteForDelegate( 466 | * 'apple banana cherry date elderberry fig grape hazelnut iris juniper kiwi lemon', 467 | * [ 468 | * '+b3d0c0b99f64d0960324089eb678e90d8bcbb3dd8c73ee748e026f8b9a5b5468', 469 | * '-9ef1f6212ae871716cfa2d04e3dc5339e8fe75f89818be21ee1d75004983e2a8', 470 | * '+system', 471 | * '-U16615166477939602094' 472 | * ] 473 | * ) 474 | * ``` 475 | */ 476 | async voteForDelegate(passphrase: string, votes: string[]) { 477 | if (!isPassphrase(passphrase)) { 478 | return badParameter('passphrase'); 479 | } 480 | 481 | const keyPair = createKeypairFromPassphrase(passphrase); 482 | 483 | const uniqueVotes: { 484 | [publicKey: string]: VoteDirection; 485 | } = {}; 486 | 487 | let delegates: DelegateDto[] = []; 488 | 489 | for (const vote of votes) { 490 | const [name, direction] = parseVote(vote); 491 | 492 | const cachedPublicKey = publicKeysCache[name]; 493 | 494 | if (cachedPublicKey) { 495 | uniqueVotes[cachedPublicKey] = direction; 496 | continue; 497 | } 498 | 499 | if (!isVoteDirection(direction)) { 500 | return badParameter('votes', vote, 'the vote should have direction'); 501 | } 502 | 503 | if (isAdmVoteForAddress(vote)) { 504 | if (!delegates.length) { 505 | const response = await this.getDelegates(); 506 | 507 | if (!response.success) { 508 | this.logger.warn( 509 | `[ADAMANT js-api] Failed to get list of delegates. ${response.errorMessage}.` 510 | ); 511 | 512 | return badParameter( 513 | 'votes', 514 | vote, 515 | 'unable to retrieve the delegates list' 516 | ); 517 | } 518 | 519 | ({delegates} = response); 520 | } 521 | 522 | const delegate = delegates.find(delegate => delegate.address === name); 523 | 524 | if (!delegate) { 525 | return badParameter('votes', vote, 'the address is not a delegate'); 526 | } 527 | 528 | const {publicKey} = delegate; 529 | 530 | publicKeysCache[name] = publicKey; 531 | uniqueVotes[publicKey] = direction; 532 | 533 | continue; 534 | } 535 | 536 | if (isAdmVoteForDelegateName(vote)) { 537 | const response = await this.getDelegate({username: name}); 538 | 539 | if (!response.success) { 540 | this.logger.warn( 541 | `[ADAMANT js-api] Failed to get public key for ${vote}. ${response.errorMessage}.` 542 | ); 543 | 544 | return badParameter( 545 | 'votes', 546 | name, 547 | "unable to retrieve the delegate's public key" 548 | ); 549 | } 550 | 551 | const {publicKey} = response.delegate; 552 | 553 | publicKeysCache[name] = publicKey; 554 | uniqueVotes[publicKey] = direction; 555 | 556 | continue; 557 | } 558 | 559 | if (!isAdmVoteForPublicKey(vote)) { 560 | return badParameter( 561 | 'votes', 562 | name, 563 | "the vote doesn't look like public key, address or delegate name" 564 | ); 565 | } 566 | 567 | uniqueVotes[name] = direction; 568 | } 569 | 570 | const data = { 571 | keyPair, 572 | votes: Object.keys(uniqueVotes).map( 573 | name => `${uniqueVotes[name]}${name}` 574 | ), 575 | }; 576 | 577 | const transaction = createVoteTransaction(data); 578 | 579 | return this.post('accounts/delegates', transaction); 580 | } 581 | 582 | /** 583 | * Get account information by ADAMANT address or Public Key 584 | */ 585 | async getAccountInfo( 586 | options: AddressOrPublicKeyObject 587 | ): Promise> { 588 | return this.get('accounts', options); 589 | } 590 | 591 | /** 592 | * Get account balance 593 | */ 594 | async getAccountBalance(address: string) { 595 | return this.get('accounts/getBalance', { 596 | address, 597 | }); 598 | } 599 | 600 | /** 601 | * Get block information by ID 602 | */ 603 | async getBlock(id: string) { 604 | return this.get('blocks/get', {id}); 605 | } 606 | 607 | /** 608 | * Get list of blocks 609 | */ 610 | async getBlocks(options?: GetBlocksOptions) { 611 | return this.get('blocks', options); 612 | } 613 | 614 | /** 615 | * Get list of Chats 616 | */ 617 | async getChats( 618 | address: string, 619 | options?: TransactionQuery 620 | ) { 621 | return this.get( 622 | `chatrooms/${address}`, 623 | transformTransactionQuery(options) 624 | ); 625 | } 626 | 627 | /** 628 | * Get messages between two accounts 629 | */ 630 | async getChatMessages( 631 | address1: string, 632 | address2: string, 633 | query?: TransactionQuery 634 | ) { 635 | return this.get( 636 | `chatrooms/${address1}/${address2}`, 637 | transformTransactionQuery(query) 638 | ); 639 | } 640 | 641 | /** 642 | * Retrieves list of registered ADAMANT delegates 643 | */ 644 | async getDelegates(options?: GetDelegatesOptions) { 645 | return this.get('delegates', options); 646 | } 647 | 648 | /** 649 | * Get delegate info by `username` or `publicKey` 650 | */ 651 | async getDelegate(options: UsernameOrPublicKeyObject) { 652 | return this.get('delegates/get', options); 653 | } 654 | 655 | /** 656 | * Search delegates by `username` 657 | * 658 | * @param q - username 659 | */ 660 | async searchDelegates(q: string) { 661 | return this.get('delegates/search', {q}); 662 | } 663 | 664 | /** 665 | * Get total count of delegates 666 | */ 667 | async getDelegatesCount() { 668 | return this.get('delegates/count'); 669 | } 670 | 671 | /** 672 | * Get forging activity of a delegate 673 | */ 674 | async getDelegateStats(generatorPublicKey: string) { 675 | return this.get( 676 | 'delegates/forging/getForgedByAccount', 677 | {generatorPublicKey} 678 | ); 679 | } 680 | 681 | /** 682 | * Returns list of next forgers 683 | * 684 | * @param limit count to retrieve 685 | */ 686 | async getNextForgers(limit?: number) { 687 | return this.get('delegates/getNextForgers', { 688 | limit, 689 | }); 690 | } 691 | 692 | /** 693 | * Gets list of delegate's voters 694 | * 695 | * @param publicKey representing delegate's publicKey 696 | */ 697 | async getVoters(publicKey: string) { 698 | return this.get('delegates/voters', {publicKey}); 699 | } 700 | 701 | /** 702 | * Gets current votes of specific ADAMANT account 703 | * 704 | * @param address address of the account to get votes 705 | */ 706 | async getVoteData(address: string) { 707 | return this.get('accounts/delegates', { 708 | address, 709 | }); 710 | } 711 | 712 | /** 713 | * Gets list of connected peer nodes 714 | */ 715 | async getPeers() { 716 | return this.get('peers'); 717 | } 718 | 719 | /** 720 | * Gets loading status 721 | */ 722 | async getLoadingStatus() { 723 | return this.get('loader/status'); 724 | } 725 | 726 | /** 727 | * Gets information on node's sync process with other peers 728 | */ 729 | async getSyncStatus() { 730 | return this.get('loader/status/sync'); 731 | } 732 | 733 | /** 734 | * Checks if the connected node is alive 735 | */ 736 | async getPingStatus() { 737 | return this.get('loader/status/ping'); 738 | } 739 | 740 | /** 741 | * Gets node's software information 742 | */ 743 | async getNodeVersion() { 744 | return this.get('peers/version'); 745 | } 746 | 747 | /** 748 | * Broadhash is established as an aggregated rolling hash of the past five blocks present in the database. 749 | */ 750 | async getBroadhash() { 751 | return this.get('blocks/getBroadhash'); 752 | } 753 | 754 | /** 755 | * Returns time when blockchain epoch starts. Value `2017-09-02T17:00:00.000Z` is for mainnet. 756 | */ 757 | async getEpoch() { 758 | return this.get('blocks/getEpoch'); 759 | } 760 | 761 | /** 762 | * Returns current node's blockchain height 763 | */ 764 | async getHeight() { 765 | return this.get('blocks/getHeight'); 766 | } 767 | 768 | /** 769 | * Returns current fee value for `type 0` (token transfer) transactions. 770 | * Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). 771 | */ 772 | async getFee() { 773 | return this.get('blocks/getFee'); 774 | } 775 | 776 | /** 777 | * Returns current fee values for different transaction types 778 | */ 779 | async getFees() { 780 | return this.get('blocks/getFees'); 781 | } 782 | 783 | /** 784 | * The nethash describes e.g. the Mainnet or the Testnet, that the node is connecting to. 785 | */ 786 | async getNethash() { 787 | return this.get('blocks/getNethash'); 788 | } 789 | 790 | /** 791 | * Return current slot height, which determines reward a delegate will get for forging a block. 792 | */ 793 | async getMilestone() { 794 | return this.get('blocks/getMilestone'); 795 | } 796 | 797 | /** 798 | * Returns reward — the reward a delegate will get for forging a block. 799 | * Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). Depends on the slot height. 800 | */ 801 | async getReward() { 802 | return this.get('blocks/getReward'); 803 | } 804 | 805 | /** 806 | * Returns total current supply of ADM tokens in network. Integer amount of 1/10^8 ADM tokens (1 ADM = 100000000). 807 | * Total supply increases with every new forged block. 808 | */ 809 | async getSupply() { 810 | return this.get('blocks/getSupply'); 811 | } 812 | 813 | /** 814 | * Returns blockchain network information in a single request 815 | */ 816 | async getStatus() { 817 | return this.get('blocks/getStatus'); 818 | } 819 | 820 | /** 821 | * Returns both ADAMANT blockchain network information and Node information in a single request. 822 | */ 823 | async getNodeStatus() { 824 | return this.get('node/status'); 825 | } 826 | 827 | /** 828 | * Returns list of transactions 829 | */ 830 | async getTransactions(options?: TransactionQuery) { 831 | return this.get( 832 | 'transactions', 833 | transformTransactionQuery(options) 834 | ); 835 | } 836 | 837 | /** 838 | * Get transaction by ID 839 | */ 840 | async getTransaction( 841 | id: string, 842 | options?: TransactionQuery 843 | ) { 844 | return this.get('transactions/get', { 845 | id, 846 | ...transformTransactionQuery(options), 847 | }); 848 | } 849 | 850 | /** 851 | * Get `confirmed`, `uncofirmed` and `queued` transactions count 852 | * 853 | * @nav Transactions 854 | */ 855 | async getTransactionsCount() { 856 | return this.get('transactions/count'); 857 | } 858 | 859 | /** 860 | * Get queued transactions count 861 | */ 862 | async getQueuedTransactions() { 863 | return this.get('transactions/queued'); 864 | } 865 | 866 | /** 867 | * Get queued transaction by ID 868 | */ 869 | async getQueuedTransaction(id: string) { 870 | return this.get( 871 | 'transactions/queued/get', 872 | {id} 873 | ); 874 | } 875 | 876 | /** 877 | * Get unconfirmed transactions 878 | */ 879 | async getUnconfirmedTransactions() { 880 | return this.get( 881 | 'transactions/unconfirmed' 882 | ); 883 | } 884 | 885 | /** 886 | * Get unconfirmed transaction by ID 887 | */ 888 | async getUnconfirmedTransaction(id: string) { 889 | return this.get( 890 | 'transactions/unconfirmed/get', 891 | {id} 892 | ); 893 | } 894 | } 895 | 896 | export * from './generated'; 897 | export * from './utils'; 898 | -------------------------------------------------------------------------------- /src/api/tests/utils.test.ts: -------------------------------------------------------------------------------- 1 | import {transformTransactionQuery} from '../utils'; 2 | 3 | describe('transformTransactionQuery', () => { 4 | it('should transform `or` and `and` object properties', () => { 5 | const transformed = transformTransactionQuery({ 6 | or: { 7 | maxAmount: 50000000, 8 | senderPublicKey: 9 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 10 | senderPublicKeys: [ 11 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 12 | '4ef885053c630041f57493343d7f6023107c5dc8b8148147e732c93', 13 | ], 14 | }, 15 | and: { 16 | blockId: '7917597195203393333', 17 | fromHeight: 10336065, 18 | toHeight: 11, 19 | minAmount: 1000000000000001, 20 | senderId: 'U15423595369615486571', 21 | senderIds: ['U18132012621449491414', 'U15881344309699504778'], 22 | recipientId: 'U15423595369615486571', 23 | recipientIds: ['U18132012621449491414', 'U15881344309699504778'], 24 | recipientPublicKey: 25 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 26 | recipientPublicKeys: [ 27 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 28 | '4ef885053c630041f57493343d7f6023107c5dc8b8148147e732c93', 29 | ], 30 | inId: 'U100739400829575109', 31 | type: 2, 32 | types: [9, 0], 33 | key: 'eth:address', 34 | keyIds: ['eth:address', 'doge:address', 'dash:address'], 35 | }, 36 | }); 37 | 38 | expect(transformed).toStrictEqual({ 39 | 'or:maxAmount': 50000000, 40 | 'or:senderPublicKey': 41 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 42 | 'or:senderPublicKeys': [ 43 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 44 | '4ef885053c630041f57493343d7f6023107c5dc8b8148147e732c93', 45 | ], 46 | 'and:blockId': '7917597195203393333', 47 | 'and:fromHeight': 10336065, 48 | 'and:toHeight': 11, 49 | 'and:minAmount': 1000000000000001, 50 | 'and:senderId': 'U15423595369615486571', 51 | 'and:senderIds': ['U18132012621449491414', 'U15881344309699504778'], 52 | 'and:recipientId': 'U15423595369615486571', 53 | 'and:recipientIds': ['U18132012621449491414', 'U15881344309699504778'], 54 | 'and:recipientPublicKey': 55 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 56 | 'and:recipientPublicKeys': [ 57 | '801846655523f5e21f2d454b2f98f70aaf5d3887c806463100a1764a4e7c1457', 58 | '4ef885053c630041f57493343d7f6023107c5dc8b8148147e732c93', 59 | ], 60 | 'and:inId': 'U100739400829575109', 61 | 'and:type': 2, 62 | 'and:types': [9, 0], 63 | 'and:key': 'eth:address', 64 | 'and:keyIds': ['eth:address', 'doge:address', 'dash:address'], 65 | }); 66 | }); 67 | 68 | it('should NOT transform object properties other than `or` and `and`', () => { 69 | const transformed = transformTransactionQuery({ 70 | minAmount: 5000, 71 | senderId: 'U15423595369615486571', 72 | senderIds: ['U18132012621449491414', 'U15881344309699504778'], 73 | and: { 74 | maxAmount: 6000, 75 | }, 76 | or: { 77 | recipientIds: ['U18132012621449491414', 'U15881344309699504778'], 78 | }, 79 | }); 80 | 81 | expect(transformed).toStrictEqual({ 82 | minAmount: 5000, 83 | senderId: 'U15423595369615486571', 84 | senderIds: ['U18132012621449491414', 'U15881344309699504778'], 85 | 'and:maxAmount': 6000, 86 | 'or:recipientIds': ['U18132012621449491414', 'U15881344309699504778'], 87 | }); 88 | }); 89 | }); 90 | -------------------------------------------------------------------------------- /src/api/utils.ts: -------------------------------------------------------------------------------- 1 | import {hasOwnProperty} from '../helpers/utils'; 2 | import {TransactionQuery} from '.'; 3 | 4 | const VOTE_DIRECTIONS = ['+', '-'] as const; 5 | 6 | export type VoteDirection = (typeof VOTE_DIRECTIONS)[number]; 7 | 8 | export const isVoteDirection = ( 9 | direction: unknown 10 | ): direction is VoteDirection => 11 | typeof direction === 'string' && 12 | VOTE_DIRECTIONS.includes(direction as VoteDirection); 13 | 14 | export const parseVote = (vote: string): [string, VoteDirection] => { 15 | const name = vote.slice(1); 16 | const direction = vote.charAt(0); 17 | 18 | return [name, direction as VoteDirection]; 19 | }; 20 | 21 | export const transformTransactionQuery = ( 22 | obj?: TransactionQuery 23 | ) => { 24 | if (!obj) { 25 | return {}; 26 | } 27 | 28 | const transformed: Record = { 29 | ...obj, 30 | }; 31 | 32 | for (const topLevelProp in obj) { 33 | if (hasOwnProperty(obj, topLevelProp)) { 34 | if (topLevelProp === 'or' || topLevelProp === 'and') { 35 | const subProps = obj[topLevelProp]; 36 | 37 | for (const subProp in subProps) { 38 | if (hasOwnProperty(subProps, subProp)) { 39 | const newKey = `${topLevelProp}:${subProp}`; 40 | transformed[newKey] = subProps[subProp]; 41 | } 42 | } 43 | 44 | delete transformed[topLevelProp]; 45 | } 46 | } 47 | } 48 | 49 | return transformed; 50 | }; 51 | -------------------------------------------------------------------------------- /src/coins/btc.ts: -------------------------------------------------------------------------------- 1 | import * as bitcoin from 'bitcoinjs-lib'; 2 | import {ECPairFactory} from 'ecpair'; 3 | import * as tinysecp from 'tiny-secp256k1'; 4 | 5 | import coininfo from 'coininfo'; 6 | 7 | const RE_BTC_ADDRESS = /^(bc1|[13])[a-km-zA-HJ-NP-Z02-9]{25,39}$/; 8 | 9 | const network = coininfo.bitcoin.main.toBitcoinJS(); 10 | 11 | export const btc = { 12 | keys: (passphrase: string) => { 13 | const pwHash = bitcoin.crypto.sha256(Buffer.from(passphrase)); 14 | 15 | const ECPairAPI = ECPairFactory(tinysecp); 16 | const keyPair = ECPairAPI.fromPrivateKey(pwHash, {network}); 17 | 18 | return { 19 | network, 20 | keyPair, 21 | address: bitcoin.payments.p2pkh({pubkey: keyPair.publicKey, network}) 22 | .address, 23 | // BTC private key is a regular 256-bit key 24 | privateKey: keyPair.privateKey?.toString('hex'), // regular 256-bit (32 bytes, 64 characters) private key 25 | privateKeyWIF: keyPair.toWIF(), // Wallet Import Format (52 base58 characters) 26 | }; 27 | }, 28 | 29 | isValidAddress: (address: string) => 30 | typeof address === 'string' && RE_BTC_ADDRESS.test(address), 31 | }; 32 | -------------------------------------------------------------------------------- /src/coins/dash.ts: -------------------------------------------------------------------------------- 1 | import * as bitcoin from 'bitcoinjs-lib'; 2 | import {ECPairFactory} from 'ecpair'; 3 | import * as tinysecp from 'tiny-secp256k1'; 4 | 5 | import coininfo from 'coininfo'; 6 | 7 | const RE_DASH_ADDRESS = /^[7X][1-9A-HJ-NP-Za-km-z]{33,}$/; 8 | 9 | const network = coininfo.dash.main.toBitcoinJS(); 10 | 11 | export const dash = { 12 | keys: (passphrase: string) => { 13 | const pwHash = bitcoin.crypto.sha256(Buffer.from(passphrase)); 14 | 15 | const ECPairAPI = ECPairFactory(tinysecp); 16 | const keyPair = ECPairAPI.fromPrivateKey(pwHash, {network}); 17 | 18 | return { 19 | network, 20 | keyPair, 21 | address: bitcoin.payments.p2pkh({pubkey: keyPair.publicKey, network}) 22 | .address, 23 | // DASH private key is a regular 256-bit key 24 | privateKey: keyPair.privateKey?.toString('hex'), // regular 256-bit (32 bytes, 64 characters) private key 25 | privateKeyWIF: keyPair.toWIF(), // Wallet Import Format (52 base58 characters) 26 | }; 27 | }, 28 | isValidAddress: (address: string) => 29 | typeof address === 'string' && RE_DASH_ADDRESS.test(address), 30 | }; 31 | -------------------------------------------------------------------------------- /src/coins/doge.ts: -------------------------------------------------------------------------------- 1 | import * as bitcoin from 'bitcoinjs-lib'; 2 | import {ECPairFactory} from 'ecpair'; 3 | import * as tinysecp from 'tiny-secp256k1'; 4 | 5 | import coininfo from 'coininfo'; 6 | 7 | const RE_DOGE_ADDRESS = /^[A|D|9][A-Z0-9]([0-9a-zA-Z]{9,})$/; 8 | 9 | const network = coininfo.dogecoin.main.toBitcoinJS(); 10 | 11 | export const doge = { 12 | keys: (passphrase: string) => { 13 | const pwHash = bitcoin.crypto.sha256(Buffer.from(passphrase)); 14 | 15 | const ECPairAPI = ECPairFactory(tinysecp); 16 | const keyPair = ECPairAPI.fromPrivateKey(pwHash, {network}); 17 | 18 | return { 19 | network, 20 | keyPair, 21 | address: bitcoin.payments.p2pkh({pubkey: keyPair.publicKey, network}) 22 | .address, 23 | // DOGE private key is a regular 256-bit key 24 | privateKey: keyPair.privateKey?.toString('hex'), // regular 256-bit (32 bytes, 64 characters) private key 25 | privateKeyWIF: keyPair.toWIF(), // Wallet Import Format (52 base58 characters) 26 | }; 27 | }, 28 | isValidAddress: (address: string) => 29 | typeof address === 'string' && RE_DOGE_ADDRESS.test(address), 30 | }; 31 | -------------------------------------------------------------------------------- /src/coins/eth.ts: -------------------------------------------------------------------------------- 1 | import {mnemonicToSeedSync} from 'bip39'; 2 | import hdkey from 'hdkey'; 3 | import {bufferToHex, privateToAddress} from 'ethereumjs-util'; 4 | 5 | const HD_KEY_PATH = "m/44'/60'/3'/1/0"; 6 | 7 | export const eth = { 8 | keys: (passphrase: string) => { 9 | const seed = mnemonicToSeedSync(passphrase); 10 | const privateKey = hdkey 11 | .fromMasterSeed(seed) 12 | .derive(HD_KEY_PATH).privateKey; 13 | 14 | return { 15 | address: bufferToHex(privateToAddress(privateKey)), 16 | privateKey: bufferToHex(privateKey), 17 | }; 18 | }, 19 | }; 20 | -------------------------------------------------------------------------------- /src/coins/index.ts: -------------------------------------------------------------------------------- 1 | export * from './btc'; 2 | export * from './dash'; 3 | export * from './doge'; 4 | export * from './eth'; 5 | export * from './lsk'; 6 | -------------------------------------------------------------------------------- /src/coins/lsk.ts: -------------------------------------------------------------------------------- 1 | import {address as cryptography} from '@liskhq/lisk-cryptography'; 2 | import sodium from 'sodium-browserify-tweetnacl'; 3 | import pbkdf2 from 'pbkdf2'; 4 | import {bytesToHex} from '../helpers/encryptor'; 5 | 6 | const LiskHashSettings = { 7 | SALT: 'adm', 8 | ITERATIONS: 2048, 9 | KEYLEN: 32, 10 | DIGEST: 'sha256', 11 | }; 12 | 13 | const network = { 14 | name: 'Lisk', 15 | port: 8000, 16 | wsPort: 8001, 17 | unit: 'LSK', 18 | }; 19 | 20 | export const lsk = { 21 | keys: (passphrase: string) => { 22 | const liskSeed = pbkdf2.pbkdf2Sync( 23 | passphrase, 24 | LiskHashSettings.SALT, 25 | LiskHashSettings.ITERATIONS, 26 | LiskHashSettings.KEYLEN, 27 | LiskHashSettings.DIGEST 28 | ); 29 | const keyPair = sodium.crypto_sign_seed_keypair(liskSeed); 30 | const address = cryptography.getLisk32AddressFromPublicKey( 31 | keyPair.publicKey 32 | ); 33 | const addressHexBinary = cryptography.getAddressFromPublicKey( 34 | keyPair.publicKey 35 | ); 36 | const addressHex = bytesToHex(addressHexBinary); 37 | const privateKey = keyPair.secretKey.toString('hex'); 38 | 39 | return { 40 | network, 41 | keyPair, 42 | address, 43 | addressHexBinary, 44 | addressHex, 45 | privateKey, 46 | }; 47 | }, 48 | }; 49 | -------------------------------------------------------------------------------- /src/coins/tests/btc.test.ts: -------------------------------------------------------------------------------- 1 | import {btc} from '../btc'; 2 | import {passphrase} from './mock/passphrase'; 3 | 4 | describe('btc.keys()', () => { 5 | test('should create keys with bitcoin network and address/privateKey for the passphrase', () => { 6 | const keys = btc.keys(passphrase); 7 | 8 | expect(keys).toMatchObject({ 9 | address: '13rK42XbSJV9BdvKQvDJeH3n45zNBbXsUV', 10 | privateKey: 11 | '0c9c84722d74ae5c5ba52f74285807ef08085a66aa7b23377fa8cdd51f1ecff3', 12 | privateKeyWIF: 'KweE3oRFhusodiwEsXjEH9rBR1HUfkZsHjHZHPzvKtXRjroArofw', 13 | network: { 14 | name: 'Bitcoin', 15 | unit: 'BTC', 16 | }, 17 | }); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/coins/tests/dash.test.ts: -------------------------------------------------------------------------------- 1 | import {dash} from '../dash'; 2 | import {passphrase} from './mock/passphrase'; 3 | 4 | describe('dash.keys()', () => { 5 | test('should create keys with dash network and address/privateKey for the passphrase', () => { 6 | const keys = dash.keys(passphrase); 7 | 8 | expect(keys).toMatchObject({ 9 | address: 'XdY9tHBVQ1hjLaWuGoXXVojZtRa4GfEdNP', 10 | privateKey: 11 | '0c9c84722d74ae5c5ba52f74285807ef08085a66aa7b23377fa8cdd51f1ecff3', 12 | privateKeyWIF: 'XBi9W4od1bWFh3wcuHj6nP3CL2Z47ZB7fJdTovL7eFoX91tC1QD4', 13 | network: { 14 | name: 'Dash', 15 | unit: 'DASH', 16 | }, 17 | }); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/coins/tests/doge.test.ts: -------------------------------------------------------------------------------- 1 | import {doge} from '../doge'; 2 | import {passphrase} from './mock/passphrase'; 3 | 4 | describe('doge.keys()', () => { 5 | test('should create keys with doge network and address/privateKey for the passphrase', () => { 6 | const keys = doge.keys(passphrase); 7 | 8 | expect(keys).toMatchObject({ 9 | address: 'D7zQbHUEjiPRie6v9WCsC3DNwDifUdbFdd', 10 | privateKey: 11 | '0c9c84722d74ae5c5ba52f74285807ef08085a66aa7b23377fa8cdd51f1ecff3', 12 | privateKeyWIF: 'QP39CeEExXMvsFLHToa2ANgnt3K3iJhgAyyU52Pm4F8nBniweSFq', 13 | network: { 14 | name: 'Dogecoin', 15 | unit: 'DOGE', 16 | }, 17 | }); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/coins/tests/eth.test.ts: -------------------------------------------------------------------------------- 1 | import {eth} from '../eth'; 2 | import {passphrase} from './mock/passphrase'; 3 | 4 | describe('eth.keys()', () => { 5 | test('should create address and privateKey for the passphrase', () => { 6 | const keys = eth.keys(passphrase); 7 | 8 | expect(keys).toMatchObject({ 9 | address: '0x6c892b27f6deb1c81ed0122b23193c5802464c2c', 10 | privateKey: 11 | '0x2a3d59f8cab3c8b90d2e841c85872d0a78c75ac8d0b74186f856b3e954121277', 12 | }); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/coins/tests/lsk.test.ts: -------------------------------------------------------------------------------- 1 | import {lsk} from '../lsk'; 2 | import {passphrase} from './mock/passphrase'; 3 | 4 | describe('eth.keys()', () => { 5 | test('should create address and privateKey for the passphrase', () => { 6 | const keys = lsk.keys(passphrase); 7 | 8 | expect(keys).toMatchObject({ 9 | address: 'lsk53o76hxv9kkc4cq7239gbgtgjhq6uswgt5aqxc', 10 | addressHex: '5a18e574226d28348eaec21bf37e7fe76aa86eff', 11 | privateKey: 12 | 'b0ec632b3ceb31dd2f1cfa8d3c16086f0d14c1344a126d0136bca3bf00d4fc1dddf501ed87c5d950241622ca678a7a96f59e63aa1a0ef89d4a6bbf096ba00471', 13 | network: { 14 | name: 'Lisk', 15 | unit: 'LSK', 16 | }, 17 | }); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /src/coins/tests/mock/passphrase.ts: -------------------------------------------------------------------------------- 1 | export const passphrase = 2 | 'learn arch equip tenant cause can brief brisk rich betray arrest damage'; 3 | -------------------------------------------------------------------------------- /src/helpers/bignumber.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js'; 2 | 3 | type Endian = 1 | -1 | 'big' | 'little'; 4 | 5 | interface TransformBufferOptions { 6 | endian?: Endian; 7 | size?: number | 'auto'; 8 | } 9 | 10 | type EndianMap = { 11 | [K in Endian]: 'big' | 'little'; 12 | }; 13 | 14 | const endianMap: EndianMap = { 15 | 1: 'big', 16 | '-1': 'little', 17 | big: 'big', 18 | little: 'little', 19 | }; 20 | 21 | export const fromBuffer = (buf: Buffer, opts: TransformBufferOptions = {}) => { 22 | const endian = resolveEndian(opts); 23 | 24 | const size = resolveSize(opts, buf.length); 25 | 26 | validateBufferLength(buf, size); 27 | 28 | const hex = bufferToHexArray(buf, size, endian); 29 | 30 | return new BigNumber(hex.join(''), 16); 31 | }; 32 | 33 | export const toBuffer = ( 34 | bignumber: BigNumber, 35 | opts: TransformBufferOptions | 'mpint' = {} 36 | ) => { 37 | if (typeof opts === 'string') { 38 | return toMpintBuffer(bignumber); 39 | } 40 | 41 | const endian = resolveEndian(opts); 42 | const hex = bignumberToHex(bignumber); 43 | 44 | const size = resolveSize(opts, hex.length / 2); 45 | 46 | return hexToBuffer(hex, size, endian); 47 | }; 48 | 49 | export function resolveEndian(opts: TransformBufferOptions): Endian { 50 | if (!opts.endian) { 51 | return 'big'; 52 | } 53 | 54 | return endianMap[opts.endian]; 55 | } 56 | 57 | export function resolveSize( 58 | opts: TransformBufferOptions, 59 | defaultSize: number 60 | ): number { 61 | return opts.size === 'auto' ? Math.ceil(defaultSize) : opts.size || 1; 62 | } 63 | 64 | export function validateBufferLength(buf: Buffer, size: number) { 65 | if (buf.length % size !== 0) { 66 | throw new RangeError( 67 | `Buffer length (${buf.length}) must be a multiple of size (${size})` 68 | ); 69 | } 70 | } 71 | 72 | export function bufferToHexArray( 73 | buf: Buffer, 74 | size: number, 75 | endian: Endian 76 | ): string[] { 77 | const hex: string[] = []; 78 | 79 | for (let i = 0; i < buf.length; i += size) { 80 | const chunk: string[] = []; 81 | for (let j = 0; j < size; j++) { 82 | const chunkIndex = endian === 'big' ? j : size - j - 1; 83 | chunk.push(buf[i + chunkIndex].toString(16).padStart(2, '0')); 84 | } 85 | hex.push(chunk.join('')); 86 | } 87 | 88 | return hex; 89 | } 90 | 91 | export function bignumberToHex(bignumber: BigNumber): string { 92 | const hex = bignumber.toString(16); 93 | if (hex.charAt(0) === '-') { 94 | throw new Error('Converting negative numbers to Buffers not supported yet'); 95 | } 96 | return hex; 97 | } 98 | 99 | export function hexToBuffer(hex: string, size: number, endian: Endian): Buffer { 100 | const len = Math.ceil(hex.length / (2 * size)) * size; 101 | const buf = Buffer.alloc(len); 102 | 103 | while (hex.length < 2 * len) { 104 | hex = '0' + hex; 105 | } 106 | 107 | const hx = hex 108 | .split(new RegExp('(.{' + 2 * size + '})')) 109 | .filter(s => s.length > 0); 110 | 111 | hx.forEach((chunk, i) => { 112 | for (let j = 0; j < size; j++) { 113 | const ix = i * size + (endian === 'big' ? j : size - j - 1); 114 | buf[ix] = parseInt(chunk.slice(j * 2, j * 2 + 2), 16); 115 | } 116 | }); 117 | 118 | return buf; 119 | } 120 | 121 | function toMpintBuffer(bignumber: BigNumber): Buffer { 122 | const buf = toBuffer(bignumber.abs(), {size: 1, endian: 'big'}); 123 | 124 | let len = buf.length === 1 && buf[0] === 0 ? 0 : buf.length; 125 | 126 | if (buf[0] & 0x80) len++; 127 | 128 | const ret = Buffer.alloc(4 + len); 129 | if (len > 0) buf.copy(ret, 4 + (buf[0] & 0x80 ? 1 : 0)); 130 | if (buf[0] & 0x80) ret[4] = 0; 131 | 132 | ret[0] = len & (0xff << 24); 133 | ret[1] = len & (0xff << 16); 134 | ret[2] = len & (0xff << 8); 135 | ret[3] = len & (0xff << 0); 136 | 137 | // Two's compliment for negative integers 138 | const isNeg = bignumber.lt(0); 139 | if (isNeg) { 140 | for (let i = 4; i < ret.length; i++) { 141 | ret[i] = 0xff - ret[i]; 142 | } 143 | } 144 | ret[4] = (ret[4] & 0x7f) | (isNeg ? 0x80 : 0); 145 | if (isNeg) ret[ret.length - 1]++; 146 | 147 | return ret; 148 | } 149 | -------------------------------------------------------------------------------- /src/helpers/constants.ts: -------------------------------------------------------------------------------- 1 | export enum TransactionType { 2 | SEND, 3 | SIGNATURE, 4 | DELEGATE, 5 | VOTE, 6 | MULTI, 7 | DAPP, 8 | IN_TRANSFER, 9 | OUT_TRANSFER, 10 | CHAT_MESSAGE, 11 | STATE, 12 | } 13 | 14 | export type MessageTypes = 1 | 2 | 3; 15 | 16 | /** 17 | * Message type 18 | * 19 | * @see https://github.com/Adamant-im/adamant/wiki/Message-Types 20 | */ 21 | export enum MessageType { 22 | Chat = 1, 23 | Rich = 2, 24 | Signal = 3, 25 | } 26 | 27 | export const MAX_VOTES_PER_TRANSACTION = 33; 28 | 29 | /** 30 | * 4 seconds 31 | */ 32 | export const HEALTH_CHECK_TIMEOUT = 4000; 33 | 34 | export const DEFAULT_GET_REQUEST_RETRIES = 3; 35 | 36 | export const SAT = 100_000_000; 37 | 38 | export const fees = { 39 | send: 50000000, 40 | vote: 1000000000, 41 | secondsignature: 500000000, 42 | delegate: 30000000000, 43 | multisignature: 500000000, 44 | dapp: 2500000000, 45 | old_chat_message: 500000, 46 | chat_message: 100000, 47 | profile_update: 5000000, 48 | avatar_upload: 10000000, 49 | state_store: 100000, 50 | }; 51 | -------------------------------------------------------------------------------- /src/helpers/encryptor.ts: -------------------------------------------------------------------------------- 1 | import sodium from 'sodium-browserify-tweetnacl'; 2 | import nacl from 'tweetnacl'; 3 | import ed2curve from 'ed2curve'; 4 | import {KeyPair, createKeypairFromPassphrase} from './keys'; 5 | 6 | export const bytesToHex = (bytes: Uint8Array) => { 7 | let hex = ''; 8 | 9 | for (const byte of bytes) { 10 | hex += (byte >>> 4).toString(16); 11 | hex += (byte & 0xf).toString(16); 12 | } 13 | 14 | return hex; 15 | }; 16 | 17 | export const hexToBytes = (hex: string) => { 18 | const bytes: number[] = []; 19 | 20 | for (let c = 0; c < hex.length; c += 2) { 21 | bytes.push(parseInt(hex.slice(c, c + 2), 16)); 22 | } 23 | 24 | return Uint8Array.from(bytes); 25 | }; 26 | 27 | export const utf8ArrayToStr = (array: Uint8Array) => { 28 | const len = array.length; 29 | let out = ''; 30 | let i = 0; 31 | let c: number; 32 | let char2: number; 33 | let char3: number; 34 | 35 | while (i < len) { 36 | c = array[i++]; 37 | switch (c >> 4) { 38 | case 0: 39 | case 1: 40 | case 2: 41 | case 3: 42 | case 4: 43 | case 5: 44 | case 6: 45 | case 7: 46 | // 0xxxxxxx 47 | out += String.fromCharCode(c); 48 | break; 49 | case 12: 50 | case 13: 51 | // 110x xxxx 10xx xxxx 52 | char2 = array[i++]; 53 | out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f)); 54 | break; 55 | case 14: 56 | // 1110 xxxx 10xx xxxx 10xx xxxx 57 | char2 = array[i++]; 58 | char3 = array[i++]; 59 | out += String.fromCharCode( 60 | ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0) 61 | ); 62 | break; 63 | } 64 | } 65 | 66 | return out; 67 | }; 68 | 69 | export const encodeMessage = ( 70 | msg: string, 71 | keypair: KeyPair, 72 | recipientPublicKey: Uint8Array | string 73 | ) => { 74 | const nonce = Buffer.allocUnsafe(24); 75 | sodium.randombytes(nonce); 76 | 77 | const plainText = Buffer.from(msg.toString()); 78 | const DHSecretKey = ed2curve.convertSecretKey(keypair.privateKey); 79 | 80 | let publicKey = recipientPublicKey; 81 | 82 | if (typeof publicKey === 'string') { 83 | publicKey = hexToBytes(publicKey); 84 | } 85 | 86 | const DHPublicKey = ed2curve.convertPublicKey(publicKey); 87 | 88 | if (!DHPublicKey) { 89 | throw new Error('encodeMessage: invalid key'); 90 | } 91 | 92 | const encrypted = nacl.box(plainText, nonce, DHPublicKey, DHSecretKey); 93 | 94 | return { 95 | message: bytesToHex(encrypted), 96 | own_message: bytesToHex(nonce), 97 | }; 98 | }; 99 | 100 | export const decodeMessage = ( 101 | message: string, 102 | senderPublicKey: Uint8Array | string, 103 | keyPairOrPassphrase: string | KeyPair, 104 | nonce: string 105 | ) => { 106 | const keypair = 107 | typeof keyPairOrPassphrase === 'string' 108 | ? createKeypairFromPassphrase(keyPairOrPassphrase) 109 | : keyPairOrPassphrase; 110 | 111 | const publicKey = 112 | typeof senderPublicKey === 'string' 113 | ? hexToBytes(senderPublicKey) 114 | : senderPublicKey; 115 | 116 | if (typeof message !== 'string') { 117 | throw new Error('decodeMessage message should be a string'); 118 | } 119 | 120 | if (typeof nonce !== 'string') { 121 | throw new Error('decodeMessage: nonce should be a string'); 122 | } 123 | 124 | if (!(publicKey instanceof Uint8Array)) { 125 | throw new Error( 126 | 'decodeMessage: senderPublicKey should be a string or an instance of Uint8Array' 127 | ); 128 | } 129 | 130 | const DHPublicKey = ed2curve.convertPublicKey(publicKey); 131 | 132 | if (!DHPublicKey) { 133 | throw new Error('decodeMessage: invalid key'); 134 | } 135 | 136 | const {privateKey} = keypair; 137 | const DHSecretKey = ed2curve.convertSecretKey(privateKey); 138 | 139 | const decrypted = nacl.box.open( 140 | hexToBytes(message), 141 | hexToBytes(nonce), 142 | DHPublicKey, 143 | DHSecretKey 144 | ); 145 | 146 | return decrypted ? utf8ArrayToStr(decrypted) : ''; 147 | }; 148 | -------------------------------------------------------------------------------- /src/helpers/healthCheck.ts: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | import {HEALTH_CHECK_TIMEOUT} from './constants'; 3 | import {Logger} from './logger'; 4 | import {unixTimestamp} from './time'; 5 | import {parseUrl} from './url'; 6 | 7 | import {GetNodeStatusResponseDto} from '../api/generated'; 8 | import {AdamantApiResult, getRandomIntInclusive} from './validator'; 9 | import {WebSocketClient, WsOptions} from './wsClient'; 10 | 11 | export interface NodeManagerOptions { 12 | nodes: string[]; 13 | timeout?: number; 14 | socket?: WebSocketClient; 15 | checkHealthAtStartup?: boolean; 16 | } 17 | 18 | export interface ActiveNode { 19 | node: string; 20 | ping: number; 21 | baseURL: string; 22 | ip?: string; 23 | isHttps: boolean; 24 | height: number; 25 | heightEpsilon: number; 26 | socketSupport: boolean; 27 | wsPort: number; 28 | outOfSync?: boolean; 29 | } 30 | 31 | const CHECK_NODES_INTERVAL = 60 * 5 * 1000; // Update active nodes every 5 minutes 32 | const HEIGHT_EPSILON = 5; // Used to group nodes by height and choose synced 33 | 34 | export class NodeManager { 35 | options: NodeManagerOptions; 36 | 37 | public node: string; 38 | public socket?: WebSocketClient; 39 | 40 | protected logger: Logger; 41 | 42 | private onReadyCallback?: () => void; 43 | 44 | private initialized = false; 45 | private isCheckingNodes = false; 46 | 47 | constructor(logger: Logger, options: NodeManagerOptions) { 48 | this.options = { 49 | timeout: HEALTH_CHECK_TIMEOUT, 50 | checkHealthAtStartup: true, 51 | ...options, 52 | }; 53 | 54 | const {socket, nodes, checkHealthAtStartup} = this.options; 55 | 56 | this.logger = logger; 57 | this.socket = socket; 58 | 59 | this.node = nodes[0]; 60 | 61 | if (checkHealthAtStartup) { 62 | this.updateNodes(true); 63 | 64 | setInterval(() => this.updateNodes(true), CHECK_NODES_INTERVAL); 65 | } else { 66 | this.ready(); 67 | } 68 | } 69 | 70 | public onReady(callback: () => void) { 71 | this.onReadyCallback = callback; 72 | } 73 | 74 | public initSocket(options: WebSocketClient | WsOptions) { 75 | if (options instanceof WebSocketClient) { 76 | this.socket = options; 77 | } else { 78 | this.socket = new WebSocketClient({logger: this.logger, ...options}); 79 | } 80 | } 81 | 82 | private ready() { 83 | if (this.onReadyCallback) { 84 | this.onReadyCallback(); 85 | } 86 | 87 | this.initialized = true; 88 | } 89 | 90 | async updateNodes(isPlannedUpdate = false) { 91 | if (this.isCheckingNodes) { 92 | return; 93 | } 94 | 95 | this.isCheckingNodes = true; 96 | 97 | if (!isPlannedUpdate) { 98 | this.logger.warn( 99 | '[ADAMANT js-api] Health check: Forcing to update active nodes…' 100 | ); 101 | } 102 | 103 | const activeNodes = await this.checkNodes(); 104 | 105 | await this.chooseNode(activeNodes, !isPlannedUpdate); 106 | 107 | if (!this.initialized) { 108 | this.ready(); 109 | } 110 | 111 | this.isCheckingNodes = false; 112 | } 113 | 114 | async chooseNode(activeNodes: ActiveNode[], forceChangeActiveNode?: boolean) { 115 | const {logger, socket} = this; 116 | 117 | const {length: activeNodesCount} = activeNodes; 118 | if (!activeNodesCount) { 119 | const totalNodesCount = this.options.nodes.length; 120 | 121 | logger.error( 122 | `[ADAMANT js-api] Health check: All of ${totalNodesCount} nodes are unavailable. Check internet connection and nodes list in config.` 123 | ); 124 | return; 125 | } 126 | 127 | let outOfSyncCount = 0; 128 | 129 | if (activeNodesCount === 1) { 130 | this.node = activeNodes[0].node; 131 | } else if (activeNodesCount === 2) { 132 | const [h0, h1] = activeNodes; 133 | 134 | this.node = h0.height > h1.height ? h0.node : h1.node; 135 | 136 | // Mark node outOfSync if needed 137 | if (h0.heightEpsilon > h1.heightEpsilon) { 138 | activeNodes[1].outOfSync = true; 139 | outOfSyncCount += 1; 140 | } else if (h0.heightEpsilon < h1.heightEpsilon) { 141 | activeNodes[0].outOfSync = true; 142 | outOfSyncCount += 1; 143 | } 144 | } else { 145 | // Removing lodash: const groups = _.groupBy(liveNodes, n => n.heightEpsilon); 146 | const groups = activeNodes.reduce( 147 | (grouped: {[heightEpsilon: number]: ActiveNode[]}, node) => { 148 | const {heightEpsilon} = node; 149 | 150 | if (!grouped[heightEpsilon]) { 151 | grouped[heightEpsilon] = []; 152 | } 153 | 154 | grouped[heightEpsilon].push(node); 155 | 156 | return grouped; 157 | }, 158 | {} 159 | ); 160 | 161 | let biggestGroup: ActiveNode[] = []; 162 | let biggestGroupSize = 0; 163 | 164 | for (const key in groups) { 165 | if (Object.prototype.hasOwnProperty.call(groups, key)) { 166 | const group = groups[key]; 167 | 168 | if (groups[key].length > biggestGroupSize) { 169 | biggestGroup = group; 170 | biggestGroupSize = group.length; 171 | } 172 | } 173 | } 174 | 175 | // All the nodes from the biggestGroup list are considered to be in sync, all the others are not 176 | for (const node of activeNodes) { 177 | node.outOfSync = !biggestGroup.includes(node); 178 | } 179 | 180 | outOfSyncCount = activeNodes.length - biggestGroup.length; 181 | 182 | biggestGroup.sort((a, b) => a.ping - b.ping); 183 | 184 | if ( 185 | forceChangeActiveNode && 186 | biggestGroup.length > 1 && 187 | this.node === biggestGroup[0].node 188 | ) { 189 | // Use random node from which are synced 190 | const randomIndex = getRandomIntInclusive(1, biggestGroup.length - 1); 191 | this.node = biggestGroup[randomIndex].node; 192 | } else { 193 | // Use node with minimum ping among synced 194 | this.node = biggestGroup[0].node; 195 | } 196 | } 197 | 198 | socket?.reviseConnection(activeNodes); 199 | 200 | const {nodes} = this.options; 201 | 202 | const unavailableCount = nodes.length - activeNodesCount; 203 | const supportedCount = activeNodesCount - outOfSyncCount; 204 | 205 | let nodesInfoString = ''; 206 | 207 | if (unavailableCount) { 208 | nodesInfoString += `, ${unavailableCount} nodes didn't respond`; 209 | } 210 | 211 | if (outOfSyncCount) { 212 | nodesInfoString += `, ${outOfSyncCount} nodes are not synced`; 213 | } 214 | 215 | this.logger.log( 216 | `[ADAMANT js-api] Health check: Found ${supportedCount} supported and synced nodes${nodesInfoString}. Active node is ${this.node}.` 217 | ); 218 | } 219 | 220 | async checkNode(node: string) { 221 | try { 222 | const {timeout} = this.options; 223 | 224 | const response = await axios.get< 225 | AdamantApiResult 226 | >(`${node}/api/node/status`, { 227 | timeout, 228 | }); 229 | 230 | return response.data; 231 | } catch (error) { 232 | return {success: false} as {success: false}; 233 | } 234 | } 235 | 236 | async checkNodes() { 237 | const {nodes} = this.options; 238 | 239 | const activeNodes: ActiveNode[] = []; 240 | 241 | for (const node of nodes) { 242 | const start = unixTimestamp(); 243 | 244 | const response = await this.checkNode(node); 245 | 246 | const ping = unixTimestamp() - start; 247 | 248 | if (!response.success) { 249 | this.logger.log( 250 | `[ADAMANT js-api] Health check: Node ${node} hasn't returned its status` 251 | ); 252 | continue; 253 | } 254 | 255 | const {wsClient, network} = response; 256 | 257 | const socketSupport = wsClient.enabled; 258 | const wsPort = wsClient.port; 259 | 260 | const {height} = network; 261 | 262 | activeNodes.push({ 263 | ...(await parseUrl(node)), 264 | node, 265 | ping, 266 | height, 267 | heightEpsilon: Math.round(height / HEIGHT_EPSILON), 268 | socketSupport, 269 | wsPort, 270 | }); 271 | } 272 | 273 | return activeNodes; 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /src/helpers/keys.ts: -------------------------------------------------------------------------------- 1 | import sodium from 'sodium-browserify-tweetnacl'; 2 | import crypto from 'crypto'; 3 | import {mnemonicToSeedSync, generateMnemonic} from 'bip39'; 4 | 5 | import * as bignum from './bignumber'; 6 | import type {AdamantAddress} from '../api'; 7 | 8 | export interface KeyPair { 9 | publicKey: Buffer; 10 | privateKey: Buffer; 11 | } 12 | 13 | export const createNewPassphrase = () => generateMnemonic(); 14 | 15 | export const makeKeypairFromHash = (hash: Buffer): KeyPair => { 16 | const keypair = sodium.crypto_sign_seed_keypair(hash); 17 | 18 | return { 19 | publicKey: keypair.publicKey, 20 | privateKey: keypair.secretKey, 21 | }; 22 | }; 23 | 24 | export const createHashFromPassphrase = (passphrase: string) => 25 | crypto 26 | .createHash('sha256') 27 | .update(mnemonicToSeedSync(passphrase).toString('hex'), 'hex') 28 | .digest(); 29 | 30 | export const createKeypairFromPassphrase = (passphrase: string) => { 31 | const hash = createHashFromPassphrase(passphrase); 32 | 33 | return makeKeypairFromHash(hash); 34 | }; 35 | 36 | export const createAddressFromPublicKey = ( 37 | publicKey: Buffer | string 38 | ): AdamantAddress => { 39 | const hash = crypto.createHash('sha256'); 40 | 41 | if (typeof publicKey === 'string') { 42 | hash.update(publicKey, 'hex'); 43 | } else { 44 | hash.update(publicKey); 45 | } 46 | 47 | const publicKeyBuffer = hash.digest(); 48 | 49 | const temp = Buffer.alloc(8); 50 | 51 | for (let i = 0; i < 8; i++) { 52 | temp[i] = publicKeyBuffer[7 - i]; 53 | } 54 | 55 | return `U${bignum.fromBuffer(temp)}`; 56 | }; 57 | -------------------------------------------------------------------------------- /src/helpers/logger.ts: -------------------------------------------------------------------------------- 1 | export enum LogLevel { 2 | Error, 3 | Warn, 4 | Info, 5 | Log, 6 | } 7 | 8 | export type CustomLogger = Record< 9 | 'error' | 'warn' | 'info' | 'log', 10 | (str: string) => void 11 | >; 12 | 13 | export const logLevels = ['error', 'warn', 'info', 'log'] as const; 14 | 15 | export type LogLevelName = (typeof logLevels)[number]; 16 | 17 | export class Logger { 18 | logger: CustomLogger; 19 | level: LogLevel; 20 | 21 | constructor( 22 | level: LogLevel | LogLevelName = LogLevel.Log, 23 | logger: CustomLogger = console 24 | ) { 25 | this.level = typeof level === 'number' ? level : logLevels.indexOf(level); 26 | this.logger = logger; 27 | } 28 | 29 | error(message: string) { 30 | if (this.level >= LogLevel.Error) { 31 | this.logger.error(message); 32 | } 33 | } 34 | 35 | warn(message: string) { 36 | if (this.level >= LogLevel.Warn) { 37 | this.logger.warn(message); 38 | } 39 | } 40 | 41 | info(message: string) { 42 | if (this.level >= LogLevel.Info) { 43 | this.logger.info(message); 44 | } 45 | } 46 | 47 | log(message: string) { 48 | if (this.level >= LogLevel.Log) { 49 | this.logger.log(message); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/helpers/tests/keys.test.ts: -------------------------------------------------------------------------------- 1 | import * as keys from '../keys'; 2 | import {mocked} from './mock-data/address'; 3 | 4 | describe('createNewPassphrase', () => { 5 | test('should return string that contains more than 11 words', () => { 6 | const passphrase = keys.createNewPassphrase(); 7 | 8 | expect(typeof passphrase).toBe('string'); 9 | expect(passphrase.split(' ').length).toBeGreaterThanOrEqual(12); 10 | }); 11 | }); 12 | 13 | describe('makeKeypairFromHash', () => { 14 | test('should create keypair with exact publicKey/privateKey values from hash', () => { 15 | const keypair = keys.makeKeypairFromHash(mocked.hash); 16 | 17 | expect(keypair.publicKey).toStrictEqual(mocked.publicKey); 18 | expect(keypair.privateKey).toStrictEqual(mocked.privateKey); 19 | }); 20 | }); 21 | 22 | describe('createHashFromPassphrase', () => { 23 | test('should create exact hash from the pass phrase', () => { 24 | const passphrase = 25 | 'wrap track hamster grocery casual talk theory half artist toast art essence'; 26 | 27 | const hash = keys.createHashFromPassphrase(passphrase); 28 | 29 | expect(hash).toStrictEqual(mocked.hash); 30 | }); 31 | }); 32 | 33 | describe('createKeypairFromPassphrase', () => { 34 | test('should create keypair with exact publicKey/privateKey values from pass phrase', () => { 35 | const keypair = keys.createKeypairFromPassphrase(mocked.passphrase); 36 | 37 | expect(keypair.publicKey).toStrictEqual(mocked.publicKey); 38 | expect(keypair.privateKey).toStrictEqual(mocked.privateKey); 39 | }); 40 | }); 41 | 42 | describe('createAddressFromPublicKey', () => { 43 | test('should return a string which matches the address pattern', () => { 44 | const address = keys.createAddressFromPublicKey(mocked.publicKey); 45 | 46 | expect(address).toBe(mocked.address); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /src/helpers/tests/logger.test.ts: -------------------------------------------------------------------------------- 1 | import {Logger, LogLevel} from '../logger'; 2 | 3 | const mockLogger = { 4 | log() {}, 5 | error() {}, 6 | warn() {}, 7 | info() {}, 8 | }; 9 | 10 | describe('logger: log', () => { 11 | const logLevel = LogLevel.Log; 12 | 13 | test('should log log level', done => { 14 | const logger = new Logger(logLevel, { 15 | ...mockLogger, 16 | log(str) { 17 | expect(str).toBe('log'); 18 | done(); 19 | }, 20 | }); 21 | 22 | logger.log('log'); 23 | }); 24 | 25 | test('should log info level', done => { 26 | const logger = new Logger(logLevel, { 27 | ...mockLogger, 28 | info(str) { 29 | expect(str).toBe('info'); 30 | done(); 31 | }, 32 | }); 33 | 34 | logger.info('info'); 35 | }); 36 | 37 | test('should log warn level', done => { 38 | const logger = new Logger(logLevel, { 39 | ...mockLogger, 40 | warn(str) { 41 | expect(str).toBe('warn'); 42 | done(); 43 | }, 44 | }); 45 | 46 | logger.warn('warn'); 47 | }); 48 | 49 | test('should log error level', done => { 50 | const logger = new Logger(logLevel, { 51 | ...mockLogger, 52 | error(str) { 53 | expect(str).toBe('error'); 54 | done(); 55 | }, 56 | }); 57 | 58 | logger.error('error'); 59 | }); 60 | }); 61 | 62 | describe('logger: info', () => { 63 | const logLevel = LogLevel.Info; 64 | 65 | test('should not log log level', done => { 66 | const logger = new Logger(logLevel, { 67 | ...mockLogger, 68 | log() { 69 | done('Log level has been called'); 70 | }, 71 | }); 72 | 73 | logger.log('log'); 74 | done(); 75 | }); 76 | 77 | test('should log info level', done => { 78 | const logger = new Logger(logLevel, { 79 | ...mockLogger, 80 | info(str) { 81 | expect(str).toBe('info'); 82 | done(); 83 | }, 84 | }); 85 | 86 | logger.info('info'); 87 | }); 88 | 89 | test('should log warn level', done => { 90 | const logger = new Logger(logLevel, { 91 | ...mockLogger, 92 | warn(str) { 93 | expect(str).toBe('warn'); 94 | done(); 95 | }, 96 | }); 97 | 98 | logger.warn('warn'); 99 | }); 100 | 101 | test('should log error level', done => { 102 | const logger = new Logger(logLevel, { 103 | ...mockLogger, 104 | error(str) { 105 | expect(str).toBe('error'); 106 | done(); 107 | }, 108 | }); 109 | 110 | logger.error('error'); 111 | }); 112 | }); 113 | 114 | describe('logger: warn', () => { 115 | const logLevel = LogLevel.Warn; 116 | 117 | test('should not log log level', done => { 118 | const logger = new Logger(logLevel, { 119 | ...mockLogger, 120 | log() { 121 | done('Log level has been called'); 122 | }, 123 | }); 124 | 125 | logger.log('log'); 126 | done(); 127 | }); 128 | 129 | test('should not log info level', done => { 130 | const logger = new Logger(logLevel, { 131 | ...mockLogger, 132 | info() { 133 | done('Info level has been called'); 134 | }, 135 | }); 136 | 137 | logger.info('info'); 138 | done(); 139 | }); 140 | 141 | test('should log warn level', done => { 142 | const logger = new Logger(logLevel, { 143 | ...mockLogger, 144 | warn(str) { 145 | expect(str).toBe('warn'); 146 | done(); 147 | }, 148 | }); 149 | 150 | logger.warn('warn'); 151 | }); 152 | 153 | test('should log error level', done => { 154 | const logger = new Logger(logLevel, { 155 | ...mockLogger, 156 | error(str) { 157 | expect(str).toBe('error'); 158 | done(); 159 | }, 160 | }); 161 | 162 | logger.error('error'); 163 | }); 164 | }); 165 | 166 | describe('logger: error', () => { 167 | const logLevel = LogLevel.Error; 168 | 169 | test('should not log log level', done => { 170 | const logger = new Logger(logLevel, { 171 | ...mockLogger, 172 | error(str) { 173 | expect(str).toBe('error'); 174 | done(); 175 | }, 176 | }); 177 | 178 | logger.log('log'); 179 | done(); 180 | }); 181 | 182 | test('should not log info level', done => { 183 | const logger = new Logger(logLevel, { 184 | ...mockLogger, 185 | info() { 186 | done('Info level has been called'); 187 | }, 188 | }); 189 | 190 | logger.info('info'); 191 | done(); 192 | }); 193 | 194 | test('should not log warn level', done => { 195 | const logger = new Logger(logLevel, { 196 | ...mockLogger, 197 | warn() { 198 | done('Warn level has been called'); 199 | }, 200 | }); 201 | 202 | logger.warn('warn'); 203 | done(); 204 | }); 205 | 206 | test('should log error level', done => { 207 | const logger = new Logger(logLevel, { 208 | ...mockLogger, 209 | error(str) { 210 | expect(str).toBe('error'); 211 | done(); 212 | }, 213 | }); 214 | 215 | logger.error('error'); 216 | }); 217 | }); 218 | -------------------------------------------------------------------------------- /src/helpers/tests/mock-data/address.ts: -------------------------------------------------------------------------------- 1 | export const mocked = { 2 | address: 'U6687642817984673870' as const, 3 | passphrase: 4 | 'wrap track hamster grocery casual talk theory half artist toast art essence', 5 | publicKey: Buffer.from( 6 | '7db9b51bc75fed7b8e631e2efaad38305b12c6b3d3d9f6af3498fdcb7b35c284', 7 | 'hex' 8 | ), 9 | privateKey: Buffer.from( 10 | '24a26e6cd6283528f6e2637dcf834434176cf8696647bd4aa6223f349882dc967db9b51bc75fed7b8e631e2efaad38305b12c6b3d3d9f6af3498fdcb7b35c284', 11 | 'hex' 12 | ), 13 | hash: Buffer.from( 14 | '24a26e6cd6283528f6e2637dcf834434176cf8696647bd4aa6223f349882dc96', 15 | 'hex' 16 | ), 17 | recipientId: 'U1234567890123456789' as const, 18 | amount: 99999999999, 19 | }; 20 | -------------------------------------------------------------------------------- /src/helpers/tests/time.test.ts: -------------------------------------------------------------------------------- 1 | import {getEpochTime, EPOCH_TIME} from '../time'; 2 | 3 | describe('getTime', () => { 4 | test('should return 0 for epoch time', () => { 5 | expect(getEpochTime(EPOCH_TIME.getTime())).toBe(0); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /src/helpers/tests/transactions.test.ts: -------------------------------------------------------------------------------- 1 | import {TransactionType} from '../constants'; 2 | import { 3 | createChatTransaction, 4 | createDelegateTransaction, 5 | createSendTransaction, 6 | createStateTransaction, 7 | createVoteTransaction, 8 | } from '../transactions/index'; 9 | import {mocked} from './mock-data/address'; 10 | 11 | beforeAll(() => { 12 | jest.useFakeTimers(); 13 | jest.setSystemTime(new Date('2021-02-18')); 14 | }); 15 | 16 | /** 17 | * Expected timestamp accross all the created transactions. 18 | */ 19 | const timestamp = 109234800; 20 | 21 | const keyPair = { 22 | publicKey: mocked.publicKey, 23 | privateKey: mocked.privateKey, 24 | }; 25 | 26 | const {address: senderId} = mocked; 27 | const senderPublicKey = mocked.publicKey.toString('hex'); 28 | 29 | describe('createSendTransaction', () => { 30 | const type = TransactionType.SEND; 31 | 32 | const {recipientId, amount} = mocked; 33 | 34 | test('should create simple send transaction', () => { 35 | const transaction = createSendTransaction({recipientId, amount, keyPair}); 36 | 37 | const expectedSignature = 38 | 'd15cf87edecf808454ac0b7f4d80fc07b72dabe43f7e8ee721f4a208831b18278c9635deb1217610c720c8800daf45b2e4d2dd8ae817111a57b67017424f9502'; 39 | 40 | expect(transaction).toStrictEqual({ 41 | type, 42 | amount, 43 | recipientId, 44 | senderId, 45 | senderPublicKey, 46 | timestamp, 47 | asset: {}, 48 | signature: expectedSignature, 49 | }); 50 | }); 51 | }); 52 | 53 | describe('createVoteTransaction', () => { 54 | const type = TransactionType.VOTE; 55 | 56 | test('should create simple vote transaction', () => { 57 | const votes = [ 58 | '+b3d0c0b99f64d0960324089eb678e90d8bcbb3dd8c73ee748e026f8b9a5b5468', 59 | '-9ef1f6212ae871716cfa2d04e3dc5339e8fe75f89818be21ee1d75004983e2a8', 60 | ]; 61 | 62 | const transaction = createVoteTransaction({keyPair, votes}); 63 | 64 | const expectedSignature = 65 | '53101dc124c0be5d6cafc2116a661884594499ea3fae37c09f4a6514ee4a60523113420e62a5ff001394461f5b72f5fa288cfe314fc05adedf2d367f3d2bd901'; 66 | 67 | expect(transaction).toStrictEqual({ 68 | type, 69 | timestamp, 70 | amount: 0, 71 | senderPublicKey, 72 | senderId, 73 | asset: { 74 | votes, 75 | }, 76 | recipientId: senderId, 77 | signature: expectedSignature, 78 | }); 79 | }); 80 | }); 81 | 82 | describe('createDelegateTransaction', () => { 83 | const type = TransactionType.DELEGATE; 84 | const username = 'admtest'; 85 | 86 | test('should create simple delegate transaction', () => { 87 | const data = { 88 | keyPair, 89 | username, 90 | }; 91 | 92 | const transaction = createDelegateTransaction(data); 93 | 94 | const expectedSignature = 95 | '602ead104c66005c2812a5e96e98506771f8ac5e2f21f002e7acb05a5ee0a3db478f2fec993e6997322dfa85cc6dde6286835e12f5211de84bfc1d3add424e00'; 96 | 97 | expect(transaction).toStrictEqual({ 98 | type, 99 | amount: 0, 100 | timestamp, 101 | senderPublicKey, 102 | senderId, 103 | recipientId: null, 104 | asset: { 105 | delegate: { 106 | username, 107 | publicKey: senderPublicKey, 108 | }, 109 | }, 110 | signature: expectedSignature, 111 | }); 112 | }); 113 | }); 114 | 115 | describe('Create chat transaction', () => { 116 | const type = TransactionType.CHAT_MESSAGE; 117 | 118 | test('should create simple chat transaction', () => { 119 | const {recipientId, amount} = mocked; 120 | 121 | const data = { 122 | keyPair, 123 | amount, 124 | recipientId, 125 | message: 'f96383619244c7e06f39f592b55cc551acc72710', 126 | own_message: 'd0801b9a647fd1469883f918ec616241c79d6f6f7914ddb0', 127 | message_type: 1, 128 | }; 129 | 130 | const transaction = createChatTransaction(data); 131 | 132 | const expectedSignature = 133 | 'd720eb7cc1a1ac863a21b02d2537b283bfa056d81761ca133d07253d4d0bd479c321b8cd766bf20d4f5b2de27f7aae8783449f28a8c8ffbf9a9109fe73500f00'; 134 | 135 | expect(transaction).toStrictEqual({ 136 | type, 137 | recipientId, 138 | timestamp, 139 | amount, 140 | senderPublicKey, 141 | senderId, 142 | asset: { 143 | chat: { 144 | message: data.message, 145 | own_message: data.own_message, 146 | type: data.message_type, 147 | }, 148 | }, 149 | signature: expectedSignature, 150 | }); 151 | }); 152 | }); 153 | 154 | describe('Create state transaction', () => { 155 | const type = TransactionType.STATE; 156 | 157 | test('should create simple state transaction', () => { 158 | const data = { 159 | key: 'key', 160 | value: 'value', 161 | }; 162 | 163 | const transaction = createStateTransaction({...data, keyPair}); 164 | 165 | const expectedSignature = 166 | '8d1bf8673b83eef10324414b0793ee26942e9379a9c38b1578a7c4df68cd922dd8a007bd6c03b5a0b6e28b0ecc4be8154fb72435d783a54dc35ac4614d095a09'; 167 | 168 | expect(transaction).toStrictEqual({ 169 | type, 170 | senderId, 171 | senderPublicKey, 172 | timestamp, 173 | recipientId: null, 174 | amount: 0, 175 | asset: { 176 | state: { 177 | key: data.key, 178 | value: data.value, 179 | type: 0, 180 | }, 181 | }, 182 | signature: expectedSignature, 183 | }); 184 | }); 185 | }); 186 | -------------------------------------------------------------------------------- /src/helpers/tests/validator.test.ts: -------------------------------------------------------------------------------- 1 | import {MessageType} from '../constants'; 2 | import * as validator from '../validator'; 3 | 4 | describe('isNumeric', () => { 5 | test('should return false for a number', () => { 6 | expect(validator.isNumeric(3)).toBe(false); 7 | }); 8 | 9 | test('should return false for Infinity', () => { 10 | expect(validator.isNumeric(Infinity)).toBe(false); 11 | }); 12 | 13 | test('should return false for an object', () => { 14 | expect(validator.isNumeric({})).toBe(false); 15 | }); 16 | 17 | test('should return false for undefined', () => { 18 | expect(validator.isNumeric(undefined)).toBe(false); 19 | }); 20 | 21 | test('should return false for NaN', () => { 22 | expect(validator.isNumeric(NaN)).toBe(false); 23 | }); 24 | 25 | test('should return false for `n3.14`', () => { 26 | expect(validator.isNumeric('n3.14')).toBe(false); 27 | }); 28 | 29 | test('should return true for `3,14`', () => { 30 | expect(validator.isNumeric('3,14')).toBe(true); 31 | }); 32 | 33 | test('should return true for `3.14`', () => { 34 | expect(validator.isNumeric('3.14')).toBe(true); 35 | }); 36 | 37 | test('should return true for ` 3.14`', () => { 38 | expect(validator.isNumeric(' 3.14')).toBe(true); 39 | }); 40 | }); 41 | 42 | describe('isPassphrase', () => { 43 | test('should return false for a number', () => { 44 | expect(validator.isPassphrase(3)).toBe(false); 45 | }); 46 | 47 | test('should return false for an object', () => { 48 | expect(validator.isPassphrase({})).toBe(false); 49 | }); 50 | 51 | test('should return false for undefined', () => { 52 | expect(validator.isPassphrase(undefined)).toBe(false); 53 | }); 54 | 55 | test('should return false for NaN', () => { 56 | expect(validator.isPassphrase(NaN)).toBe(false); 57 | }); 58 | 59 | test('should return false for a too short string', () => { 60 | expect(validator.isPassphrase('short')).toBe(false); 61 | }); 62 | 63 | test('should return true for a 12 word string', () => { 64 | expect(validator.isPassphrase('word '.repeat(12))).toBe(true); 65 | }); 66 | }); 67 | 68 | describe('isAdmAddress', () => { 69 | test('should return false for a number', () => { 70 | expect(validator.isAdmAddress(3)).toBe(false); 71 | }); 72 | 73 | test('should return false for an object', () => { 74 | expect(validator.isAdmAddress({})).toBe(false); 75 | }); 76 | 77 | test('should return false for undefined', () => { 78 | expect(validator.isAdmAddress(undefined)).toBe(false); 79 | }); 80 | 81 | test('should return false for NaN', () => { 82 | expect(validator.isAdmAddress(NaN)).toBe(false); 83 | }); 84 | 85 | test('should return false for U123', () => { 86 | expect(validator.isAdmAddress('U123')).toBe(false); 87 | }); 88 | 89 | test('should return false for ` U123456`', () => { 90 | expect(validator.isAdmAddress(' U123456')).toBe(false); 91 | }); 92 | 93 | test('should return false for `U123213N123`', () => { 94 | expect(validator.isAdmAddress('U123213N123')).toBe(false); 95 | }); 96 | 97 | test('should return true for U123456', () => { 98 | expect(validator.isAdmAddress('U1234506')).toBe(true); 99 | }); 100 | 101 | test('should return true for U01234561293812931283918239', () => { 102 | expect(validator.isAdmAddress('U01234561293812931283918239')).toBe(true); 103 | }); 104 | }); 105 | 106 | describe('isAdmPublicKey', () => { 107 | test('should return false for a number', () => { 108 | expect(validator.isAdmPublicKey(3)).toBe(false); 109 | }); 110 | 111 | test('should return false for an object', () => { 112 | expect(validator.isAdmPublicKey({})).toBe(false); 113 | }); 114 | 115 | test('should return false for undefined', () => { 116 | expect(validator.isAdmPublicKey(undefined)).toBe(false); 117 | }); 118 | 119 | test('should return false for NaN', () => { 120 | expect(validator.isAdmPublicKey(NaN)).toBe(false); 121 | }); 122 | 123 | test('should return false for a short string', () => { 124 | expect(validator.isAdmPublicKey('0f')).toBe(false); 125 | }); 126 | 127 | test('should return false for a string that contains `L`', () => { 128 | expect( 129 | validator.isAdmPublicKey( 130 | 'Le003f782cd1c1c84a6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 131 | ) 132 | ).toBe(false); 133 | }); 134 | 135 | test('should return true for a public key that starts with a number', () => { 136 | expect( 137 | validator.isAdmPublicKey( 138 | '4e003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 139 | ) 140 | ).toBe(true); 141 | }); 142 | 143 | test('should return true for a public key that starts with a letter', () => { 144 | expect( 145 | validator.isAdmPublicKey( 146 | 'e4003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 147 | ) 148 | ).toBe(true); 149 | }); 150 | }); 151 | 152 | describe('isAdmVoteForAddress', () => { 153 | test('should return false for a number', () => { 154 | expect(validator.isAdmVoteForAddress(3)).toBe(false); 155 | }); 156 | 157 | test('should return false for an object', () => { 158 | expect(validator.isAdmVoteForAddress({})).toBe(false); 159 | }); 160 | 161 | test('should return false for undefined', () => { 162 | expect(validator.isAdmVoteForAddress(undefined)).toBe(false); 163 | }); 164 | 165 | test('should return false for NaN', () => { 166 | expect(validator.isAdmVoteForAddress(NaN)).toBe(false); 167 | }); 168 | 169 | test('should return false for a short string', () => { 170 | expect(validator.isAdmVoteForAddress('0f')).toBe(false); 171 | }); 172 | 173 | test('should return false for a string that starts with `L`', () => { 174 | expect(validator.isAdmVoteForAddress('L01234561293812931283918239')).toBe( 175 | false 176 | ); 177 | }); 178 | 179 | test('should return false for an address that starts with a number', () => { 180 | expect(validator.isAdmVoteForAddress('0U1234561293812931283918239')).toBe( 181 | false 182 | ); 183 | }); 184 | 185 | test('should return false for an address that starts with a letter', () => { 186 | expect(validator.isAdmVoteForAddress('U01234561293812931283918239')).toBe( 187 | false 188 | ); 189 | }); 190 | 191 | test('should return true for an address with a plus', () => { 192 | expect(validator.isAdmVoteForAddress('+U01234561293812931283918239')).toBe( 193 | true 194 | ); 195 | }); 196 | 197 | test('should return true for an address with a minus', () => { 198 | expect(validator.isAdmVoteForAddress('+U01234561293812931283918239')).toBe( 199 | true 200 | ); 201 | }); 202 | }); 203 | 204 | describe('isAdmVoteForPublicKey', () => { 205 | test('should return false for a number', () => { 206 | expect(validator.isAdmVoteForPublicKey(3)).toBe(false); 207 | }); 208 | 209 | test('should return false for an object', () => { 210 | expect(validator.isAdmVoteForPublicKey({})).toBe(false); 211 | }); 212 | 213 | test('should return false for undefined', () => { 214 | expect(validator.isAdmVoteForPublicKey(undefined)).toBe(false); 215 | }); 216 | 217 | test('should return false for NaN', () => { 218 | expect(validator.isAdmVoteForPublicKey(NaN)).toBe(false); 219 | }); 220 | 221 | test('should return false for a short string', () => { 222 | expect(validator.isAdmVoteForPublicKey('0f')).toBe(false); 223 | }); 224 | 225 | test('should return false for a string that starts with `L`', () => { 226 | expect( 227 | validator.isAdmVoteForPublicKey( 228 | '+L4e003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 229 | ) 230 | ).toBe(false); 231 | }); 232 | 233 | test('should return false for a public key that starts with a number', () => { 234 | expect( 235 | validator.isAdmVoteForPublicKey( 236 | '4e003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 237 | ) 238 | ).toBe(false); 239 | }); 240 | 241 | test('should return false for a public key that starts with a letter', () => { 242 | expect( 243 | validator.isAdmVoteForPublicKey( 244 | 'e4003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 245 | ) 246 | ).toBe(false); 247 | }); 248 | 249 | test('should return true for a public key with a plus', () => { 250 | expect( 251 | validator.isAdmVoteForPublicKey( 252 | '+4e003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 253 | ) 254 | ).toBe(true); 255 | }); 256 | 257 | test('should return true for a public key with a minus', () => { 258 | expect( 259 | validator.isAdmVoteForPublicKey( 260 | '+4e003f782cd1c1c84A6767a871321af2ecdb3da8d8f6b8d1f13179835b6ec432' 261 | ) 262 | ).toBe(true); 263 | }); 264 | }); 265 | 266 | describe('isAdmVoteForDelegateName', () => { 267 | test('should return false for a number', () => { 268 | expect(validator.isAdmVoteForDelegateName(3)).toBe(false); 269 | }); 270 | 271 | test('should return false for an object', () => { 272 | expect(validator.isAdmVoteForDelegateName({})).toBe(false); 273 | }); 274 | 275 | test('should return false for undefined', () => { 276 | expect(validator.isAdmVoteForDelegateName(undefined)).toBe(false); 277 | }); 278 | 279 | test('should return false for NaN', () => { 280 | expect(validator.isAdmVoteForDelegateName(NaN)).toBe(false); 281 | }); 282 | 283 | test('should return false for a short string', () => { 284 | expect(validator.isAdmVoteForDelegateName('0f')).toBe(false); 285 | }); 286 | 287 | test('should return false for a vote without delegate name', () => { 288 | expect(validator.isAdmVoteForDelegateName('+')).toBe(false); 289 | }); 290 | 291 | test('should return false for a too long delegate name', () => { 292 | expect( 293 | validator.isAdmVoteForDelegateName('+e003f782cd1c1c84A6767a871321af2e') 294 | ).toBe(false); 295 | }); 296 | 297 | test('should return false for a vote that starts with a number', () => { 298 | expect(validator.isAdmVoteForDelegateName('4darksinc')).toBe(false); 299 | }); 300 | 301 | test('should return false for a vote that starts with a letter', () => { 302 | expect(validator.isAdmVoteForDelegateName('darksinc')).toBe(false); 303 | }); 304 | 305 | test('should return true for a delegate name with a plus', () => { 306 | expect(validator.isAdmVoteForDelegateName('+darksinc')).toBe(true); 307 | }); 308 | 309 | test('should return true for a delegate name with a minus', () => { 310 | expect(validator.isAdmVoteForDelegateName('+darksinc')).toBe(true); 311 | }); 312 | }); 313 | 314 | describe('validateMessage', () => { 315 | test('should return false for a number message', () => { 316 | expect(validator.validateMessage(3 as any).success).toBe(false); 317 | }); 318 | 319 | test('should return false for an object message', () => { 320 | expect(validator.validateMessage({} as any).success).toBe(false); 321 | }); 322 | 323 | test('should return true for an empty string message', () => { 324 | expect(validator.validateMessage('').success).toBe(true); 325 | }); 326 | 327 | test('should return false for an empty string rich message', () => { 328 | expect(validator.validateMessage('', MessageType.Rich).success).toBe(false); 329 | }); 330 | 331 | test('should return true for an empty string signal message', () => { 332 | expect(validator.validateMessage('', MessageType.Signal).success).toBe( 333 | true 334 | ); 335 | }); 336 | 337 | test('should return true for an empty json rich message', () => { 338 | expect(validator.validateMessage('{}', MessageType.Rich).success).toBe( 339 | true 340 | ); 341 | }); 342 | 343 | test('should return false for an empty json signal message', () => { 344 | expect(validator.validateMessage('{}', MessageType.Signal).success).toBe( 345 | true 346 | ); 347 | }); 348 | 349 | test('should return true for a json rich message with the given amount', () => { 350 | expect( 351 | validator.validateMessage('{"amount": "0.13"}', MessageType.Rich).success 352 | ).toBe(true); 353 | }); 354 | 355 | test('should return true for a json signal message with the given amount', () => { 356 | expect( 357 | validator.validateMessage('{"amount": "0.13"}', MessageType.Signal) 358 | .success 359 | ).toBe(true); 360 | }); 361 | 362 | test('should return false for a json rich message with uppercase coin name', () => { 363 | expect( 364 | validator.validateMessage( 365 | '{"amount": "0.13", "type": "ETH_transaction"}', 366 | MessageType.Rich 367 | ).success 368 | ).toBe(false); 369 | }); 370 | 371 | test('should return true for a json signal message with uppercase coin name', () => { 372 | expect( 373 | validator.validateMessage( 374 | '{"amount": "0.13", "type": "ETH_transaction"}', 375 | MessageType.Signal 376 | ).success 377 | ).toBe(true); 378 | }); 379 | 380 | test('should return true for a json rich message with lowercase coin name', () => { 381 | expect( 382 | validator.validateMessage( 383 | '{"amount": "0.13", "type": "eth_transaction"}', 384 | MessageType.Rich 385 | ).success 386 | ).toBe(true); 387 | }); 388 | 389 | test('should return true for a json signal message with lowercase coin name', () => { 390 | expect( 391 | validator.validateMessage( 392 | '{"amount": "0.13", "type": "eth_transaction"}', 393 | MessageType.Signal 394 | ).success 395 | ).toBe(true); 396 | }); 397 | 398 | test('should return true for a push notification signal message', () => { 399 | expect( 400 | validator.validateMessage( 401 | '{"token": "DeviceToken","provider":"apns","action":"add"}', 402 | MessageType.Signal 403 | ).success 404 | ).toBe(true); 405 | }); 406 | 407 | test('should allow a string signal message', () => { 408 | expect( 409 | validator.validateMessage('not a json string', MessageType.Signal).success 410 | ).toBe(true); 411 | }); 412 | 413 | test('should NOT allow a string rich message', () => { 414 | expect( 415 | validator.validateMessage('not a json string', MessageType.Rich).success 416 | ).toBe(false); 417 | }); 418 | }); 419 | 420 | describe('isDelegateName', () => { 421 | test('should return false for a number', () => { 422 | expect(validator.isDelegateName(1)).toBe(false); 423 | }); 424 | 425 | test('should return true for valid name', () => { 426 | expect(validator.isDelegateName('validname')).toBe(true); 427 | }); 428 | 429 | test('should return true for name with numbers', () => { 430 | expect(validator.isDelegateName('name_with1_number')).toBe(true); 431 | }); 432 | 433 | test('should return true for name with special characters', () => { 434 | expect(validator.isDelegateName('allow&special!chars')).toBe(true); 435 | }); 436 | 437 | test('should return true for short name (minimum length)', () => { 438 | expect(validator.isDelegateName('short')).toBe(true); 439 | }); 440 | 441 | test('should return true for name with underscores', () => { 442 | expect(validator.isDelegateName('this_is_a_valid_name')).toBe(true); 443 | }); 444 | 445 | test('should return false for an empty string', () => { 446 | expect(validator.isDelegateName('')).toBe(false); 447 | }); 448 | 449 | test('should return false for camel case with spaces', () => { 450 | expect(validator.isDelegateName('CamelCase')).toBe(false); 451 | }); 452 | 453 | test('should return false for long name (exceeds maximum length)', () => { 454 | expect(validator.isDelegateName('name-that-is-way-too-long')).toBe(false); 455 | }); 456 | 457 | test('should return false for name with invalid characters', () => { 458 | expect(validator.isDelegateName('!invalid$%characters&')).toBe(false); 459 | }); 460 | 461 | test('should return false for name with spaces', () => { 462 | expect(validator.isDelegateName('there is space')).toBe(false); 463 | }); 464 | }); 465 | -------------------------------------------------------------------------------- /src/helpers/time.ts: -------------------------------------------------------------------------------- 1 | export const EPOCH_TIME = new Date(Date.UTC(2017, 8, 2, 17, 0, 0, 0)); 2 | 3 | export const getEpochTime = (timestamp?: number) => { 4 | const startTimestamp = timestamp ?? Date.now(); 5 | const epochTimestamp = EPOCH_TIME.getTime(); 6 | 7 | return Math.floor((startTimestamp - epochTimestamp) / 1000); 8 | }; 9 | 10 | export const unixTimestamp = () => new Date().getTime(); 11 | -------------------------------------------------------------------------------- /src/helpers/transactions/hash.ts: -------------------------------------------------------------------------------- 1 | import sodium from 'sodium-browserify-tweetnacl'; 2 | import ByteBuffer from 'bytebuffer'; 3 | import crypto from 'crypto'; 4 | 5 | import BigNumber from 'bignumber.js'; 6 | import {toBuffer} from '../bignumber'; 7 | 8 | import {MessageType, TransactionType} from '../constants'; 9 | import {KeyPair} from '../keys'; 10 | 11 | export interface BasicTransaction { 12 | timestamp: number; 13 | amount: number; 14 | senderPublicKey: string; 15 | senderId: string; 16 | asset: {}; 17 | } 18 | 19 | export interface SendTransaction extends BasicTransaction { 20 | type: 0; 21 | recipientId: string; 22 | amount: number; 23 | asset: {}; 24 | } 25 | 26 | export interface StateTransaction extends BasicTransaction { 27 | type: 9; 28 | recipientId: null; 29 | asset: { 30 | state: { 31 | key: string; 32 | value: string; 33 | type: 0; 34 | }; 35 | }; 36 | } 37 | 38 | export interface ChatTransaction extends BasicTransaction { 39 | type: 8; 40 | recipientId: string; 41 | amount: number; 42 | asset: { 43 | chat: { 44 | message: string; 45 | own_message: string; 46 | type: MessageType; 47 | }; 48 | }; 49 | } 50 | 51 | export interface DelegateTransaction extends BasicTransaction { 52 | type: 2; 53 | recipientId: null; 54 | asset: { 55 | delegate: { 56 | username: string; 57 | publicKey: string; 58 | }; 59 | }; 60 | } 61 | 62 | export interface VoteTransaction extends BasicTransaction { 63 | type: 3; 64 | asset: { 65 | votes: string[]; 66 | }; 67 | } 68 | 69 | export type SomeTransaction = 70 | | VoteTransaction 71 | | DelegateTransaction 72 | | ChatTransaction 73 | | StateTransaction 74 | | SendTransaction; 75 | 76 | export type PossiblySignedTransaction = SomeTransaction & { 77 | signature?: string; 78 | }; 79 | 80 | export type SignedTransaction = SomeTransaction & { 81 | signature: string; 82 | }; 83 | 84 | export function getHash( 85 | trs: PossiblySignedTransaction, 86 | options = {skipSignature: true} 87 | ) { 88 | const hash = crypto 89 | .createHash('sha256') 90 | .update(getBytes(trs, options.skipSignature)) 91 | .digest(); 92 | 93 | return hash; 94 | } 95 | 96 | export function getAssetBytes(transaction: PossiblySignedTransaction) { 97 | const {type} = transaction; 98 | const {VOTE, DELEGATE, CHAT_MESSAGE, STATE} = TransactionType; 99 | 100 | let assetBytes = null; 101 | 102 | if (type === VOTE) { 103 | assetBytes = voteGetBytes(transaction); 104 | } else if (type === DELEGATE) { 105 | assetBytes = delegatesGetBytes(transaction); 106 | } else if (type === CHAT_MESSAGE) { 107 | assetBytes = chatGetBytes(transaction); 108 | } else if (type === STATE) { 109 | assetBytes = statesGetBytes(transaction); 110 | } 111 | 112 | return {assetBytes, assetSize: assetBytes?.length || 0}; 113 | } 114 | 115 | export function getBytes( 116 | transaction: PossiblySignedTransaction, 117 | skipSignature = true 118 | ) { 119 | const result = getAssetBytes(transaction); 120 | 121 | if (!result) { 122 | throw new Error('Not supported transaction type'); 123 | } 124 | 125 | const {assetSize, assetBytes} = result; 126 | 127 | const bb = new ByteBuffer(1 + 4 + 32 + 8 + 8 + 64 + 64 + assetSize, true); 128 | 129 | bb.writeByte(transaction.type); 130 | bb.writeInt(transaction.timestamp); 131 | 132 | const senderPublicKeyBuffer = Buffer.from(transaction.senderPublicKey, 'hex'); 133 | 134 | for (const buf of senderPublicKeyBuffer) { 135 | bb.writeByte(buf); 136 | } 137 | 138 | if ('recipientId' in transaction && transaction.recipientId) { 139 | const bignum = new BigNumber(transaction.recipientId.slice(1)); 140 | const recipient = toBuffer(bignum, {size: 8}); 141 | 142 | for (let i = 0; i < 8; i++) { 143 | bb.writeByte(recipient[i] || 0); 144 | } 145 | } else { 146 | for (let i = 0; i < 8; i++) { 147 | bb.writeByte(0); 148 | } 149 | } 150 | 151 | bb.writeLong(transaction.amount); 152 | 153 | if (assetBytes && assetSize > 0) { 154 | for (const assetByte of assetBytes) { 155 | bb.writeByte(assetByte); 156 | } 157 | } 158 | 159 | if (!skipSignature && transaction.signature) { 160 | const signatureBuffer = Buffer.from(transaction.signature, 'hex'); 161 | for (let i = 0; i < signatureBuffer.length; i++) { 162 | bb.writeByte(signatureBuffer[i]); 163 | } 164 | } 165 | 166 | bb.flip(); 167 | 168 | const arrayBuffer = new Uint8Array(bb.toArrayBuffer()); 169 | const buffer: number[] = []; 170 | 171 | for (let i = 0; i < arrayBuffer.length; i++) { 172 | buffer[i] = arrayBuffer[i]; 173 | } 174 | 175 | return Buffer.from(buffer); 176 | } 177 | 178 | export function signTransaction(trs: SomeTransaction, keypair: KeyPair) { 179 | const hash = getHash(trs); 180 | 181 | return sign(hash, keypair).toString('hex'); 182 | } 183 | 184 | export function voteGetBytes(trs: VoteTransaction) { 185 | const {votes} = trs.asset; 186 | 187 | return votes ? Buffer.from(votes.join(''), 'utf8') : null; 188 | } 189 | 190 | export function delegatesGetBytes(trs: DelegateTransaction) { 191 | const {username} = trs.asset.delegate; 192 | 193 | return username ? Buffer.from(username, 'utf8') : null; 194 | } 195 | 196 | export function statesGetBytes(trs: StateTransaction) { 197 | const {value} = trs.asset.state; 198 | 199 | if (!value) { 200 | return null; 201 | } 202 | 203 | let buf = Buffer.from([]); 204 | 205 | const {key, type} = trs.asset.state; 206 | 207 | const stateBuf = Buffer.from(value); 208 | 209 | buf = Buffer.concat([buf, stateBuf]); 210 | 211 | if (key) { 212 | const keyBuf = Buffer.from(key); 213 | buf = Buffer.concat([buf, keyBuf]); 214 | } 215 | 216 | const bb = new ByteBuffer(4 + 4, true); 217 | 218 | bb.writeInt(type); 219 | bb.flip(); 220 | 221 | buf = Buffer.concat([buf, bb.toBuffer()]); 222 | 223 | return buf; 224 | } 225 | 226 | export function chatGetBytes(trs: ChatTransaction) { 227 | let buf = Buffer.from([]); 228 | 229 | const {message} = trs.asset.chat; 230 | const messageBuf = Buffer.from(message, 'hex'); 231 | 232 | buf = Buffer.concat([buf, messageBuf]); 233 | 234 | const {own_message: ownMessage} = trs.asset.chat; 235 | 236 | if (ownMessage) { 237 | const ownMessageBuf = Buffer.from(ownMessage, 'hex'); 238 | buf = Buffer.concat([buf, ownMessageBuf]); 239 | } 240 | 241 | const bb = new ByteBuffer(4 + 4, true); 242 | 243 | bb.writeInt(trs.asset.chat.type); 244 | bb.flip(); 245 | 246 | buf = Buffer.concat([buf, Buffer.from(bb.toBuffer())]); 247 | 248 | return buf; 249 | } 250 | 251 | export function sign(hash: Buffer, keypair: KeyPair) { 252 | const sign = sodium.crypto_sign_detached( 253 | hash, 254 | Buffer.from(keypair.privateKey) 255 | ); 256 | 257 | return sign; 258 | } 259 | -------------------------------------------------------------------------------- /src/helpers/transactions/id.ts: -------------------------------------------------------------------------------- 1 | import {fromBuffer} from '../bignumber'; 2 | import {getHash, type SignedTransaction} from './hash'; 3 | 4 | export const getTransactionId = (transaction: SignedTransaction) => { 5 | if (!transaction.signature) { 6 | throw new Error('Transaction Signature is required'); 7 | } 8 | 9 | const hash = getHash(transaction, {skipSignature: false}); 10 | 11 | const temp = Buffer.alloc(8); 12 | for (let i = 0; i < 8; i++) { 13 | temp[i] = hash[7 - i]; 14 | } 15 | 16 | return fromBuffer(temp).toString(); 17 | }; 18 | -------------------------------------------------------------------------------- /src/helpers/transactions/index.ts: -------------------------------------------------------------------------------- 1 | import {signTransaction} from './hash'; 2 | 3 | import {createAddressFromPublicKey} from '../keys'; 4 | import {getEpochTime} from '../time'; 5 | 6 | import {MessageType, TransactionType} from '../constants'; 7 | import type {KeyPair} from '../keys'; 8 | import type {AdamantAddress} from '../../api'; 9 | 10 | export type AnyTransactionData = ( 11 | | SendTransactionData 12 | | ChatTransactionData 13 | | VoteTransactionData 14 | | DelegateTransactionData 15 | | StateTransactionData 16 | ) & { 17 | transactionType: TransactionType; 18 | }; 19 | 20 | export interface BasicTransactionData { 21 | keyPair: KeyPair; 22 | } 23 | 24 | export interface SendTransactionData extends BasicTransactionData { 25 | recipientId: string; 26 | amount: number; 27 | } 28 | 29 | export interface ChatTransactionData extends BasicTransactionData { 30 | recipientId: AdamantAddress; 31 | message_type: MessageType; 32 | amount?: number; 33 | message: string; 34 | own_message: string; 35 | } 36 | 37 | export interface VoteTransactionData extends BasicTransactionData { 38 | votes: string[]; 39 | } 40 | 41 | export interface DelegateTransactionData extends BasicTransactionData { 42 | username: string; 43 | } 44 | 45 | export interface StateTransactionData extends BasicTransactionData { 46 | key: string; 47 | value: string; 48 | } 49 | 50 | interface BasicTransaction { 51 | type: T; 52 | timestamp: number; 53 | amount: number; 54 | senderPublicKey: string; 55 | senderId: AdamantAddress; 56 | asset: {}; 57 | } 58 | 59 | export const createBasicTransaction = ( 60 | data: AnyTransactionData 61 | ): BasicTransaction => { 62 | const transaction = { 63 | type: data.transactionType as T, 64 | timestamp: getEpochTime(), 65 | amount: 0, 66 | senderPublicKey: data.keyPair.publicKey.toString('hex'), 67 | senderId: createAddressFromPublicKey(data.keyPair.publicKey), 68 | asset: {}, 69 | }; 70 | 71 | return transaction; 72 | }; 73 | 74 | export const createSendTransaction = (data: SendTransactionData) => { 75 | const details = { 76 | ...data, 77 | transactionType: TransactionType.SEND, 78 | }; 79 | 80 | const transaction = { 81 | ...createBasicTransaction(details), 82 | recipientId: details.recipientId, 83 | amount: details.amount, 84 | asset: {}, 85 | }; 86 | 87 | const signature = signTransaction(transaction, details.keyPair); 88 | 89 | return { 90 | ...transaction, 91 | signature, 92 | }; 93 | }; 94 | 95 | export const createStateTransaction = (data: StateTransactionData) => { 96 | const details = { 97 | ...data, 98 | transactionType: TransactionType.STATE, 99 | }; 100 | 101 | const transaction = { 102 | ...createBasicTransaction(details), 103 | recipientId: null, 104 | asset: { 105 | state: { 106 | key: details.key, 107 | value: details.value, 108 | type: 0 as const, 109 | }, 110 | }, 111 | }; 112 | 113 | const signature = signTransaction(transaction, details.keyPair); 114 | 115 | return { 116 | ...transaction, 117 | signature, 118 | }; 119 | }; 120 | 121 | export const createChatTransaction = (data: ChatTransactionData) => { 122 | const details = { 123 | ...data, 124 | transactionType: TransactionType.CHAT_MESSAGE, 125 | }; 126 | 127 | const transaction = { 128 | ...createBasicTransaction(details), 129 | recipientId: details.recipientId, 130 | amount: details.amount || 0, 131 | asset: { 132 | chat: { 133 | message: data.message, 134 | own_message: data.own_message, 135 | type: data.message_type, 136 | }, 137 | }, 138 | }; 139 | 140 | const signature = signTransaction(transaction, details.keyPair); 141 | 142 | return { 143 | ...transaction, 144 | signature, 145 | }; 146 | }; 147 | 148 | export const createDelegateTransaction = (data: DelegateTransactionData) => { 149 | const details = { 150 | ...data, 151 | transactionType: TransactionType.DELEGATE, 152 | }; 153 | 154 | const transaction = { 155 | ...createBasicTransaction(details), 156 | recipientId: null, 157 | asset: { 158 | delegate: { 159 | username: details.username, 160 | publicKey: details.keyPair.publicKey.toString('hex'), 161 | }, 162 | }, 163 | }; 164 | 165 | const signature = signTransaction(transaction, details.keyPair); 166 | 167 | return { 168 | ...transaction, 169 | signature, 170 | }; 171 | }; 172 | 173 | export const createVoteTransaction = (data: VoteTransactionData) => { 174 | const details = { 175 | ...data, 176 | transactionType: TransactionType.VOTE, 177 | }; 178 | 179 | const basicTransaction = 180 | createBasicTransaction(details); 181 | 182 | const transaction = { 183 | ...basicTransaction, 184 | recipientId: basicTransaction.senderId, 185 | asset: { 186 | votes: details.votes, 187 | }, 188 | }; 189 | 190 | const signature = signTransaction(transaction, details.keyPair); 191 | 192 | return { 193 | ...transaction, 194 | signature, 195 | }; 196 | }; 197 | 198 | export * from './hash'; 199 | export * from './id'; 200 | -------------------------------------------------------------------------------- /src/helpers/transactions/tests/id.test.ts: -------------------------------------------------------------------------------- 1 | import {getTransactionId} from '../id'; 2 | 3 | describe('getTransactionId', () => { 4 | it('should return the same id as a node for message transaction', () => { 5 | const id = getTransactionId({ 6 | type: 8, 7 | amount: 0, 8 | timestamp: 194049840, 9 | asset: { 10 | chat: { 11 | message: '7189aba904138dd1d53948ed1e5b1d18a11ba1910834', 12 | own_message: '8b717d0a9142e697cafd342c8f79f042c47a9e712e8a61b6', 13 | type: 1, 14 | }, 15 | }, 16 | recipientId: 'U12605277787100066317', 17 | senderId: 'U8084717991279447871', 18 | senderPublicKey: 19 | '09c93f2667728c62d2279bbb8df34c3856088290167f557c33594dc212da054a', 20 | signature: 21 | '304a4cb7e11651d576e2c4dffb4100bef5385981807f18c3267c863daf60bd277706e6790157beacf5100c77b6798c4725f2f4e070ca78496ff53a4c2e437f02', 22 | }); 23 | 24 | // https://ahead.adamant.im/api/transactions/get?id=5505818610983968576&returnAsset=1 25 | expect(id).toBe('5505818610983968576'); 26 | }); 27 | 28 | it('should return the same id as a node for transfer transaction', () => { 29 | const id = getTransactionId({ 30 | type: 8, 31 | amount: 0, 32 | senderId: 'U3716604363012166999', 33 | senderPublicKey: 34 | '1ed651ec1c686c23249dadb2cb656edd5f8e7d35076815d8a81c395c3eed1a85', 35 | asset: { 36 | chat: { 37 | message: 38 | 'beeac1b98d27cb2052edaf37e2843838b25fa8eb6cccaa076a2b66db179207ff76a2233822218143fddbcb5d034da27d1a7b088bab2012b16ac9574995dadeaf2783afcaa6b960cdcd680761895b16f004736aea55f1fb46417fd2816da35c00960c2d40e9e5e96ab52d97c5d97fe72d2fca2a6ef5225dd46ad380edfa27de6bd8b0f3f3a6c8166da3bff716db4e42699d116668403da7eb742f640ffc69a7122111e1e0db9bf3f65ae6c3380d3436d7a6', 39 | own_message: '1111240165c825cf31164cc05fb6d40b58d72493d8798390', 40 | type: 2, 41 | }, 42 | }, 43 | recipientId: 'U8084717991279447871', 44 | timestamp: 194374197, 45 | signature: 46 | 'bf9912ab59fe93780433c18e27d3634d8e78112e53379bcac7fc52a46cf90071c147d9dee06497441928afdb6e59501dce679788b3322e97be93178d9f7c7c0d', 47 | }); 48 | 49 | // https://ahead.adamant.im/api/transactions/get?id=10707920525275969664&returnAsset=1 50 | expect(id).toBe('10707920525275969664'); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /src/helpers/url.ts: -------------------------------------------------------------------------------- 1 | import dns from 'dns/promises'; 2 | 3 | const RE_HTTP_URL = /^https?:\/\/(.*)$/; 4 | const RE_IP = 5 | /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/; 6 | 7 | export const parseUrl = async (url: string) => { 8 | const isHttps = url.startsWith('https'); 9 | 10 | // base url without port 11 | const [baseURL] = url.replace(RE_HTTP_URL, '$1').split(':'); 12 | 13 | const ip = RE_IP.test(baseURL) ? baseURL : await retrieveIP(baseURL); 14 | 15 | return { 16 | baseURL, 17 | ip, 18 | isHttps, 19 | }; 20 | }; 21 | 22 | export const retrieveIP = async (url: string) => { 23 | try { 24 | const addresses = await dns.resolve4(url); 25 | 26 | if (addresses) { 27 | const [address] = addresses; 28 | 29 | if (address !== '0.0.0.0') { 30 | return address; 31 | } 32 | } 33 | } catch (error) { 34 | return; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /src/helpers/utils.ts: -------------------------------------------------------------------------------- 1 | export const hasOwnProperty = ( 2 | obj: T, 3 | prop: K 4 | ): obj is T & Record => { 5 | return Object.prototype.hasOwnProperty.call(obj, prop); 6 | }; 7 | -------------------------------------------------------------------------------- /src/helpers/validator.ts: -------------------------------------------------------------------------------- 1 | import BigNumber from 'bignumber.js'; 2 | import {MessageType, MessageTypes, SAT} from './constants'; 3 | import type {AdamantAddress} from '../api'; 4 | 5 | export const getRandomIntInclusive = (minimum: number, maximum: number) => { 6 | const min = Math.ceil(minimum); 7 | const max = Math.floor(maximum); 8 | 9 | // The maximum is inclusive and the minimum is inclusive 10 | return Math.floor(Math.random() * (max - min + 1) + min); 11 | }; 12 | 13 | export const isNumeric = (str: unknown): str is string => 14 | typeof str === 'string' && !isNaN(parseFloat(str)); 15 | 16 | export const parseJsonSafe = (json: string) => { 17 | try { 18 | const result = JSON.parse(json) as unknown; 19 | 20 | return { 21 | result, 22 | success: true, 23 | }; 24 | } catch (error) { 25 | return { 26 | error, 27 | success: false, 28 | }; 29 | } 30 | }; 31 | 32 | export const isPassphrase = (passphrase: unknown): passphrase is string => 33 | typeof passphrase === 'string' && passphrase.length > 30; 34 | 35 | export const isEndpoint = (endpoint: unknown): endpoint is string => 36 | typeof endpoint === 'string' && endpoint.startsWith('/'); 37 | 38 | const RE_ADM_ADDRESS = /^U([0-9]{6,})$/; 39 | 40 | export const isAdmAddress = (address: unknown): address is AdamantAddress => 41 | typeof address === 'string' && RE_ADM_ADDRESS.test(address); 42 | 43 | const RE_HEX = /^[a-fA-F0-9]+$/; 44 | 45 | export const isAdmPublicKey = (publicKey: unknown): publicKey is string => 46 | typeof publicKey === 'string' && 47 | publicKey.length === 64 && 48 | RE_HEX.test(publicKey); 49 | 50 | const RE_ADM_VOTE_FOR_PUBLIC_KEY = /^(\+|-)[a-fA-F0-9]{64}$/; 51 | 52 | export const isAdmVoteForPublicKey = ( 53 | publicKey: unknown 54 | ): publicKey is string => 55 | typeof publicKey === 'string' && RE_ADM_VOTE_FOR_PUBLIC_KEY.test(publicKey); 56 | 57 | const RE_ADM_VOTE_FOR_ADDRESS = /^(\+|-)U([0-9]{6,})$/; 58 | 59 | export const isAdmVoteForAddress = (address: unknown) => 60 | typeof address === 'string' && RE_ADM_VOTE_FOR_ADDRESS.test(address); 61 | 62 | const RE_ADM_VOTE_FOR_DELEGATE_NAME = /^(\+|-)([a-z0-9!@$&_]{1,20})$/; 63 | 64 | export const isAdmVoteForDelegateName = ( 65 | delegateName: unknown 66 | ): delegateName is string => 67 | typeof delegateName === 'string' && 68 | RE_ADM_VOTE_FOR_DELEGATE_NAME.test(delegateName); 69 | 70 | export const isIntegerAmount = (amount: number) => Number.isSafeInteger(amount); 71 | 72 | export const isStringAmount = (amount: string) => isNumeric(amount); 73 | 74 | export const isMessageType = ( 75 | messageType: number 76 | ): messageType is MessageTypes => [1, 2, 3].includes(messageType); 77 | 78 | export const validateMessage = ( 79 | message: string, 80 | messageType: MessageType = MessageType.Chat 81 | ) => { 82 | if (typeof message !== 'string') { 83 | return { 84 | success: false, 85 | error: 'Message should be a string', 86 | }; 87 | } 88 | 89 | if ([MessageType.Rich].includes(messageType)) { 90 | const data = parseJsonSafe(message); 91 | 92 | const {success, result} = data; 93 | if (!success || typeof result !== 'object' || result === null) { 94 | return { 95 | success: false, 96 | error: "For rich and signal message, 'message' should be a JSON string", 97 | }; 98 | } 99 | 100 | if ('type' in result && typeof result.type === 'string') { 101 | const typeInLowerCase = result.type.toLowerCase(); 102 | if (typeInLowerCase.endsWith('_transaction')) { 103 | if (typeInLowerCase !== result.type) { 104 | return { 105 | success: false, 106 | error: "Value '_transaction' must be in lower case", 107 | }; 108 | } 109 | 110 | if ( 111 | 'amount' in result && 112 | (typeof result.amount !== 'string' || !isStringAmount(result.amount)) 113 | ) { 114 | return { 115 | success: false, 116 | error: "Field 'amount' must be a string, representing a number", 117 | }; 118 | } 119 | } 120 | } 121 | } 122 | 123 | return {success: true}; 124 | }; 125 | 126 | const RE_ADM_DELEGATE_NAME = /^[a-z0-9!@$&_]{1,20}$/; 127 | 128 | export const isDelegateName = (name: unknown): name is string => 129 | typeof name === 'string' && RE_ADM_DELEGATE_NAME.test(name); 130 | 131 | export const admToSats = (amount: number) => 132 | new BigNumber(String(amount)).multipliedBy(SAT).integerValue().toNumber(); 133 | 134 | export const badParameter = ( 135 | name: string, 136 | value?: unknown, 137 | message?: string 138 | ) => ({ 139 | success: false, 140 | error: `Wrong '${name}' parameter${value ? `: ${value}` : ''}${ 141 | message ? `. Error: ${message}` : '' 142 | }`, 143 | }); 144 | 145 | export type AdamantApiResult = 146 | | (Omit & {success: true}) 147 | | { 148 | success: false; 149 | errorMessage: string; 150 | }; 151 | -------------------------------------------------------------------------------- /src/helpers/wsClient.ts: -------------------------------------------------------------------------------- 1 | import {io, type Socket} from 'socket.io-client'; 2 | 3 | import type {ActiveNode} from './healthCheck'; 4 | import {Logger} from './logger'; 5 | import {getRandomIntInclusive} from './validator'; 6 | import {TransactionType} from './constants'; 7 | import type { 8 | AnyTransaction, 9 | ChatMessageTransaction, 10 | KVSTransaction, 11 | RegisterDelegateTransaction, 12 | TokenTransferTransaction, 13 | VoteForDelegateTransaction, 14 | } from '../api/generated'; 15 | import type {AdamantAddress} from '../api'; 16 | 17 | export type WsType = 'ws' | 'wss'; 18 | 19 | export interface WsOptions { 20 | /** 21 | * ADM address to subscribe to notifications 22 | */ 23 | admAddress: AdamantAddress; 24 | 25 | /** 26 | * Websocket type: `'wss'` or `'ws'`. `'wss'` is recommended. 27 | */ 28 | wsType?: WsType; 29 | 30 | /** 31 | * Must connect to node with minimum ping. Not recommended. Default is `false`. 32 | */ 33 | useFastest?: boolean; 34 | 35 | logger?: Logger; 36 | } 37 | 38 | type ErrorHandler = (error: unknown) => void; 39 | 40 | type TransactionMap = { 41 | [TransactionType.SEND]: TokenTransferTransaction; 42 | [TransactionType.DELEGATE]: RegisterDelegateTransaction; 43 | [TransactionType.VOTE]: VoteForDelegateTransaction; 44 | [TransactionType.CHAT_MESSAGE]: ChatMessageTransaction; 45 | [TransactionType.STATE]: KVSTransaction; 46 | }; 47 | 48 | type EventType = keyof TransactionMap; 49 | 50 | export type TransactionHandler = ( 51 | transaction: T 52 | ) => void; 53 | 54 | export type SingleTransactionHandler = 55 | | TransactionHandler 56 | | TransactionHandler 57 | | TransactionHandler 58 | | TransactionHandler 59 | | TransactionHandler; 60 | 61 | export type AnyTransactionHandler = TransactionHandler; 62 | 63 | export class WebSocketClient { 64 | /** 65 | * Web socket client options. 66 | */ 67 | public options: WsOptions; 68 | 69 | /** 70 | * Current socket connection 71 | */ 72 | private connection?: Socket; 73 | 74 | /** 75 | * List of nodes that are active, synced and support socket. 76 | */ 77 | private nodes: ActiveNode[]; 78 | 79 | private logger: Logger; 80 | 81 | private errorHandler: ErrorHandler; 82 | private eventHandlers: { 83 | [T in EventType]: TransactionHandler[]; 84 | } = { 85 | [TransactionType.SEND]: [], 86 | [TransactionType.DELEGATE]: [], 87 | [TransactionType.VOTE]: [], 88 | [TransactionType.CHAT_MESSAGE]: [], 89 | [TransactionType.STATE]: [], 90 | }; 91 | 92 | constructor(options: WsOptions) { 93 | this.logger = options.logger || new Logger(); 94 | this.options = { 95 | wsType: 'ws', 96 | ...options, 97 | }; 98 | 99 | this.nodes = []; 100 | 101 | this.errorHandler = (error: unknown) => { 102 | this.logger.error(`${error}`); 103 | }; 104 | } 105 | 106 | /** 107 | * Filters nodes that support websocket and connects to one of them. 108 | * 109 | * @param nodes Sorted by ping array of active nodes 110 | */ 111 | reviseConnection(nodes: ActiveNode[]) { 112 | if (this.connection?.connected) { 113 | return; 114 | } 115 | 116 | const {wsType} = this.options; 117 | 118 | this.nodes = nodes.filter( 119 | node => 120 | node.socketSupport && 121 | !node.outOfSync && 122 | // Remove nodes without IP if 'ws' connection type 123 | (wsType !== 'ws' || !node.isHttps || node.ip) 124 | ); 125 | 126 | this.setConnection(); 127 | } 128 | 129 | /** 130 | * Chooses node and sets up connection. 131 | */ 132 | setConnection() { 133 | const {logger} = this; 134 | 135 | const supportedCount = this.nodes.length; 136 | if (!supportedCount) { 137 | logger.warn('[Socket] No supported socket nodes at the moment.'); 138 | return; 139 | } 140 | 141 | const node = this.chooseNode(); 142 | logger.log( 143 | `[Socket] Supported nodes: ${supportedCount}. Connecting to ${node}...` 144 | ); 145 | const connection = io(node, { 146 | reconnection: false, 147 | timeout: 5000, 148 | }); 149 | 150 | connection.on('connect', () => { 151 | const {admAddress} = this.options; 152 | 153 | connection.emit('address', admAddress); 154 | logger.info( 155 | `[Socket] Connected to ${node} and subscribed to incoming transactions for ${admAddress}` 156 | ); 157 | }); 158 | 159 | connection.on('disconnect', reason => 160 | logger.warn(`[Socket] Disconnected. Reason: ${reason}`) 161 | ); 162 | 163 | connection.on('connect_error', error => 164 | logger.warn(`[Socket] Connection error: ${error}`) 165 | ); 166 | 167 | connection.on('newTrans', (transaction: AnyTransaction) => { 168 | if (transaction.recipientId !== this.options.admAddress) { 169 | return; 170 | } 171 | 172 | this.handle(transaction); 173 | }); 174 | 175 | this.connection = connection; 176 | } 177 | 178 | /** 179 | * Sets an error handler for all event handlers. 180 | * 181 | * @example 182 | * ```js 183 | * socket.onMessage(() => throw new Error('catch me')) 184 | * 185 | * socket.catch((error) => { 186 | * console.log(error) // Error: catch me 187 | * }) 188 | * ``` 189 | */ 190 | public catch(callback: ErrorHandler) { 191 | this.errorHandler = callback; 192 | return this; 193 | } 194 | 195 | /** 196 | * Removes the handler from all types. 197 | */ 198 | public off(handler: SingleTransactionHandler) { 199 | for (const handlers of Object.values(this.eventHandlers)) { 200 | const index = (handlers as SingleTransactionHandler[]).indexOf(handler); 201 | if (index !== -1) { 202 | handlers.splice(index, 1); 203 | } 204 | } 205 | 206 | return this; 207 | } 208 | 209 | /** 210 | * Adds an event listener handler for all transaction types. 211 | */ 212 | public on(handler: AnyTransactionHandler): this; 213 | /** 214 | * Adds an event listener handler for the specific transaction types. 215 | */ 216 | public on( 217 | types: T | T[], 218 | handler: TransactionHandler 219 | ): this; 220 | public on( 221 | typesOrHandler: T | T[] | AnyTransactionHandler, 222 | handler?: TransactionHandler 223 | ) { 224 | if (handler === undefined) { 225 | if (typeof typesOrHandler === 'function') { 226 | for (const trigger of Object.keys(this.eventHandlers)) { 227 | this.eventHandlers[+trigger as EventType].push(typesOrHandler); 228 | } 229 | } 230 | } else { 231 | const triggers = Array.isArray(typesOrHandler) 232 | ? typesOrHandler 233 | : [typesOrHandler]; 234 | 235 | for (const trigger of triggers) { 236 | this.eventHandlers[trigger as T].push(handler); 237 | } 238 | } 239 | 240 | return this; 241 | } 242 | 243 | /** 244 | * Registers an event handler for Chatn Message transactions. 245 | */ 246 | public onMessage(handler: TransactionHandler) { 247 | return this.on(TransactionType.CHAT_MESSAGE, handler); 248 | } 249 | 250 | /** 251 | * Registers an event handler for Token Transfer transactions. 252 | */ 253 | public onTransfer(handler: TransactionHandler) { 254 | return this.on(TransactionType.SEND, handler); 255 | } 256 | 257 | /** 258 | * Registers an event handler for Register Delegate transactions. 259 | */ 260 | public onNewDelegate( 261 | handler: TransactionHandler 262 | ) { 263 | return this.on(TransactionType.DELEGATE, handler); 264 | } 265 | 266 | /** 267 | * Registers an event handler for Vote for Delegate transactions. 268 | */ 269 | public onVoteForDelegate( 270 | handler: TransactionHandler 271 | ) { 272 | return this.on(TransactionType.VOTE, handler); 273 | } 274 | 275 | /** 276 | * Registers an event handler for Key-Value Store (KVS) transactions. 277 | */ 278 | public onKVS(handler: TransactionHandler) { 279 | return this.on(TransactionType.STATE, handler); 280 | } 281 | 282 | private async handle(transaction: AnyTransaction) { 283 | const handlers = this.eventHandlers[transaction.type as T]; 284 | 285 | for (const handler of handlers) { 286 | try { 287 | await handler(transaction as TransactionMap[T]); 288 | } catch (error) { 289 | this.errorHandler(error); 290 | } 291 | } 292 | } 293 | 294 | /** 295 | * Chooses fastest or random node based on {@link WsOptions.useFastest} option 296 | * 297 | * @returns WebSocket url 298 | */ 299 | chooseNode(): string { 300 | const {wsType, useFastest} = this.options; 301 | 302 | const node = useFastest ? this.fastestNode() : this.randomNode(); 303 | 304 | let baseURL: string; 305 | 306 | if (wsType === 'ws') { 307 | const host = node.ip ? node.ip : node.baseURL; 308 | 309 | baseURL = `${host}:${node.wsPort}`; 310 | } else { 311 | baseURL = node.baseURL; // no port if wss 312 | } 313 | 314 | return `${wsType}://${baseURL}`; 315 | } 316 | 317 | fastestNode() { 318 | return this.nodes[0]; // They are already sorted by ping 319 | } 320 | 321 | randomNode() { 322 | const randomIndex = getRandomIntInclusive(0, this.nodes.length - 1); 323 | return this.nodes[randomIndex]; 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './api/index'; 2 | export * from './coins/index'; 3 | export * from './helpers/transactions/index'; 4 | export * from './helpers/encryptor'; 5 | export * from './helpers/constants'; 6 | export * from './helpers/logger'; 7 | export * from './helpers/wsClient'; 8 | export * from './helpers/keys'; 9 | export { 10 | isPassphrase, 11 | isAdmAddress, 12 | isAdmPublicKey, 13 | isAdmVoteForPublicKey, 14 | isAdmVoteForAddress, 15 | isAdmVoteForDelegateName, 16 | validateMessage, 17 | isDelegateName, 18 | admToSats, 19 | } from './helpers/validator'; 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "lib": [], 5 | "target": "ESNext", 6 | "module": "CommonJS", 7 | "outDir": "./dist", 8 | "rootDir": "./src", 9 | "declaration": true, 10 | "esModuleInterop": true 11 | }, 12 | "include": ["src/index.ts", "types/*.d.ts"], 13 | "exclude": ["node_modules"] 14 | } 15 | -------------------------------------------------------------------------------- /types/coininfo.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'coininfo' { 2 | export interface Network { 3 | messagePrefix: string; 4 | bech32: string; 5 | bip32: Bip32; 6 | pubKeyHash: number; 7 | scriptHash: number; 8 | wif: number; 9 | } 10 | 11 | export interface Bip32 { 12 | public: number; 13 | private: number; 14 | } 15 | 16 | export interface CoinInfo { 17 | main: { 18 | toBitcoinJS: () => Network; 19 | }; 20 | } 21 | 22 | export interface Coins { 23 | bitcoin: CoinInfo; 24 | dash: CoinInfo; 25 | dogecoin: CoinInfo; 26 | } 27 | 28 | const coininfo: Coins; 29 | export default coininfo; 30 | } 31 | -------------------------------------------------------------------------------- /types/socket-io-client.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is temporary workaround. 3 | * 4 | * `@types/node` doesn't expose `TransformStream` in global scope as it should 5 | * which breaks `engine.io-parser` package that is dependency of `socket.io-client` 6 | * 7 | * @see https://github.com/socketio/engine.io-parser/issues/136 8 | */ 9 | import {TransformStream as TS} from 'node:stream/web'; 10 | 11 | declare global { 12 | type TransformStream = TS; 13 | } 14 | -------------------------------------------------------------------------------- /types/sodium-browserify-tweetnacl.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'sodium-browserify-tweetnacl' { 2 | namespace sodium { 3 | export function crypto_sign_seed_keypair(seed: Buffer): { 4 | publicKey: Buffer; 5 | secretKey: Buffer; 6 | }; 7 | 8 | export function crypto_sign_detached( 9 | hash: Buffer, 10 | privateKey: Buffer 11 | ): Buffer; 12 | 13 | export function randombytes(nonce: Buffer): void; 14 | } 15 | 16 | export = sodium; 17 | } 18 | --------------------------------------------------------------------------------