refactor: refactor clients.

This commit is contained in:
Christopher Jeffrey 2017-07-01 03:41:02 -07:00
parent 3e7c921ad3
commit c651136d83
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
3 changed files with 131 additions and 170 deletions

View File

@ -37,7 +37,7 @@ function HTTPClient(options) {
this.options = options;
this.network = Network.get(options.network);
this.uri = options.uri || 'http://localhost:' + this.network.rpcPort;
this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
this.socket = null;
this.apiKey = options.apiKey;
this.auth = options.auth;
@ -147,8 +147,10 @@ HTTPClient.prototype.onConnect = function onConnect() {
HTTPClient.prototype.sendAuth = function sendAuth() {
return new Promise((resolve, reject) => {
this.socket.emit('auth', this.apiKey, (err) => {
if (err)
return reject(new Error(err.message));
if (err) {
reject(new Error(err.message));
return;
}
resolve();
});
});
@ -163,8 +165,10 @@ HTTPClient.prototype.sendAuth = function sendAuth() {
HTTPClient.prototype.sendWalletAuth = function sendWalletAuth() {
return new Promise((resolve, reject) => {
this.socket.emit('wallet auth', this.apiKey, (err) => {
if (err)
return reject(new Error(err.message));
if (err) {
reject(new Error(err.message));
return;
}
resolve();
});
});
@ -224,7 +228,7 @@ HTTPClient.prototype._request = async function _request(method, endpoint, json)
throw new Error('Unauthorized (bad API key).');
if (res.statusCode !== 200)
throw new Error('Status code: ' + res.statusCode);
throw new Error(`Status code: ${res.statusCode}.`);
if (res.type !== 'json')
throw new Error('Bad response (wrong content-type).');
@ -293,7 +297,7 @@ HTTPClient.prototype._del = function _del(endpoint, json) {
/**
* Get a mempool snapshot.
* @returns {Promise} - Returns {@link TX}[].
* @returns {Promise} - Returns {@link Hash}[].
*/
HTTPClient.prototype.getMempool = function getMempool() {
@ -312,13 +316,12 @@ HTTPClient.prototype.getInfo = function getInfo() {
/**
* Get coins that pertain to an address from the mempool or chain database.
* Takes into account spent coins in the mempool.
* @param {Base58Address|Base58Address[]} addresses
* @param {String} address
* @returns {Promise} - Returns {@link Coin}[].
*/
HTTPClient.prototype.getCoinsByAddress = function getCoinsByAddress(address) {
let body = { address: address };
return this._post('/coin/address', body);
return this._post('/coin/address', { address });
};
/**
@ -330,19 +333,18 @@ HTTPClient.prototype.getCoinsByAddress = function getCoinsByAddress(address) {
*/
HTTPClient.prototype.getCoin = function getCoin(hash, index) {
return this._get('/coin/' + hash + '/' + index);
return this._get(`/coin/${hash}/${index}`);
};
/**
* Retrieve transactions pertaining to an
* address from the mempool or chain database.
* @param {Base58Address|Base58Address[]} addresses
* @param {String} address
* @returns {Promise} - Returns {@link TX}[].
*/
HTTPClient.prototype.getTXByAddress = function getTXByAddress(address) {
let body = { address: address };
return this._post('/tx/address', body);
return this._post('/tx/address', { address });
};
/**
@ -352,7 +354,7 @@ HTTPClient.prototype.getTXByAddress = function getTXByAddress(address) {
*/
HTTPClient.prototype.getTX = function getTX(hash) {
return this._get('/tx/' + hash);
return this._get(`/tx/${hash}`);
};
/**
@ -362,7 +364,7 @@ HTTPClient.prototype.getTX = function getTX(hash) {
*/
HTTPClient.prototype.getBlock = function getBlock(block) {
return this._get('/block/' + block);
return this._get(`/block/${block}`);
};
/**
@ -372,9 +374,7 @@ HTTPClient.prototype.getBlock = function getBlock(block) {
*/
HTTPClient.prototype.broadcast = function broadcast(tx) {
let body = { tx: toHex(tx) };
return this._post('/broadcast', body);
return this._post('/broadcast', { tx: toHex(tx) });
};
/**
@ -384,8 +384,7 @@ HTTPClient.prototype.broadcast = function broadcast(tx) {
*/
HTTPClient.prototype.rescan = function rescan(height) {
let options = { height: height };
return this._post('/wallet/_admin/rescan', options);
return this._post('/wallet/_admin/rescan', { height });
};
/**
@ -395,8 +394,7 @@ HTTPClient.prototype.rescan = function rescan(height) {
*/
HTTPClient.prototype.reset = function reset(height) {
let options = { height: height };
return this._post('/reset', options);
return this._post('/reset', { height });
};
/**
@ -415,13 +413,14 @@ HTTPClient.prototype.resend = function resend() {
*/
HTTPClient.prototype.backup = function backup(path) {
let options = { path: path };
return this._post('/wallet/_admin/backup', options);
return this._post('/wallet/_admin/backup', { path });
};
/**
* Listen for events on wallet id.
* @param {WalletID} id
* @param {String} id
* @param {String?} token
* @returns {Promise}
*/
HTTPClient.prototype.join = function join(id, token) {
@ -430,8 +429,10 @@ HTTPClient.prototype.join = function join(id, token) {
return new Promise((resolve, reject) => {
this.socket.emit('wallet join', id, token, (err) => {
if (err)
return reject(new Error(err.message));
if (err) {
reject(new Error(err.message));
return;
}
resolve();
});
});
@ -439,7 +440,7 @@ HTTPClient.prototype.join = function join(id, token) {
/**
* Unlisten for events on wallet id.
* @param {WalletID} id
* @param {String} id
*/
HTTPClient.prototype.leave = function leave(id) {
@ -448,8 +449,10 @@ HTTPClient.prototype.leave = function leave(id) {
return new Promise((resolve, reject) => {
this.socket.emit('wallet leave', id, (err) => {
if (err)
return reject(new Error(err.message));
if (err) {
reject(new Error(err.message));
return;
}
resolve();
});
});
@ -482,83 +485,78 @@ HTTPClient.prototype.getWallets = function getWallets() {
/**
* Create a wallet.
* @param {Object} options - See {@link Wallet}.
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createWallet = function createWallet(options) {
return this._put('/wallet/' + options.id, options);
return this._put(`/wallet/${options.id}`, options);
};
/**
* Get the raw wallet JSON.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getWallet = function getWallet(id) {
return this._get('/wallet/' + id);
return this._get(`/wallet/${id}`);
};
/**
* Get wallet transaction history.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getHistory = function getHistory(id, account) {
let options = { account: account };
return this._get('/wallet/' + id + '/tx/history', options);
return this._get(`/wallet/${id}/tx/history`, { account });
};
/**
* Get wallet coins.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getCoins = function getCoins(id, account) {
let options = { account: account };
return this._get('/wallet/' + id + '/coin', options);
return this._get(`/wallet/${id}/coin`, { account });
};
/**
* Get all unconfirmed transactions.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getPending = function getPending(id, account) {
let options = { account: account };
return this._get('/wallet/' + id + '/tx/unconfirmed', options);
return this._get(`/wallet/${id}/tx/unconfirmed`, { account });
};
/**
* Calculate wallet balance.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getBalance = function getBalance(id, account) {
let options = { account: account };
return this._get('/wallet/' + id + '/balance', options);
return this._get(`/wallet/${id}/balance`, { account });
};
/**
* Get last N wallet transactions.
* @param {WalletID} id
* @param {String} id
* @param {Number} limit - Max number of transactions.
* @returns {Promise}
*/
HTTPClient.prototype.getLast = function getLast(id, account, limit) {
let options = { account: account, limit: limit };
return this._get('/wallet/' + id + '/tx/last', options);
return this._get(`/wallet/${id}/tx/last`, { account, limit });
};
/**
* Get wallet transactions by timestamp range.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @param {Number} options.start - Start time.
* @param {Number} options.end - End time.
@ -568,82 +566,82 @@ HTTPClient.prototype.getLast = function getLast(id, account, limit) {
*/
HTTPClient.prototype.getRange = function getRange(id, account, options) {
options = {
let body = {
account: account,
start: options.start,
end: options.end ,
limit: options.limit,
reverse: options.reverse
};
return this._get('/wallet/' + id + '/tx/range', options);
return this._get(`/wallet/${id}/tx/range`, body);
};
/**
* Get transaction (only possible if the transaction
* is available in the wallet history).
* @param {WalletID} id
* @param {String} id
* @param {Hash} hash
* @returns {Promise}
*/
HTTPClient.prototype.getWalletTX = function getWalletTX(id, hash) {
return this._get('/wallet/' + id + '/tx/' + hash);
return this._get(`/wallet/${id}/tx/${hash}`);
};
/**
* Get wallet blocks.
* @param {WalletID} id
* @param {String} id
* @param {Number} height
* @returns {Promise}
*/
HTTPClient.prototype.getWalletBlocks = function getWalletBlocks(id) {
return this._get('/wallet/' + id + '/block');
return this._get(`/wallet/${id}/block`);
};
/**
* Get wallet block.
* @param {WalletID} id
* @param {String} id
* @param {Number} height
* @returns {Promise}
*/
HTTPClient.prototype.getWalletBlock = function getWalletBlock(id, height) {
return this._get('/wallet/' + id + '/block/' + height);
return this._get(`/wallet/${id}/block/${height}`);
};
/**
* Get unspent coin (only possible if the transaction
* is available in the wallet history).
* @param {WalletID} id
* @param {String} id
* @param {Hash} hash
* @param {Number} index
* @returns {Promise}
*/
HTTPClient.prototype.getWalletCoin = function getWalletCoin(id, account, hash, index) {
let path = '/wallet/' + id + '/coin/' + hash + '/' + index;
let options = { account: account };
return this._get(path, options);
return this._get(`/wallet/${id}/coin/${hash}/${index}`, { account });
};
/**
* Create a transaction, fill, sign, and broadcast.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @param {Base58Address} options.address
* @param {String} options.address
* @param {Amount} options.value
* @returns {Promise}
*/
HTTPClient.prototype.send = function send(id, options) {
options = Object.assign({}, options);
options.outputs = options.outputs || [];
let body = Object.assign({}, options);
if (options.rate)
options.rate = Amount.btc(options.rate);
if (!body.outputs)
body.outputs = [];
options.outputs = options.outputs.map((output) => {
if (body.rate)
body.rate = Amount.btc(body.rate);
body.outputs = body.outputs.map((output) => {
return {
value: Amount.btc(output.value),
address: output.address,
@ -651,7 +649,7 @@ HTTPClient.prototype.send = function send(id, options) {
};
});
return this._post('/wallet/' + id + '/send', options);
return this._post(`/wallet/${id}/send`, body);
};
/**
@ -661,8 +659,7 @@ HTTPClient.prototype.send = function send(id, options) {
*/
HTTPClient.prototype.retoken = async function retoken(id, passphrase) {
let options = { passphrase: passphrase };
let body = await this._post('/wallet/' + id + '/retoken', options);
let body = await this._post(`/wallet/${id}/retoken`, { passphrase });
return body.token;
};
@ -674,24 +671,27 @@ HTTPClient.prototype.retoken = async function retoken(id, passphrase) {
*/
HTTPClient.prototype.setPassphrase = function setPassphrase(id, old, new_) {
let options = { old: old, passphrase: new_ };
return this._post('/wallet/' + id + '/passphrase', options);
let body = { old: old, passphrase: new_ };
return this._post(`/wallet/${id}/passphrase`, body);
};
/**
* Create a transaction, fill.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createTX = function createTX(id, options) {
options = Object.assign({}, options);
let body = Object.assign({}, options);
if (options.rate)
options.rate = Amount.btc(options.rate);
if (!body.outputs)
body.outputs = [];
options.outputs = options.outputs.map((output) => {
if (body.rate)
body.rate = Amount.btc(body.rate);
body.outputs = body.outputs.map((output) => {
return {
value: Amount.btc(output.value),
address: output.address,
@ -699,71 +699,60 @@ HTTPClient.prototype.createTX = function createTX(id, options) {
};
});
return this._post('/wallet/' + id + '/create', options);
return this._post(`/wallet/${id}/create`, body);
};
/**
* Sign a transaction.
* @param {WalletID} id
* @param {String} id
* @param {TX} tx
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.sign = function sign(id, tx, options) {
let body;
if (!options)
options = {};
body = Object.assign({}, options);
let body = Object.assign({}, options);
body.tx = toHex(tx);
return this._post('/wallet/' + id + '/sign', body);
return this._post(`/wallet/${id}/sign`, body);
};
/**
* @param {WalletID} id
* @param {String} id
* @param {Number} now - Current time.
* @param {Number} age - Age delta (delete transactions older than `now - age`).
* @returns {Promise}
*/
HTTPClient.prototype.zapWallet = function zapWallet(id, account, age) {
let body = {
account: account,
age: age
};
return this._post('/wallet/' + id + '/zap', body);
return this._post(`/wallet/${id}/zap`, { account, age });
};
/**
* Get wallet key.
* @param {WalletID} id
* @param {Base58Address} address
* @param {String} id
* @param {String} address
* @returns {Promise}
*/
HTTPClient.prototype.getKey = function getKey(id, address) {
return this._get('/wallet/' + id + '/key/' + address);
return this._get(`/wallet/${id}/key/${address}`);
};
/**
* Get wallet key WIF dump.
* @param {WalletID} id
* @param {Base58Address} address
* @param {String} id
* @param {String} address
* @param {String?} passphrase
* @returns {Promise}
*/
HTTPClient.prototype.getWIF = function getWIF(id, address, passphrase) {
let options = { passphrase: passphrase };
return this._get('/wallet/' + id + '/wif/' + address, options);
return this._get(`/wallet/${id}/wif/${address}`, { passphrase });
};
/**
* Add a public account/purpose key to the wallet for multisig.
* @param {WalletID} id
* @param {String} id
* @param {(String|Number)?} account
* @param {Base58String} key - Account (bip44) or
* Purpose (bip45) key (can be in base58 form).
@ -771,13 +760,13 @@ HTTPClient.prototype.getWIF = function getWIF(id, address, passphrase) {
*/
HTTPClient.prototype.addSharedKey = function addSharedKey(id, account, key) {
let options = { account: account, accountKey: key };
return this._put('/wallet/' + id + '/shared-key', options);
let body = { account: account, accountKey: key };
return this._put(`/wallet/${id}/shared-key`, body);
};
/**
* Remove a public account/purpose key to the wallet for multisig.
* @param {WalletID} id
* @param {String} id
* @param {(String|Number)?} account
* @param {Base58String} key - Account (bip44) or Purpose
* (bip45) key (can be in base58 form).
@ -785,8 +774,8 @@ HTTPClient.prototype.addSharedKey = function addSharedKey(id, account, key) {
*/
HTTPClient.prototype.removeSharedKey = function removeSharedKey(id, account, key) {
let options = { account: account, accountKey: key };
return this._del('/wallet/' + id + '/shared-key', options);
let body = { account: account, accountKey: key };
return this._del(`/wallet/${id}/shared-key`, body);
};
/**
@ -798,8 +787,8 @@ HTTPClient.prototype.removeSharedKey = function removeSharedKey(id, account, key
*/
HTTPClient.prototype.importPrivate = function importPrivate(id, account, key) {
let options = { account: account, privateKey: key };
return this._post('/wallet/' + id + '/import', options);
let body = { account: account, privateKey: key };
return this._post(`/wallet/${id}/import`, body);
};
/**
@ -811,8 +800,8 @@ HTTPClient.prototype.importPrivate = function importPrivate(id, account, key) {
*/
HTTPClient.prototype.importPublic = function importPublic(id, account, key) {
let options = { account: account, publicKey: key };
return this._post('/wallet/' + id + '/import', options);
let body = { account: account, publicKey: key };
return this._post(`/wallet/${id}/import`, body);
};
/**
@ -824,8 +813,7 @@ HTTPClient.prototype.importPublic = function importPublic(id, account, key) {
*/
HTTPClient.prototype.importAddress = function importAddress(id, account, address) {
let options = { account: account, address: address };
return this._post('/wallet/' + id + '/import', options);
return this._post(`/wallet/${id}/import`, { account, address });
};
/**
@ -837,8 +825,7 @@ HTTPClient.prototype.importAddress = function importAddress(id, account, address
*/
HTTPClient.prototype.lockCoin = function lockCoin(id, hash, index) {
let options = { hash: hash, index: index };
return this._put('/wallet/' + id + '/coin/locked', options);
return this._put(`/wallet/${id}/coin/locked`, { hash, index });
};
/**
@ -850,8 +837,7 @@ HTTPClient.prototype.lockCoin = function lockCoin(id, hash, index) {
*/
HTTPClient.prototype.unlockCoin = function unlockCoin(id, hash, index) {
let options = { hash: hash, index: index };
return this._del('/wallet/' + id + '/coin/locked', options);
return this._del(`/wallet/${id}/coin/locked`, { hash, index });
};
/**
@ -861,7 +847,7 @@ HTTPClient.prototype.unlockCoin = function unlockCoin(id, hash, index) {
*/
HTTPClient.prototype.getLocked = function getLocked(id) {
return this._get('/wallet/' + id + '/coin/locked');
return this._get(`/wallet/${id}/coin/locked`);
};
/**
@ -871,7 +857,7 @@ HTTPClient.prototype.getLocked = function getLocked(id) {
*/
HTTPClient.prototype.lock = function lock(id) {
return this._post('/wallet/' + id + '/lock', {});
return this._post(`/wallet/${id}/lock`, {});
};
/**
@ -883,8 +869,7 @@ HTTPClient.prototype.lock = function lock(id) {
*/
HTTPClient.prototype.unlock = function unlock(id, passphrase, timeout) {
let options = { passphrase: passphrase, timeout: timeout };
return this._post('/wallet/' + id + '/unlock', options);
return this._post(`/wallet/${id}/unlock`, { passphrase, timeout });
};
/**
@ -893,117 +878,101 @@ HTTPClient.prototype.unlock = function unlock(id, passphrase, timeout) {
*/
HTTPClient.prototype.resendWallet = function resendWallet(id) {
return this._post('/wallet/' + id + '/resend', {});
return this._post(`/wallet/${id}/resend`, {});
};
/**
* Get wallet accounts.
* @param {WalletID} id
* @param {String} id
* @returns {Promise} - Returns Array.
*/
HTTPClient.prototype.getAccounts = function getAccounts(id) {
let path = '/wallet/' + id + '/account';
return this._get(path);
return this._get(`/wallet/${id}/account`);
};
/**
* Get wallet master key.
* @param {WalletID} id
* @param {String} id
* @returns {Promise}
*/
HTTPClient.prototype.getMaster = function getMaster(id) {
let path = '/wallet/' + id + '/master';
return this._get(path);
return this._get(`/wallet/${id}/master`);
};
/**
* Get wallet account.
* @param {WalletID} id
* @param {String} id
* @param {String} account
* @returns {Promise}
*/
HTTPClient.prototype.getAccount = function getAccount(id, account) {
let path = '/wallet/' + id + '/account/' + account;
return this._get(path);
return this._get(`/wallet/${id}/account/${account}`);
};
/**
* Create account.
* @param {WalletID} id
* @param {String} id
* @param {String} name
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createAccount = function createAccount(id, name, options) {
let path = '/wallet/' + id + '/account/' + name;
return this._put(path, options || {});
return this._put(`/wallet/${id}/account/${name}`, options || {});
};
/**
* Create address.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createAddress = function createAddress(id, options) {
let path;
if (!options)
options = {};
if (typeof options === 'string')
options = { account: options };
path = '/wallet/' + id + '/address';
return this._post(path, options);
return this._post(`/wallet/${id}/address`, options);
};
/**
* Create change address.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createChange = function createChange(id, options) {
let path;
if (!options)
options = {};
if (typeof options === 'string')
options = { account: options };
path = '/wallet/' + id + '/change';
return this._post(path, options);
return this._post(`/wallet/${id}/change`, options);
};
/**
* Create nested address.
* @param {WalletID} id
* @param {String} id
* @param {Object} options
* @returns {Promise}
*/
HTTPClient.prototype.createNested = function createNested(id, options) {
let path;
if (!options)
options = {};
if (typeof options === 'string')
options = { account: options };
path = '/wallet/' + id + '/nested';
return this._post(path, options);
return this._post(`/wallet/${id}/nested`, options);
};
/*

View File

@ -31,7 +31,7 @@ function RPCClient(options) {
this.options = options;
this.network = Network.get(options.network);
this.uri = options.uri || 'http://localhost:' + this.network.rpcPort;
this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
this.apiKey = options.apiKey;
this.id = 0;
}
@ -64,7 +64,7 @@ RPCClient.prototype.execute = async function execute(method, params) {
throw new RPCError('Unauthorized (bad API key).', -1);
if (res.statusCode !== 200)
throw new Error('Status code: ' + res.statusCode);
throw new Error(`Status code: ${res.statusCode}.`);
if (res.type !== 'json')
throw new Error('Bad response (wrong content-type).');

View File

@ -11,7 +11,7 @@ const IOClient = require('socket.io-client');
const Network = require('../protocol/network');
const AsyncObject = require('../utils/asyncobject');
const TX = require('../primitives/tx');
const BlockMeta = require('./records').BlockMeta;
const {BlockMeta} = require('./records');
const Headers = require('../primitives/headers');
const Amount = require('../btc/amount');
const util = require('../utils/util');
@ -21,8 +21,7 @@ const BufferReader = require('../utils/reader');
* Bcoin HTTP client.
* @alias module:wallet.WalletClient
* @constructor
* @param {String} uri
* @param {Object?} options
* @param {Object|String} options
*/
function WalletClient(options) {
@ -40,7 +39,7 @@ function WalletClient(options) {
this.options = options;
this.network = Network.get(options.network);
this.uri = options.uri || 'http://localhost:' + this.network.rpcPort;
this.uri = options.uri || `http://localhost:${this.network.rpcPort}`;
this.apiKey = options.apiKey;
this.socket = null;
@ -235,8 +234,7 @@ WalletClient.prototype.getEntry = function getEntry(block) {
WalletClient.prototype.send = function send(tx) {
return new Promise((resolve, reject) => {
let raw = tx.toRaw();
this.socket.emit('send', raw, wrap(resolve, reject));
this.socket.emit('send', tx.toRaw(), wrap(resolve, reject));
});
};
@ -248,8 +246,7 @@ WalletClient.prototype.send = function send(tx) {
WalletClient.prototype.setFilter = function setFilter(filter) {
return new Promise((resolve, reject) => {
let raw = filter.toRaw();
this.socket.emit('set filter', raw, wrap(resolve, reject));
this.socket.emit('set filter', filter.toRaw(), wrap(resolve, reject));
});
};
@ -260,14 +257,9 @@ WalletClient.prototype.setFilter = function setFilter(filter) {
*/
WalletClient.prototype.addFilter = function addFilter(chunks) {
let out = [];
if (!Array.isArray(chunks))
chunks = [chunks];
for (let chunk of chunks)
out.push(chunk);
return new Promise((resolve, reject) => {
this.socket.emit('add filter', out, wrap(resolve, reject));
});
@ -356,7 +348,7 @@ function BlockResult(entry, txs) {
}
function wrap(resolve, reject, parse) {
return (err, result) => {
return function(err, result) {
if (err) {
reject(new Error(err.message));
return;