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

View File

@ -31,7 +31,7 @@ function RPCClient(options) {
this.options = options; this.options = options;
this.network = Network.get(options.network); 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.apiKey = options.apiKey;
this.id = 0; this.id = 0;
} }
@ -64,7 +64,7 @@ RPCClient.prototype.execute = async function execute(method, params) {
throw new RPCError('Unauthorized (bad API key).', -1); throw new RPCError('Unauthorized (bad API key).', -1);
if (res.statusCode !== 200) if (res.statusCode !== 200)
throw new Error('Status code: ' + res.statusCode); throw new Error(`Status code: ${res.statusCode}.`);
if (res.type !== 'json') if (res.type !== 'json')
throw new Error('Bad response (wrong content-type).'); 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 Network = require('../protocol/network');
const AsyncObject = require('../utils/asyncobject'); const AsyncObject = require('../utils/asyncobject');
const TX = require('../primitives/tx'); const TX = require('../primitives/tx');
const BlockMeta = require('./records').BlockMeta; const {BlockMeta} = require('./records');
const Headers = require('../primitives/headers'); const Headers = require('../primitives/headers');
const Amount = require('../btc/amount'); const Amount = require('../btc/amount');
const util = require('../utils/util'); const util = require('../utils/util');
@ -21,8 +21,7 @@ const BufferReader = require('../utils/reader');
* Bcoin HTTP client. * Bcoin HTTP client.
* @alias module:wallet.WalletClient * @alias module:wallet.WalletClient
* @constructor * @constructor
* @param {String} uri * @param {Object|String} options
* @param {Object?} options
*/ */
function WalletClient(options) { function WalletClient(options) {
@ -40,7 +39,7 @@ function WalletClient(options) {
this.options = options; this.options = options;
this.network = Network.get(options.network); 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.apiKey = options.apiKey;
this.socket = null; this.socket = null;
@ -235,8 +234,7 @@ WalletClient.prototype.getEntry = function getEntry(block) {
WalletClient.prototype.send = function send(tx) { WalletClient.prototype.send = function send(tx) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let raw = tx.toRaw(); this.socket.emit('send', tx.toRaw(), wrap(resolve, reject));
this.socket.emit('send', raw, wrap(resolve, reject));
}); });
}; };
@ -248,8 +246,7 @@ WalletClient.prototype.send = function send(tx) {
WalletClient.prototype.setFilter = function setFilter(filter) { WalletClient.prototype.setFilter = function setFilter(filter) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let raw = filter.toRaw(); this.socket.emit('set filter', filter.toRaw(), wrap(resolve, reject));
this.socket.emit('set filter', raw, wrap(resolve, reject));
}); });
}; };
@ -260,14 +257,9 @@ WalletClient.prototype.setFilter = function setFilter(filter) {
*/ */
WalletClient.prototype.addFilter = function addFilter(chunks) { WalletClient.prototype.addFilter = function addFilter(chunks) {
let out = [];
if (!Array.isArray(chunks)) if (!Array.isArray(chunks))
chunks = [chunks]; chunks = [chunks];
for (let chunk of chunks)
out.push(chunk);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.socket.emit('add filter', out, wrap(resolve, reject)); this.socket.emit('add filter', out, wrap(resolve, reject));
}); });
@ -356,7 +348,7 @@ function BlockResult(entry, txs) {
} }
function wrap(resolve, reject, parse) { function wrap(resolve, reject, parse) {
return (err, result) => { return function(err, result) {
if (err) { if (err) {
reject(new Error(err.message)); reject(new Error(err.message));
return; return;