Skip to content

Commit

Permalink
Add delegateNew()
Browse files Browse the repository at this point in the history
  • Loading branch information
martiliones committed Feb 9, 2022
1 parent 564cc83 commit 6d40ec0
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 5 deletions.
70 changes: 70 additions & 0 deletions groups/delegateNew.js
@@ -0,0 +1,70 @@
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_SEND_TOKENS_RETRIES = 4; // How much re-tries for send tokens requests by default. Total 4+1 tries

module.exports = (nodeManager) => {
/**
* Creates Token Transfer transaction, signs it, and broadcasts to ADAMANT network
* See https://github.com/Adamant-im/adamant/wiki/Transaction-Types#type-0-token-transfer-transaction
* @param {string} passPhrase Senders's passPhrase. Sender's address will be derived from it.
* @param {string} addressOrPublicKey Recipient's ADAMANT address or public key.
* Address is preferred, as if we get public key, we should derive address from it.
* @param {string, number} amount Amount to send
* @param {boolean} isAmountInADM If amount specified in ADM, or in sats (10^-8 ADM)
* @param {number} maxRetries How much times to retry request
* @returns {Promise} Request results
*/
return (passPhrase, username, maxRetries = DEFAULT_SEND_TOKENS_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)

}

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

}
};
16 changes: 12 additions & 4 deletions helpers/validator.js
Expand Up @@ -84,24 +84,24 @@ module.exports = {

let json = this.tryParseJSON(message)

if (!json)
if (!json)
return {
result: false,
error: `For rich and signal messages, 'message' must be a JSON string`
}

if (json.type && json.type.toLowerCase().includes('_transaction'))
if (json.type.toLowerCase() !== json.type)
return {
result: false,
error: `Value '<coin>_transaction' must be in lower case`
}

if (typeof json.amount !== 'string' || !this.validateStringAmount(json.amount))
return {
result: false,
error: `Field 'amount' must be a string, representing a number`
}
}

}
}
Expand All @@ -110,6 +110,14 @@ module.exports = {
}
},

validateDelegateName(name) {
if (typeof name !== 'string') {
return false;
}

return /^[\w!@$&_]*$/.test(name);
},

AdmToSats(amount) {
return BigNumber(String(amount)).multipliedBy(constants.SAT).integerValue().toNumber()
},
Expand Down
4 changes: 3 additions & 1 deletion index.js
Expand Up @@ -2,6 +2,7 @@ const constants = require('./helpers/constants.js');
const get = require('./groups/get');
const getPublicKey = require('./groups/getPublicKey');
const decodeMsg = require('./groups/decodeMsg');
const delegateNew = require('./groups/delegateNew');
const sendTokens = require('./groups/sendTokens');
const sendMessage = require('./groups/sendMessage');
const healthCheck = require('./helpers/healthCheck');
Expand All @@ -19,12 +20,13 @@ module.exports = (params, log) => {
log = log || console;
logger.initLogger(params.logLevel, log);
const nodeManager = healthCheck(params.node);

return {
get: get(nodeManager),
getPublicKey: getPublicKey(nodeManager),
sendTokens: sendTokens(nodeManager),
sendMessage: sendMessage(nodeManager),
delegateNew: delegateNew(nodeManager),
decodeMsg,
eth,
dash,
Expand Down

0 comments on commit 6d40ec0

Please sign in to comment.