UNPKG

@bpanel/bpanel-utils

Version:
118 lines (92 loc) 3.1 kB
'use strict'; var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _typeof2 = require('babel-runtime/helpers/typeof'); var _typeof3 = _interopRequireDefault(_typeof2); var _uxtx = require('./uxtx.js'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var assert = require('bsert'); class TxManager { constructor(options) { // hash -> parsed transaction this._parsed = {}; this._constants = null; this._custom = null; this._labels = null; if (options) this.fromOptions(options); } static fromOptions(options) { return new this().fromOptions(options); } /** * Inject properties from options object. * @private * @param {Object} options * @param {Object} options.constants - constants used interally * @param {Object} options.labels - * human readable labels, used in toJSON output * @param {Object} options.custom - * custom function to apply on list of transaction json */ fromOptions(options) { assert((typeof options === 'undefined' ? 'undefined' : (0, _typeof3.default)(options)) === 'object', 'must pass options object'); if (options.custom) { assert(typeof options.custom === 'function'); this._custom = options.custom; } return this; } /** * Clear any cached values. */ refresh() { this._parsed = {}; } /** * Parse transactions into human readable form * @param {Object[]} transactions * @param {Object} UXTXOpts * @param {String|null} UXTXOpts.wallet * @param {Boolen} bust - bust the cache * * User can call more than once for transactions * from different wallets */ parse(transactions, UXTXOpts) { var _this = this; var bust = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; assert(Array.isArray(transactions), 'Must pass list of txs'); assert((typeof UXTXOpts === 'undefined' ? 'undefined' : (0, _typeof3.default)(UXTXOpts)) === 'object', 'Must pass UXTXOptions'); // use custom parsing function if (this._custom) { var out = this._custom(transactions, UXTXOpts, bust); assert(Array.isArray(out), 'Must return list from custom tx parse function'); return out; } return transactions.map(function (txn) { // no global bust and the transaction already parsed if (bust === false && txn.hash in _this._parsed) return _this._parsed[txn.hash]; var options = (0, _extends3.default)({}, UXTXOpts, { json: txn }); var uxtx = _uxtx.UXTX.fromRaw(txn.tx, 'hex', options); // cache output var json = uxtx.toJSON(); _this._parsed[txn.hash] = json; return json; }); } } // initial null custom parsing function var custom = null; // initial options // bundle together with UXTX opts // so that TxManager can handle setting // options of all txs it manages var TxManagerOptions = { custom: custom }; module.exports = { TxManager: TxManager, TxManagerOptions: TxManagerOptions };