mazzaroth-js
Version:
Library that facilitates interaction with Mazzaroth nodes from both the browser and node-js
155 lines (125 loc) • 6.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PollReceipt = PollReceipt;
exports.JSONtoXDR = JSONtoXDR;
exports.XDRtoJSON = XDRtoJSON;
exports.GenerateNonce = GenerateNonce;
exports.AddressFromPrivate = AddressFromPrivate;
var _debug = require("debug");
var _debug2 = _interopRequireDefault(_debug);
var _deepmerge = require("deepmerge");
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _mazzarothXdr = require("mazzaroth-xdr");
var types = _interopRequireWildcard(_mazzarothXdr);
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Common utility functions used by the Mazzaroth Client.
*
*/
const debug = (0, _debug2.default)('mazzaroth-js:client-utils');
/**
* Polls a node for the result of a specific transaction. It does this by
* repeatedly checking for a transaction's receipt. Calls the resolve/reject
* functions based on the results of the polling.
*
* @param channelID Hex string (32 chars) identifier for the channel.
* @param transactionID Hex string (32 chars) identifier for the transaction submitted
* to the Mazzaroth node.
* @param resolve Promise function to resolve upon success.
* @param reject Promise function to reject upon failure.
* @param nodeClient Client to use during receipt lookup.
* @param lookupRetries Number of times to poll before returning a failure.
* @param lookupTimeout Amount of time in ms to wait between requests.
*
* @return none
*/
function pollReceipt(channelID, transactionID, resolve, reject, nodeClient, lookupRetries, lookupTimeout) {
nodeClient.ReceiptLookup(channelID, transactionID).then(res => {
const receipt = res.toJSON();
debug('Receipt lookup result: %o', receipt); // Check response is receipt
if (receipt.transactionID) {
return resolve(res);
} // Check timeout.
if (lookupRetries === 0) {
return reject(new Error('Request timeout.'));
}
setTimeout(() => {
PollReceipt(channelID, transactionID, resolve, reject, nodeClient, lookupRetries - 1, lookupTimeout);
}, lookupTimeout);
}).catch(err => reject(err));
}
/**
* Polls a node for the result of a specific transaction. It does this by
* repeatedly checking for a transaction's receipt. Calls the resolve/reject
* functions based on the results of the polling.
*
* @param nodeClient Node-client to use for node operations.
* @param channelID Hex string (32 chars) identifier for the channel.
* @param transactionID Hex string (32 chars) identifier for the transaction submitted
* to the Mazzaroth node.
* @param lookupRetries Number of times to poll before returning a failure.
* @param lookupTimeout Amount of time in ms to wait between requests.
*
* @return Promise that on success provides an XDR ReceiptLookupResponse.
*/
function PollReceipt(nodeClient, channelID, transactionID, lookupRetries = 5, lookupTimeout = 500) {
return new Promise((resolve, reject) => {
pollReceipt(channelID, transactionID, resolve, reject, nodeClient, lookupRetries, lookupTimeout);
});
}
/**
* Translates a json string to a base64 XDR representation of the supplied data
* type. If the json string is not complete, the function will do its best to
* interpolate the json properties into a default XDR object.
*
* @param input Json string to convert to XDR.
* @param type String xdr object from mazzaroth-xdr i.e. 'Transaction'.
* @return String base64 representation of XDR binary.
*/
function JSONtoXDR(input, type) {
if (types[type] === undefined) {
throw new Error(`Could not identify type '${type}'`);
}
const xdrObj = types[type]();
const xdrJSON = xdrObj.toJSON();
const result = (0, _deepmerge2.default)(xdrJSON, JSON.parse(input));
xdrObj.fromJSON(result);
return xdrObj.toXDR('base64');
}
/**
* Translates an XDR string to a json string representation of the
* supplied data type.
*
* @param input String XDR representation matching the arg format.
* @param type String XDR object from mazzaroth-xdr i.e. 'Transaction'.
* @param format Data string format base64/hex defaults to base64.
* @return Json string representation of XDR object.
*/
function XDRtoJSON(input, type, format) {
if (types[type] === undefined) {
throw new Error(`Could not identify type '${type}'`);
}
format = format === undefined ? 'base64' : format;
if (format !== 'base64' && format !== 'hex') {
throw new Error(`Invalid format '${format}'`);
}
const xdrObj = types[type]().fromXDR(input, format);
return JSON.stringify(xdrObj.toJSON());
}
/**
* Return a random nonce value that may be used with the Transaction Builder
*/
function GenerateNonce() {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString();
}
/**
* Return the public key portion of a given private key
*/
function AddressFromPrivate(privateKey) {
// Public Key is last 64 hex characters of full private key
return privateKey.slice(64);
}