-
-
Notifications
You must be signed in to change notification settings - Fork 12
Feature/add delegate methods #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
6d40ec0
Add delegateNew()
martiliones 4a8f497
Add voteForDelegate()
martiliones 6e05144
Refactoring
martiliones 0f72806
Pump version
martiliones eb9f466
Rename the constants
martiliones acadab3
Test delegate names for length and lowercase
martiliones 6b7bf7d
Allow votes[] to include publicKeys and ADM addresses and delegate na…
martiliones 13a20a2
Remove console.log()
martiliones 5bd5631
Update dependencies
martiliones 97d925d
Update voteForDelegate() description
martiliones c6430de
Refactoring
martiliones 26f48c8
Fix bug: Cached addresses were not checked for duplicates
martiliones File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| const axios = require('axios'); | ||
| const logger = require('../helpers/logger'); | ||
| const keys = require('../helpers/keys'); | ||
| const constants = require('../helpers/constants'); | ||
| const transactionFormer = require('../helpers/transactionFormer'); | ||
| const validator = require('../helpers/validator'); | ||
|
|
||
| const DEFAULT_NEW_DELEGATE_RETRIES = 4; // How much re-tries for send tokens requests by default. Total 4+1 tries | ||
|
|
||
| module.exports = (nodeManager) => { | ||
| /** | ||
| * Registers user account as delegate | ||
| * @param {string} passPhrase Senders's passPhrase. Sender's address will be derived from it. | ||
| * @param {string} username Delegate name you want to register with. | ||
| * It must be unique in ADAMANT blockchain. It should not be similar to ADAMANT address. | ||
| * Delegate name can only contain alphanumeric characters and symbols !@$&_. | ||
| * @param {number} maxRetries How much times to retry request | ||
| * @returns {Promise} Request results | ||
| */ | ||
| return async (passPhrase, username, maxRetries = DEFAULT_NEW_DELEGATE_RETRIES, retryNo = 0) => { | ||
|
|
||
| let transaction; | ||
|
|
||
| try { | ||
| if (!validator.validatePassPhrase(passPhrase)) { | ||
| return validator.badParameter('passPhrase'); | ||
| } | ||
|
|
||
| const keyPair = keys.createKeypairFromPassPhrase(passPhrase); | ||
|
|
||
| if (!validator.validateDelegateName(username)) { | ||
| return validator.badParameter('username'); | ||
| } | ||
|
|
||
| const type = constants.transactionTypes.DELEGATE; | ||
|
|
||
| const data = { | ||
| type, | ||
| keyPair, | ||
| username, | ||
| }; | ||
|
|
||
| transaction = transactionFormer.createTransaction(type, data); | ||
|
|
||
| } catch (e) { | ||
| return validator.badParameter('#exception_catched#', e); | ||
| } | ||
|
|
||
| const url = nodeManager.node() + '/api/delegates'; | ||
|
|
||
| try { | ||
| const response = await axios.post(url, transaction); | ||
|
|
||
| return validator.formatRequestResults(response, true); | ||
| } catch (error) { | ||
| const logMessage = `[ADAMANT js-api] New delegate request: Request to ${url} failed with ${error.response ? error.response.status : undefined} status code, ${error.toString()}${error.response && error.response.data ? '. Message: ' + error.response.data.toString().trim() : ''}. Try ${retryNo+1} of ${maxRetries+1}.`; | ||
|
|
||
| if (retryNo < maxRetries) { | ||
| logger.log(`${logMessage} Retrying…`); | ||
|
|
||
| return nodeManager.changeNodes() | ||
| .then(() => ( | ||
| module.exports(nodeManager)(passPhrase, addressOrPublicKey, amount, isAmountInADM, maxRetries, ++retryNo) | ||
| )); | ||
| } | ||
|
|
||
| logger.warn(`${logMessage} No more attempts, returning error.`); | ||
|
|
||
| return validator.formatRequestResults(error, false); | ||
| } | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| const axios = require('axios'); | ||
| const get = require('./get'); | ||
| const logger = require('../helpers/logger'); | ||
| const keys = require('../helpers/keys'); | ||
| const constants = require('../helpers/constants'); | ||
| const transactionFormer = require('../helpers/transactionFormer'); | ||
| const validator = require('../helpers/validator'); | ||
|
|
||
| const DEFAULT_VOTE_FOR_DELEGATE_RETRIES = 4; // How much re-tries for send tokens requests by default. Total 4+1 tries | ||
|
|
||
| const publicKeysCache = { }; | ||
|
|
||
| module.exports = (nodeManager) => { | ||
| /** | ||
| * Creates votes for delegate transaction, signs it, and broadcasts to ADAMANT network | ||
| * See https://github.com/Adamant-im/adamant/wiki/Transaction-Types#type-3-vote-for-delegate-transaction | ||
| * @param {string} passPhrase Senders's passPhrase. Sender's address will be derived from it. | ||
| * @param {string[]} votes PublicKeys, ADM addresses and delegate names for upvote and downvote. | ||
| * It would be more efficient to pass publicKey, otherwise the api will make additional queries | ||
| * @param {number} maxRetries How much times to retry request | ||
| * @returns {Promise} Request results | ||
| */ | ||
| return async (passPhrase, votes, maxRetries = DEFAULT_VOTE_FOR_DELEGATE_RETRIES, retryNo = 0) => { | ||
|
|
||
| let transaction; | ||
|
|
||
| try { | ||
| if (!validator.validatePassPhrase(passPhrase)) { | ||
| return validator.badParameter('passPhrase'); | ||
| } | ||
|
|
||
| const keyPair = keys.createKeypairFromPassPhrase(passPhrase); | ||
|
|
||
| const uniqueVotes = []; | ||
|
|
||
| for (let i = votes.length - 1; i >= 0; i--) { | ||
| const vote = votes[i]; | ||
| const voteName = vote.slice(1); | ||
| const voteDirection = vote.charAt(0); | ||
|
|
||
| const cachedPublicKey = publicKeysCache[voteName]; | ||
|
|
||
| if (cachedPublicKey) { | ||
| votes[i] = `${voteDirection}${cachedPublicKey}`; | ||
| } else { | ||
| if (validator.validateAdmVoteForAddress(vote)) { | ||
| const res = await get(nodeManager)('/accounts', { address: voteName }); | ||
|
|
||
| if (res.success) { | ||
| const publicKey = res.data.account.publicKey; | ||
|
|
||
| votes[i] = `${voteDirection}${publicKey}`; | ||
| publicKeysCache[voteName] = publicKey; | ||
| } else { | ||
| logger.warn(`[ADAMANT js-api] Failed to get public key for ${vote}. ${res.errorMessage}.`); | ||
|
|
||
| return validator.badParameter('votes'); | ||
| } | ||
| } else if (validator.validateAdmVoteForDelegateName(vote)) { | ||
| const res = await get(nodeManager)('/delegates/get', { username: voteName }); | ||
|
|
||
| if (res.success) { | ||
| const publicKey = res.data.delegate.publicKey; | ||
|
|
||
| votes[i] = `${voteDirection}${publicKey}`; | ||
| publicKeysCache[voteName] = publicKey; | ||
| } else { | ||
| logger.warn(`[ADAMANT js-api] Failed to get public key for ${vote}. ${res.errorMessage}.`); | ||
|
|
||
| return validator.badParameter('votes'); | ||
| } | ||
| } else if (!validator.validateAdmVoteForPublicKey(vote)) { | ||
| return validator.badParameter('votes'); | ||
| } | ||
| } | ||
|
|
||
| // Exclude duplicates | ||
| const foundCopy = uniqueVotes.find((v) => v.slice(1) === votes[i].slice(1)); | ||
|
|
||
| if (!foundCopy) { | ||
| uniqueVotes.push(votes[i]); | ||
| } | ||
| } | ||
|
|
||
| const type = constants.transactionTypes.VOTE; | ||
|
|
||
| const data = { | ||
| type, | ||
| keyPair, | ||
| votes: uniqueVotes, | ||
| }; | ||
|
|
||
| transaction = transactionFormer.createTransaction(type, data); | ||
| } catch (error) { | ||
| return validator.badParameter('#exception_catched#', error) | ||
| } | ||
|
|
||
| const url = nodeManager.node() + '/api/accounts/delegates'; | ||
|
|
||
| try { | ||
| const response = await axios.post(url, transaction); | ||
|
|
||
| return validator.formatRequestResults(response, true); | ||
| } catch(error) { | ||
| const logMessage = `[ADAMANT js-api] Vote for delegate request: Request to ${url} failed with ${error.response ? error.response.status : undefined} status code, ${error.toString()}${error.response && error.response.data ? '. Message: ' + error.response.data.toString().trim() : ''}. Try ${retryNo+1} of ${maxRetries+1}.`; | ||
|
|
||
| if (retryNo < maxRetries) { | ||
| logger.log(`${logMessage} Retrying…`); | ||
|
|
||
| return nodeManager.changeNodes() | ||
| .then(() => ( | ||
| module.exports(nodeManager)(passPhrase, addressOrPublicKey, amount, isAmountInADM, maxRetries, ++retryNo) | ||
| )); | ||
| } | ||
|
|
||
| logger.warn(`${logMessage} No more attempts, returning error.`); | ||
|
|
||
| return validator.formatRequestResults(error, false); | ||
| } | ||
| } | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.