Skip to content

Commit

Permalink
Build 0.7.4
Browse files Browse the repository at this point in the history
  • Loading branch information
emiliorizzo committed Mar 13, 2019
1 parent 0deb170 commit 7d311c7
Show file tree
Hide file tree
Showing 23 changed files with 329 additions and 154 deletions.
4 changes: 4 additions & 0 deletions dist/api/Address.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ class Address extends _DataCollector.DataCollectorItem {
type: _types.addrTypes.CONTRACT,
contractInterfaces: { $in: _types.tokensInterfaces } },
params);
},

getCirculatingSupply: params => {
return this.parent.getCirculatingSupply();
} };

}}exports.Address = Address;exports.default =
Expand Down
57 changes: 36 additions & 21 deletions dist/api/Blocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ var _Tx = require('./Tx');
var _Address = require('./Address');
var _Event = require('./Event');
var _TokenAccount = require('./TokenAccount');
var _TxPending = require('./TxPending');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
var _TxPending = require('./TxPending');
var _getCirculatingSupply = require('./getCirculatingSupply');var _getCirculatingSupply2 = _interopRequireDefault(_getCirculatingSupply);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

const lastLimit = _config2.default.api.lastBlocks || 10;
const collections = _config2.default.blocks.collections;

class Blocks extends _DataCollector.DataCollector {
constructor(db) {
let collectionName = collections.Blocks;
Expand All @@ -17,6 +20,7 @@ class Blocks extends _DataCollector.DataCollector {
this.latest = 0;
this.lastBlocks = [];
this.lastTransactions = [];
this.circulatingSupply = null;
this.addItem(collections.Blocks, 'Block', _Block.Block);
this.addItem(collections.PendingTxs, 'TxPending', _TxPending.TxPending);
this.addItem(collections.Txs, 'Tx', _Tx.Tx);
Expand All @@ -26,41 +30,51 @@ class Blocks extends _DataCollector.DataCollector {
}
tick() {
this.setLastBlocks();
this.setCirculatingSupply();
}

run(module, action, params) {
return this.itemPublicAction(module, action, params);
}
setLastBlocks() {
this.collection.
find().
sort({ number: -1 }).
limit(this.lastLimit).
toArray((err, blocks) => {
if (err) console.log(err);else
{
this.Tx.db.
find({ txType: { $in: [_types.txTypes.default, _types.txTypes.contract] } }).
sort({ blockNumber: -1, transactionIndex: -1 }).
limit(this.lastLimit).
toArray((err, txs) => {
if (err) console.log(err);else
{
this.updateLastBlocks(blocks, txs);
}
});
}
});

async setLastBlocks() {
try {
let { collection, lastLimit, Tx } = this;
let blocks = await collection.find().sort({ number: -1 }).limit(lastLimit).toArray();
let txs = await Tx.db.find({ txType: { $in: [_types.txTypes.default, _types.txTypes.contract] } }).
sort({ blockNumber: -1, transactionIndex: -1 }).
limit(this.lastLimit).
toArray();

this.updateLastBlocks(blocks, txs);
} catch (err) {
console.log(err);
}
}

async setCirculatingSupply() {
try {
const collection = this.db.collection(collections.Addrs);
let circulating = await (0, _getCirculatingSupply2.default)(collection);
this.circulatingSupply = Object.assign({}, circulating);
} catch (err) {
console.log(err);
}
}
getCirculatingSupply() {
return this.formatData(this.circulatingSupply);
}

getLastBlocks() {
let blocks = this.lastBlocks;
let transactions = this.lastTransactions;
return this.formatData({ blocks, transactions });
}

getLastBlock() {
return this.lastBlocks[0] || null;
}

updateLastBlocks(blocks, transactions) {
this.lastBlocks = blocks;
this.lastTransactions = transactions;
Expand All @@ -71,6 +85,7 @@ class Blocks extends _DataCollector.DataCollector {
this.events.emit('newBlocks', this.formatData({ blocks, transactions }));
}
}

async getAddress(address) {
return this.Address.run('getAddress', { address });
}
Expand Down
25 changes: 25 additions & 0 deletions dist/api/HttpServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.HttpServer = undefined;var _http = require('http');var _http2 = _interopRequireDefault(_http);
var _express = require('express');var _express2 = _interopRequireDefault(_express);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

const HttpServer = exports.HttpServer = ({ blocks, status }) => {
const app = (0, _express2.default)();
const httpServer = _http2.default.Server(app);
app.set('etag', false);
app.set('x-powered-by', false);

app.use('/status', (req, res) => {
const data = status.getState().data;
res.send(data);
});

app.use('/circulating', (req, res) => {
const data = blocks.getCirculatingSupply().data;
res.send(data);
});

// 404
app.use((req, res, next) => res.status(404).send());
return httpServer;
};exports.default =

HttpServer;
22 changes: 18 additions & 4 deletions dist/api/TokenAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,35 @@ class TokenAccount extends _DataCollector.DataCollectorItem {
},

getTokenBalance: async params => {
const { contract } = params;
const { contract, addresses } = params;
if (!contract) return;

let query = {};

if (addresses) query = this.fieldFilterParse('address', addresses);

let contractData = await this.parent.getAddress(contract);

contractData = contractData.data;
if (!contractData) return;
let { totalSupply } = contractData;

let { totalSupply, decimals } = contractData;
if (!totalSupply) return;
let accounts = await this.find({ contract });

query.contract = contract;
let accounts = await this.find(query, null, null, { _id: 0, address: 1, balance: 1 });
if (accounts) accounts = accounts.data;
if (!accounts) return;

let accountsBalance = (0, _utils.bigNumberSum)(accounts.map(account => account.balance));
totalSupply = new _bignumber.BigNumber(totalSupply);
let balance = accountsBalance ? totalSupply.minus(accountsBalance) : totalSupply;
let data = { balance, accountsBalance, totalSupply, decimals

// send accounts
};if (addresses) data.accounts = accounts;

const data = this.serialize({ balance, accountsBalance, totalSupply });
data = this.serialize(data);
return { data };
} };

Expand Down
2 changes: 1 addition & 1 deletion dist/api/UserEventsApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ var _config = require('../lib/config');var _config2 = _interopRequireDefault(_co
var _apiLib = require('./apiLib');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}

function UserEventsSocket() {
return (0, _child_process.fork)(_path2.default.resolve(__dirname, '../services/userEvents.js'));
return (0, _child_process.fork)(_path2.default.resolve(__dirname, '../services/userEvents/userEventsService.js'));
}

const UserEventsApi = exports.UserEventsApi = (io, Blocks, log) => {
Expand Down
16 changes: 16 additions & 0 deletions dist/api/getCirculatingSupply.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _config = require('../lib/config');var _config2 = _interopRequireDefault(_config);
var _types = require('../lib/types');
var _utils = require('../lib/utils');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const { bridgeAddress } = _config2.default;exports.default =

async function (collection) {
try {
let { balance, decimals } = await collection.findOne({ address: bridgeAddress });
decimals = decimals || 18;
const bridgeBalance = (0, _utils.applyDecimals)(balance, decimals).toString(10);
let circulatingSupply = (0, _utils.bigNumberDifference)(_types.TOTAL_SUPPLY, bridgeBalance).toString(10);
return { circulatingSupply, totalSupply: _types.TOTAL_SUPPLY, bridgeBalance };
} catch (err) {
return Promise.reject(err);
}
};
15 changes: 4 additions & 11 deletions dist/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ var _Blocks = require('./Blocks');var _Blocks2 = _interopRequireDefault(_Blocks)
var _Status = require('./Status');var _Status2 = _interopRequireDefault(_Status);
var _TxPool = require('./TxPool');var _TxPool2 = _interopRequireDefault(_TxPool);
var _Logger = require('../lib/Logger');var _Logger2 = _interopRequireDefault(_Logger);
var _http = require('http');var _http2 = _interopRequireDefault(_http);
var _UserEventsApi = require('./UserEventsApi');var _UserEventsApi2 = _interopRequireDefault(_UserEventsApi);
var _config = require('../lib/config');var _config2 = _interopRequireDefault(_config);
var _HttpServer = require('./HttpServer');

var _apiLib = require('./apiLib');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}


Expand All @@ -32,16 +33,8 @@ _dataSource2.default.then(db => {
status.start();
txPool.start();

const httpServer = _http2.default.createServer((req, res) => {
const url = req.url || null;
if (url && url === '/status') {
res.writeHead(200, { 'Content-type': 'application/json' });
res.write(JSON.stringify(status.state));
} else {
res.writeHead(404, 'Not Found');
}
res.end();
});
// http server
const httpServer = (0, _HttpServer.HttpServer)({ blocks, status });
httpServer.listen(port, address);
const io = new _socket2.default(httpServer);

Expand Down
3 changes: 2 additions & 1 deletion dist/lib/DataCollector/DataCollectorItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ filterSort = filterSort;exports.

fieldFilterParse = fieldFilterParse;var _mongodb = require('mongodb');var _pagination = require('./pagination');var _types = require('../../lib/types');class DataCollectorItem {constructor(collection, key, parent, { cursorField = '_id', sortDir = -1, sortable = { _id: -1 } } = {}) {if (!(collection instanceof _mongodb.Collection)) {throw new Error('Collection is not mongodb Collection');}this.db = collection;this.key = key;this.parent = parent;this.fieldsTypes = null;this.cursorField = cursorField;this.cursorData = null;this.sortDir = sortDir;sortable[cursorField] = sortDir;this.sortableFields = sortable;this.sort = { [cursorField]: sortDir };this.publicActions = {};this.fields = {};}getDefaultsFields() {return Object.assign({}, this.fields);}async run(action, params) {try {const f = this.publicActions[action];if (f && typeof f === 'function') return f(params);else throw new Error(`Unknown action: ${action}`);} catch (err) {return Promise.reject(err);}}async find(query, sort, limit, project) {let collection = this.db;project = project || this.getDefaultsFields();let data = await (0, _pagination.find)(collection, query, sort, limit, project);return { data };}async getOne(query, project) {project = project || this.getDefaultsFields();let data = await this.db.findOne(query, { project });return { data };}async setFieldsTypes() {let types = await getFieldsTypes(this.db);this.fieldsTypes = types;return types;}async getFieldsTypes() {let types = this.fieldsTypes;return types || this.setFieldsTypes();}responseParams(params) {let sort = params.sort || this.sort || {};let sortable = this.sortableFields;let defaultSort = this.sort;let sortDir = this.sortDir;let { limit, next, prev, fields, count, countOnly, page, getPages } = params;if (!fields) fields = this.getDefaultsFields();sort = filterSort(sort, sortable, defaultSort);return { sort, sortable, defaultSort, sortDir, limit, next, prev, fields, count, countOnly, page, getPages };}async getCursorData() {let data = this.cursorData;if (!data) data = await this.setCursorData();return data;}async setCursorData() {const cursorField = this.cursorField;const types = await this.getFieldsTypes();const cursorType = types[cursorField];this.cursorData = { cursorField, cursorType, fields: types };return this.cursorData;}getPageData(query, params) {return this.getPages({ query, params });}getAggPageData(aggregate, params) {return this.getPages({ aggregate, params });}async getPrevNext(query, project, data) {try {let { cursorField } = this;project = project || this.getDefaultsFields();if (!data) data = await this.getOne(query);if (data) data = data.data;if (!data) return;let value = query[cursorField] || data[cursorField];if (undefined === value) throw new Error(`Missing ${cursorField} value`);let prev = (await (0, _pagination.find)(this.db, { [cursorField]: { $lt: value } }, { [cursorField]: -1 }, 1, project))[0];let next = (await (0, _pagination.find)(this.db, { [cursorField]: { $gt: value } }, { [cursorField]: 1 }, 1, project))[0];return { prev, data, next };} catch (err) {return Promise.reject(err);}}async getPages({ aggregate, query, params }) {try {let pages = this.responseParams(params);let cursorData = await this.getCursorData();query = aggregate || query;let args = [this.db, cursorData, query, pages];let result = aggregate ? await (0, _pagination.aggregatePages)(...args) : await (0, _pagination.findPages)(...args);return formatResponse(result, pages);} catch (err) {return Promise.reject(err);}}fieldFilterParse(field, value, query) {return fieldFilterParse(field, value, query);}}exports.DataCollectorItem = DataCollectorItem;function formatResponse(result, pages) {if (!result) return;let { data, pagination } = result;pages = Object.assign(pages, pagination);return { pages, data };}async function getFieldsTypes(collection) {let doc = await collection.findOne();let fields = {};for (let p in doc) {let value = doc[p];let type = typeof value;type = value instanceof _mongodb.ObjectID ? _types.OBJECT_ID : type;fields[p] = type;}return fields;}function filterSort(sort, sortable, defaultSort) {let filteredSort = {}; // allow only one field to user sort
if (Object.keys(sort).length > 1) return defaultSort;for (let field in sort) {if (undefined !== sortable[field]) filteredSort[field] = sort[field];}return Object.keys(filteredSort).length > 0 ? filteredSort : defaultSort;} // value: string| array of searched values | Object: 'value':true|false
function fieldFilterParse(field, value, query) {query = query || {};let fieldQuery;
function fieldFilterParse(field, value, query) {query = query || {};if (!field || !value || typeof field !== 'string') return query;
let fieldQuery;
let inArr = [];
let ninArr = [];
if (typeof value === 'string') {
Expand Down
8 changes: 8 additions & 0 deletions dist/lib/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@
key: { blockNumber: 1 },
name: 'eventBlockNumberIndex' },

{
key: { txHash: 1 },
name: 'eventTxHashIndex' },

{
key: { blockHash: 1 },
name: 'eventBlockHashIndex' },

{
key: { args: 1 },
name: 'eventsArgsIndex' },
Expand Down
6 changes: 4 additions & 2 deletions dist/lib/types.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.OBJECT_ID = exports.BIG_NUMBER = exports.REMASC_NAME = exports.BRIDGE_NAME = exports.modules = exports.actions = exports.events = exports.tokensInterfaces = exports.contractsInterfaces = exports.addrTypes = exports.errors = exports.txTypes = undefined;var _errors = require('../lib/errors');
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.TOTAL_SUPPLY = exports.OBJECT_ID = exports.BIG_NUMBER = exports.REMASC_NAME = exports.BRIDGE_NAME = exports.modules = exports.actions = exports.events = exports.tokensInterfaces = exports.contractsInterfaces = exports.addrTypes = exports.errors = exports.txTypes = undefined;var _errors = require('../lib/errors');

const txTypes = exports.txTypes = {
default: 'normal',
Expand Down Expand Up @@ -68,6 +68,8 @@ const REMASC_NAME = exports.REMASC_NAME = 'remasc (native)';

const BIG_NUMBER = exports.BIG_NUMBER = 'BigNumber';

const OBJECT_ID = exports.OBJECT_ID = 'ObjectID';exports.default =
const OBJECT_ID = exports.OBJECT_ID = 'ObjectID';

const TOTAL_SUPPLY = exports.TOTAL_SUPPLY = 21 * 10 ** 6;exports.default =

{ txTypes, errors, addrTypes, contractsInterfaces };
19 changes: 17 additions & 2 deletions dist/lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.jsonDecode = exports.jsonEncode = exports.keccak256 = exports.base64toHex = exports.btoa = exports.atob = exports.includesAll = exports.hasValue = exports.arraySymmetricDifference = exports.arrayDifference = exports.arrayIntersection = exports.getBestBlock = exports.blockQuery = exports.isBlockHash = exports.checkBlockHash = exports.serialize = exports.bigNumberSum = exports.bigNumberToSring = exports.unSerializeBigNumber = exports.isSerializedBigNumber = exports.serializeBigNumber = exports.isBigNumber = exports.bigNumberDoc = exports.isValidAddress = exports.isAddress = exports.remove0x = exports.add0x = exports.isHexString = undefined;var _bignumber = require('bignumber.js');
'use strict';Object.defineProperty(exports, "__esModule", { value: true });exports.jsonDecode = exports.jsonEncode = exports.keccak256 = exports.applyDecimals = exports.base64toHex = exports.btoa = exports.atob = exports.includesAll = exports.hasValue = exports.arraySymmetricDifference = exports.arrayDifference = exports.arrayIntersection = exports.getBestBlock = exports.blockQuery = exports.isBlockHash = exports.checkBlockHash = exports.serialize = exports.newBigNumber = exports.bigNumberDifference = exports.bigNumberSum = exports.bigNumberToSring = exports.unSerializeBigNumber = exports.isSerializedBigNumber = exports.serializeBigNumber = exports.isBigNumber = exports.bigNumberDoc = exports.isValidAddress = exports.isAddress = exports.remove0x = exports.add0x = exports.isHexString = undefined;var _bignumber = require('bignumber.js');
var _types = require('./types');
var _mongodb = require('mongodb');
var _keccak = require('keccak');var _keccak2 = _interopRequireDefault(_keccak);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
Expand Down Expand Up @@ -70,12 +70,20 @@ const bigNumberSum = exports.bigNumberSum = values => {
let total = new _bignumber.BigNumber(0);
values.
forEach(value => {
value = isBigNumber(value) ? value : new _bignumber.BigNumber(value);
value = newBigNumber(value);
total = total.plus(value);
});
return total;
};

const bigNumberDifference = exports.bigNumberDifference = (a, b) => {
a = newBigNumber(a);
b = newBigNumber(b);
return a.minus(b);
};

const newBigNumber = exports.newBigNumber = value => isBigNumber(value) ? value : new _bignumber.BigNumber(value);

const isObj = value => {
if (undefined === value || value === null) return false;
let is = typeof value === 'object';
Expand Down Expand Up @@ -157,6 +165,13 @@ const base64toHex = exports.base64toHex = base64 => {
}).join('').toLowerCase();
};

const applyDecimals = exports.applyDecimals = (value, decimals = 18) => {
value = newBigNumber(value);
const divisor = new _bignumber.BigNumber(10).exponentiatedBy(parseInt(decimals));
const result = value.dividedBy(divisor);
return result;
};

const keccak256 = exports.keccak256 = (input, format = 'hex') => (0, _keccak2.default)('keccak256').update(input).digest(format);

const jsonEncode = exports.jsonEncode = value => btoa(JSON.stringify(value));
Expand Down
2 changes: 2 additions & 0 deletions dist/services/blocks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ _dataSource.dataBase.db().then(db => {

}
};
/* eslint-disable-next-line no-unused-vars */
const Listener = startService('Listener', listenToMessage);
const Checker = startService('Checker', listenToMessage);
const Requester = startService('Requester', listenToMessage);
/* eslint-disable-next-line no-unused-vars */
const TxPool = startService('TxPool', listenToMessage, '../txPool.js');
});
});
Expand Down
Loading

0 comments on commit 7d311c7

Please sign in to comment.