Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
martiliones committed Feb 12, 2022
1 parent 97d925d commit c6430de
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 65 deletions.
52 changes: 28 additions & 24 deletions groups/newDelegate.js
Expand Up @@ -17,18 +17,20 @@ module.exports = (nodeManager) => {
* @param {number} maxRetries How much times to retry request
* @returns {Promise} Request results
*/
return (passPhrase, username, maxRetries = DEFAULT_NEW_DELEGATE_RETRIES, retryNo = 0) => {
return async (passPhrase, username, maxRetries = DEFAULT_NEW_DELEGATE_RETRIES, retryNo = 0) => {

let transaction;

try {
if (!validator.validatePassPhrase(passPhrase))
return validator.badParameter('passPhrase')
if (!validator.validatePassPhrase(passPhrase)) {
return validator.badParameter('passPhrase');
}

const keyPair = keys.createKeypairFromPassPhrase(passPhrase);

if (!validator.validateDelegateName(username))
return validator.badParameter('username')
if (!validator.validateDelegateName(username)) {
return validator.badParameter('username');
}

const type = constants.transactionTypes.DELEGATE;

Expand All @@ -41,28 +43,30 @@ module.exports = (nodeManager) => {
transaction = transactionFormer.createTransaction(type, data);

} catch (e) {
return validator.badParameter('#exception_catched#', 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}.`;

let url = nodeManager.node() + '/api/delegates';
return axios.post(url, transaction)
.then(function (response) {
return validator.formatRequestResults(response, true)
})
.catch(function (error) {
let 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(function () {
return module.exports(nodeManager)(passPhrase, addressOrPublicKey, amount, isAmountInADM, maxRetries, ++retryNo)
})
}
logger.warn(`${logMessage} No more attempts, returning error.`);
return validator.formatRequestResults(error, false)
})
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);
}
}
};
64 changes: 35 additions & 29 deletions groups/voteForDelegate.js
Expand Up @@ -25,22 +25,23 @@ module.exports = (nodeManager) => {
let transaction;

try {
if (!validator.validatePassPhrase(passPhrase))
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];
votes.forEach((vote, i) => {
const voteName = vote.slice(1);
const voteDirection = vote.charAt(0);

const cachedPublicKey = publicKeysCache[voteName];

if (cachedPublicKey) {
votes[i] = `${voteDirection}${cachedPublicKey}`;

continue;
}

Expand All @@ -49,34 +50,38 @@ module.exports = (nodeManager) => {

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')

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')

return validator.badParameter('votes');
}
} else if (!validator.validateAdmVoteForPublicKey(vote)) {
return validator.badParameter('votes')
return validator.badParameter('votes');
}

// Exclude duplicates
const foundCopy = uniqueVotes.findIndex((v) => v.slice(1) === votes[i].slice(1));
const foundCopy = uniqueVotes.find((v) => v.slice(1) === votes[i].slice(1));

if (foundCopy === -1) {
if (!foundCopy) {
uniqueVotes.push(votes[i]);
}
}
});

const type = constants.transactionTypes.VOTE;

Expand All @@ -87,30 +92,31 @@ module.exports = (nodeManager) => {
};

transaction = transactionFormer.createTransaction(type, data);
} catch (error) {
return validator.badParameter('#exception_catched#', error)
}

} catch (e) {
const url = nodeManager.node() + '/api/accounts/delegates';

return validator.badParameter('#exception_catched#', e)
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}.`;

let url = nodeManager.node() + '/api/accounts/delegates';
return axios.post(url, transaction)
.then(function (response) {
return validator.formatRequestResults(response, true)
})
.catch(function (error) {
let 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(function () {
return module.exports(nodeManager)(passPhrase, addressOrPublicKey, amount, isAmountInADM, maxRetries, ++retryNo)
})
}
logger.warn(`${logMessage} No more attempts, returning error.`);
return validator.formatRequestResults(error, false)
})
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);
}
}
};
15 changes: 3 additions & 12 deletions helpers/validator.js
Expand Up @@ -53,24 +53,15 @@ module.exports = {
},

validateAdmVoteForPublicKey(publicKey) {
if (!publicKey || typeof(publicKey) !== 'string' || !constants.RE_ADM_VOTE_FOR_PUBLIC_KEY.test(publicKey))
return false
else
return true
return (publicKey && typeof(publicKey) === 'string' && constants.RE_ADM_VOTE_FOR_PUBLIC_KEY.test(publicKey));
},

validateAdmVoteForAddress(address) {
if (!address || typeof(address) !== 'string' || !constants.RE_ADM_VOTE_FOR_ADDRESS.test(address))
return false
else
return true
return (address && typeof(address) === 'string' && constants.RE_ADM_VOTE_FOR_ADDRESS.test(address));
},

validateAdmVoteForDelegateName(delegateName) {
if (!delegateName || typeof(delegateName) !== 'string' || !constants.RE_ADM_VOTE_FOR_DELEGATE_NAME.test(delegateName))
return false
else
return true
return (delegateName && typeof(delegateName) === 'string' && constants.RE_ADM_VOTE_FOR_DELEGATE_NAME.test(delegateName));
},

validateIntegerAmount(amount) {
Expand Down

0 comments on commit c6430de

Please sign in to comment.