Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
const { promisify } = require('util');
// Inline promisify shim — avoids requiring Node's `util` module so this file
// can be bundled for browsers without a polyfill. If the codegen template
// is regenerated, restore this shim.
function promisify(fn) {
return (...args) => new Promise((resolve, reject) => {
fn(...args, (err, result) => (err ? reject(err) : resolve(result)));
});
}
const GrpcError = require('@dashevo/grpc-common/lib/server/error/GrpcError');

const { CoreClient } = require('./core_pb_service');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
const { PlatformClient } = require('./platform_pb_service');
const { promisify } = require('util');

// Inline promisify shim — avoids requiring Node's `util` module so this file
// can be bundled for browsers without a polyfill. If the codegen template
// is regenerated, restore this shim.
function promisify(fn) {
return (...args) => new Promise((resolve, reject) => {
fn(...args, (err, result) => (err ? reject(err) : resolve(result)));
});
}

class PlatformPromiseClient {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const SimplifiedMNListDiff = require('@dashevo/dashcore-lib/lib/deterministicmnl
const cbor = require('cbor');

const logger = require('../logger');
const { bytesToHex } = require('../utils/bytes');

class SimplifiedMasternodeListProvider {
/**
Expand Down Expand Up @@ -100,11 +101,11 @@ class SimplifiedMasternodeListProvider {

let simplifiedMNListDiff;
let simplifiedMNListDiffObject;
let simplifiedMNListDiffBuffer;
let simplifiedMNListDiffBytes;
try {
simplifiedMNListDiffBuffer = Buffer.from(response.getMasternodeListDiff_asU8());
simplifiedMNListDiffBytes = new Uint8Array(response.getMasternodeListDiff_asU8());

simplifiedMNListDiffObject = cbor.decodeFirstSync(simplifiedMNListDiffBuffer);
simplifiedMNListDiffObject = cbor.decodeFirstSync(simplifiedMNListDiffBytes);

simplifiedMNListDiff = new SimplifiedMNListDiff(
simplifiedMNListDiffObject,
Expand All @@ -118,7 +119,7 @@ class SimplifiedMasternodeListProvider {
network: this.options.network,
error: e,
simplifiedMNListDiffObject,
simplifiedMNListDiffBytes: simplifiedMNListDiffBuffer.toString('hex'),
simplifiedMNListDiffBytes: bytesToHex(simplifiedMNListDiffBytes),
},
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const sample = require('lodash/sample');
const sample = (arr) => arr[Math.floor(Math.random() * arr.length)];
const networks = require('@dashevo/dashcore-lib/lib/networks');

class ListDAPIAddressProvider {
Expand Down
2 changes: 0 additions & 2 deletions packages/js-dapi-client/lib/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
require('../polyfills/fetch-polyfill');

const DAPIClient = require('./DAPIClient');

const NotFoundError = require('./transport/GrpcTransport/errors/NotFoundError');
Expand Down
105 changes: 29 additions & 76 deletions packages/js-dapi-client/lib/logger/index.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,33 @@
const util = require('util');
const winston = require('winston');
const LOG_LEVEL = (typeof process !== 'undefined' && process.env && process.env.LOG_LEVEL) || 'silent';

// TODO: Refactor to use params instead on envs

const LOG_LEVEL = process.env.LOG_LEVEL || 'silent';
const LOG_TO_FILE = process.env.LOG_WALLET_TO_FILE || 'false';

// Log levels:
// error 0
// warn 1
// info 2 (default)
// verbose 3
// debug 4
// silly 5

const loggers = {};

const createLogger = (formats = [], id = '') => {
const format = winston.format.combine(
{
transform: (info) => {
const args = info[Symbol.for('splat')];
const result = { ...info };
if (args) {
result.message = util.format(info.message, ...args);
}
return result;
},
},
...formats,
winston.format.colorize(),
winston.format.printf(({
level, message,
}) => `${level}: ${message}`),
);

const transports = [
new winston.transports.Console({
format,
silent: LOG_LEVEL === 'silent',
}),
];

if (LOG_TO_FILE === 'true' && typeof window === 'undefined') {
transports.push(
new winston.transports.File({
filename: `wallet${id !== '' ? `_${id}` : ''}`,
format,
silent: LOG_LEVEL === 'silent',
}),
);
}

return winston.createLogger({
level: LOG_LEVEL,
transports,
});
const LEVELS = {
silent: -1, error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5,
};

const logger = createLogger();

logger.getForId = (id) => {
if (!loggers[id]) {
const format = {
transform: (info) => {
const message = `[DAPIClient: ${id}] ${info.message}`;
return { ...info, message };
},
};

loggers[id] = createLogger([format], id);
}

return loggers[id];
};

logger.verbose(`Logger uses "${LOG_LEVEL}" level`, { level: LOG_LEVEL });
const cache = {};

function build(level = LOG_LEVEL, prefix = '') {
const threshold = LEVELS[level] != null ? LEVELS[level] : LEVELS.silent;
const noop = () => {};
const fmt = prefix ? (...a) => [prefix, ...a] : (...a) => a;

const logger = {
error: threshold >= 0 ? (...a) => console.error(...fmt(...a)) : noop,

Check warning on line 15 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 15 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
warn: threshold >= 1 ? (...a) => console.warn(...fmt(...a)) : noop,

Check warning on line 16 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 16 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
info: threshold >= 2 ? (...a) => console.info(...fmt(...a)) : noop,

Check warning on line 17 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 17 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
verbose: threshold >= 3 ? (...a) => console.debug(...fmt(...a)) : noop,

Check warning on line 18 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 18 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
debug: threshold >= 4 ? (...a) => console.debug(...fmt(...a)) : noop,

Check warning on line 19 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 19 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
silly: threshold >= 5 ? (...a) => console.debug(...fmt(...a)) : noop,

Check warning on line 20 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement

Check warning on line 20 in packages/js-dapi-client/lib/logger/index.js

View workflow job for this annotation

GitHub Actions / JS packages (@dashevo/dapi-client) / Linting

Unexpected console statement
getForId(id, overrideLevel) {
const effective = overrideLevel || level;
const key = `${id}\0${effective}`;
if (!cache[key]) {
cache[key] = build(effective, `[DAPIClient: ${id}]`);
}
return cache[key];
},
};
return logger;
}

module.exports = logger;
module.exports = build();
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function getBlockByHashFactory(grpcTransport) {
* @typedef {getBlockByHash}
* @param {string} hash
* @param {DAPIClientOptions} [options]
* @returns {Promise<null|Buffer>}
* @returns {Promise<null|Uint8Array>}
*/
async function getBlockByHash(hash, options = {}) {
const getBlockRequest = new GetBlockRequest();
Expand All @@ -29,7 +29,7 @@ function getBlockByHashFactory(grpcTransport) {
);
const blockBinaryArray = response.getBlock();

return Buffer.from(blockBinaryArray);
return new Uint8Array(blockBinaryArray);
}

return getBlockByHash;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function getBlockByHeightFactory(grpcTransport) {
* @typedef {getBlockByHeight}
* @param {number} height
* @param {DAPIClientOptions} [options]
* @returns {Promise<null|Buffer>}
* @returns {Promise<null|Uint8Array>}
*/
async function getBlockByHeight(height, options = {}) {
const getBlockRequest = new GetBlockRequest();
Expand All @@ -30,7 +30,7 @@ function getBlockByHeightFactory(grpcTransport) {

const blockBinaryArray = response.getBlock();

return Buffer.from(blockBinaryArray);
return new Uint8Array(blockBinaryArray);
}

return getBlockByHeight;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@ function getBlockchainStatusFactory(grpcTransport) {

const responseObject = response.toObject();

// Respond with Buffers instead of base64 for binary fields
// Respond with Uint8Arrays instead of base64 for binary fields

if (response.getChain()) {
if (response.getChain()
.getBestBlockHash()) {
responseObject.chain.bestBlockHash = Buffer.from(response.getChain()
responseObject.chain.bestBlockHash = new Uint8Array(response.getChain()
.getBestBlockHash());
}

if (response.getChain()
.getChainWork()) {
responseObject.chain.chainWork = Buffer.from(response.getChain()
responseObject.chain.chainWork = new Uint8Array(response.getChain()
.getChainWork());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
CorePromiseClient,
},
} = require('@dashevo/dapi-grpc');
const { base64ToBytes } = require('../../utils/bytes');

/**
* @param {GrpcTransport} grpcTransport
Expand Down Expand Up @@ -34,7 +35,7 @@ function getMasternodeStatusFactory(grpcTransport) {
responseObject.status = Object.keys(GetMasternodeStatusResponse.Status)
.find((key) => GetMasternodeStatusResponse.Status[key] === responseObject.status);

responseObject.proTxHash = Buffer.from(responseObject.proTxHash, 'base64');
responseObject.proTxHash = base64ToBytes(responseObject.proTxHash);

return responseObject;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ class GetTransactionResponse {
/**
*
* @param {object} properties
* @param {Buffer} properties.transaction
* @param {Buffer} properties.blockHash
* @param {Uint8Array} properties.transaction
* @param {Uint8Array} properties.blockHash
* @param {number} properties.height
* @param {number} properties.confirmations
* @param {boolean} properties.isInstantLocked
Expand All @@ -22,15 +22,15 @@ class GetTransactionResponse {

/**
* Get transaction
* @returns {Buffer}
* @returns {Uint8Array}
*/
getTransaction() {
return this.transaction;
}

/**
* Get block hash
* @returns {Buffer}
* @returns {Uint8Array}
*/
getBlockHash() {
return this.blockHash;
Expand Down Expand Up @@ -75,8 +75,8 @@ class GetTransactionResponse {
}

return new GetTransactionResponse({
transaction: Buffer.from(transactionBinaryArray),
blockHash: Buffer.from(proto.getBlockHash()),
transaction: new Uint8Array(transactionBinaryArray),
blockHash: new Uint8Array(proto.getBlockHash()),
height: proto.getHeight(),
confirmations: proto.getConfirmations(),
isInstantLocked: proto.getIsInstantLocked(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
} = require('@dashevo/dapi-grpc');

const DAPIClientError = require('../../errors/DAPIClientError');
const { hexToBytes } = require('../../utils/bytes');

/**
* @param {GrpcTransport} grpcTransport
Expand Down Expand Up @@ -41,7 +42,7 @@ function subscribeToBlockHeadersWithChainLocksFactory(grpcTransport) {

if (options.fromBlockHash) {
request.setFromBlockHash(
Buffer.from(options.fromBlockHash, 'hex'),
hexToBytes(options.fromBlockHash),
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const {
} = require('@dashevo/dapi-grpc');

const DAPIClientError = require('../../errors/DAPIClientError');
const { hexToBytes } = require('../../utils/bytes');

/**
* @param {GrpcTransport} grpcTransport
Expand Down Expand Up @@ -65,7 +66,7 @@ function subscribeToTransactionsWithProofsFactory(grpcTransport) {

if (options.fromBlockHash) {
request.setFromBlockHash(
Buffer.from(options.fromBlockHash, 'hex'),
hexToBytes(options.fromBlockHash),
);
}

Expand Down
Loading
Loading