From 4eb64b5e72c211140d96f9735b456c681aadadf7 Mon Sep 17 00:00:00 2001 From: Elliot Lee Date: Thu, 12 Nov 2020 11:49:53 -0800 Subject: [PATCH] style: yarn format (run prettier) (#1327) --- .prettierrc | 2 +- src/api.ts | 4 +- src/broadcast.ts | 24 ++--- src/common/connection.ts | 16 ++-- src/common/hashes/index.ts | 9 +- src/common/rangeset.ts | 8 +- src/common/schema-validator.ts | 14 +-- src/common/serverinfo.ts | 2 +- src/common/utils.ts | 2 +- src/common/wswrapper.ts | 4 +- src/ledger/balance-sheet.ts | 4 +- src/ledger/balances.ts | 4 +- src/ledger/orderbook.ts | 4 +- src/ledger/orders.ts | 4 +- src/ledger/parse/pathfind.ts | 6 +- src/ledger/parse/settings.ts | 2 +- src/ledger/parse/utils.ts | 8 +- src/ledger/pathfind.ts | 14 +-- src/ledger/transaction.ts | 8 +- src/ledger/transactions.ts | 10 +- src/ledger/trustlines.ts | 4 +- src/ledger/utils.ts | 10 +- src/offline/ledgerhash.ts | 4 +- src/transaction/combine.ts | 2 +- src/transaction/payment.ts | 7 +- src/transaction/settings.ts | 4 +- src/transaction/sign.ts | 2 +- src/transaction/utils.ts | 17 ++-- test/api/dropsToXrp/index.ts | 20 ++-- test/api/formatBidsAndAsks/index.ts | 16 ++-- test/api/generateAddress/index.ts | 36 ++++--- test/api/generateXAddress/index.ts | 38 +++++--- test/api/getBalances/index.ts | 4 +- test/api/getLedger/index.ts | 16 ++-- test/api/getOrderbook/index.ts | 18 ++-- test/api/getPaths/index.ts | 26 ++--- test/api/getTransactions/index.ts | 10 +- test/api/preparePayment/index.ts | 27 +++--- test/api/prepareTransaction/index.ts | 4 +- test/api/sign/index.ts | 5 +- test/api/xrpToDrops/index.ts | 20 ++-- test/backoff-test.ts | 10 +- test/broadcast-api-test.ts | 12 +-- test/connection-test.ts | 138 +++++++++++++-------------- test/hashes-test.ts | 34 +++---- test/integration/broadcast-test.ts | 4 +- test/integration/connection-test.ts | 6 +- test/integration/integration-test.ts | 128 +++++++++++++------------ test/mock-rippled.ts | 60 ++++++------ test/rangeset-test.ts | 16 ++-- test/ripple-api-test-private.ts | 40 ++++---- test/ripple-api-test.ts | 10 +- test/setup-api-web.ts | 4 +- test/setup-api.ts | 10 +- test/shamap-test.ts | 6 +- test/utils.ts | 10 +- 56 files changed, 480 insertions(+), 447 deletions(-) diff --git a/.prettierrc b/.prettierrc index 66e6e819..7f0aa514 100644 --- a/.prettierrc +++ b/.prettierrc @@ -7,4 +7,4 @@ "trailingComma": "none", "quoteProps": "consistent", "bracketSpacing": false - } \ No newline at end of file +} diff --git a/src/api.ts b/src/api.ts index fdd98e21..f33bd826 100644 --- a/src/api.ts +++ b/src/api.ts @@ -155,7 +155,7 @@ class RippleAPI extends EventEmitter { const serverURL = options.server if (serverURL !== undefined) { this.connection = new Connection(serverURL, options) - this.connection.on('ledgerClosed', message => { + this.connection.on('ledgerClosed', (message) => { this.emit('ledger', formatLedgerClose(message)) }) this.connection.on('error', (errorCode, errorMessage, data) => { @@ -164,7 +164,7 @@ class RippleAPI extends EventEmitter { this.connection.on('connected', () => { this.emit('connected') }) - this.connection.on('disconnected', code => { + this.connection.on('disconnected', (code) => { let finalCode = code // 1005: This is a backwards-compatible fix for this change in the ws library: https://github.com/websockets/ws/issues/1257 // 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close diff --git a/src/broadcast.ts b/src/broadcast.ts index 8e1e8e24..0ed43bb8 100644 --- a/src/broadcast.ts +++ b/src/broadcast.ts @@ -9,38 +9,38 @@ class RippleAPIBroadcast extends RippleAPI { super(options) const apis: RippleAPI[] = servers.map( - server => new RippleAPI(_.assign({}, options, {server})) + (server) => new RippleAPI(_.assign({}, options, {server})) ) // exposed for testing this._apis = apis - this.getMethodNames().forEach(name => { - this[name] = function() { + this.getMethodNames().forEach((name) => { + this[name] = function () { // eslint-disable-line no-loop-func - return Promise.race(apis.map(api => api[name](...arguments))) + return Promise.race(apis.map((api) => api[name](...arguments))) } }) // connection methods must be overridden to apply to all api instances - this.connect = async function() { - await Promise.all(apis.map(api => api.connect())) + this.connect = async function () { + await Promise.all(apis.map((api) => api.connect())) } - this.disconnect = async function() { - await Promise.all(apis.map(api => api.disconnect())) + this.disconnect = async function () { + await Promise.all(apis.map((api) => api.disconnect())) } - this.isConnected = function() { - return apis.map(api => api.isConnected()).every(Boolean) + this.isConnected = function () { + return apis.map((api) => api.isConnected()).every(Boolean) } // synchronous methods are all passed directly to the first api instance const defaultAPI = apis[0] const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash'] - syncMethods.forEach(name => { + syncMethods.forEach((name) => { this[name] = defaultAPI[name].bind(defaultAPI) }) - apis.forEach(api => { + apis.forEach((api) => { api.on('ledger', this.onLedgerEvent.bind(this)) api.on('error', (errorCode, errorMessage, data) => this.emit('error', errorCode, errorMessage, data) diff --git a/src/common/connection.ts b/src/common/connection.ts index d392184f..b948e1d6 100644 --- a/src/common/connection.ts +++ b/src/common/connection.ts @@ -120,7 +120,7 @@ function createWebSocket(url: string, config: ConnectionOptions): WebSocket { */ function websocketSendAsync(ws: WebSocket, message: string) { return new Promise((resolve, reject) => { - ws.send(message, undefined, error => { + ws.send(message, undefined, (error) => { if (error) { reject(new DisconnectedError(error.message, error)) } else { @@ -390,7 +390,7 @@ export class Connection extends EventEmitter { */ private _heartbeat = () => { return this.request({command: 'ping'}).catch(() => { - this.reconnect().catch(error => { + this.reconnect().catch((error) => { this.emit('error', 'reconnect', error.message, error) }) }) @@ -504,11 +504,11 @@ export class Connection extends EventEmitter { clearTimeout(connectionTimeoutID) // Add new, long-term connected listeners for messages and errors this._ws.on('message', (message: string) => this._onMessage(message)) - this._ws.on('error', error => + this._ws.on('error', (error) => this.emit('error', 'websocket', error.message, error) ) // Handle a closed connection: reconnect if it was unexpected - this._ws.once('close', code => { + this._ws.once('close', (code) => { this._clearHeartbeatInterval() this._requestManager.rejectAll( new DisconnectedError('websocket was closed') @@ -524,7 +524,7 @@ export class Connection extends EventEmitter { // Start the reconnect timeout, but set it to `this._reconnectTimeoutID` // so that we can cancel one in-progress on disconnect. this._reconnectTimeoutID = setTimeout(() => { - this.reconnect().catch(error => { + this.reconnect().catch((error) => { this.emit('error', 'reconnect', error.message, error) }) }, retryTimeout) @@ -558,8 +558,8 @@ export class Connection extends EventEmitter { if (this._state === WebSocket.CLOSED || !this._ws) { return Promise.resolve(undefined) } - return new Promise(resolve => { - this._ws.once('close', code => resolve(code)) + return new Promise((resolve) => { + this._ws.once('close', (code) => resolve(code)) // Connection already has a disconnect handler for the disconnect logic. // Just close the websocket manually (with our "intentional" code) to // trigger that. @@ -635,7 +635,7 @@ export class Connection extends EventEmitter { timeout || this._config.timeout ) this._trace('send', message) - websocketSendAsync(this._ws, message).catch(error => { + websocketSendAsync(this._ws, message).catch((error) => { this._requestManager.reject(id, error) }) diff --git a/src/common/hashes/index.ts b/src/common/hashes/index.ts index 2f493045..b035f6c9 100644 --- a/src/common/hashes/index.ts +++ b/src/common/hashes/index.ts @@ -36,10 +36,7 @@ const addressToHex = (address: string): string => { const currencyToHex = (currency: string): string => { if (currency.length === 3) { - const bytes = new Array(20 + 1) - .join('0') - .split('') - .map(parseFloat) + const bytes = new Array(20 + 1).join('0').split('').map(parseFloat) bytes[12] = currency.charCodeAt(0) & 0xff bytes[13] = currency.charCodeAt(1) & 0xff bytes[14] = currency.charCodeAt(2) & 0xff @@ -163,7 +160,7 @@ export const computeTrustlineHash = ( export const computeTransactionTreeHash = (transactions: any[]): string => { const shamap = new SHAMap() - transactions.forEach(txJSON => { + transactions.forEach((txJSON) => { const txBlobHex = encode(txJSON) const metaHex = encode(txJSON.metaData) const txHash = computeBinaryTransactionHash(txBlobHex) @@ -177,7 +174,7 @@ export const computeTransactionTreeHash = (transactions: any[]): string => { export const computeStateTreeHash = (entries: any[]): string => { const shamap = new SHAMap() - entries.forEach(ledgerEntry => { + entries.forEach((ledgerEntry) => { const data = encode(ledgerEntry) shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE) }) diff --git a/src/common/rangeset.ts b/src/common/rangeset.ts index d4ec2334..3a8a2bb2 100644 --- a/src/common/rangeset.ts +++ b/src/common/rangeset.ts @@ -5,7 +5,7 @@ type Interval = [number, number] function mergeIntervals(intervals: Interval[]): Interval[] { const stack: Interval[] = [[-Infinity, -Infinity]] - _.sortBy(intervals, x => x[0]).forEach(interval => { + _.sortBy(intervals, (x) => x[0]).forEach((interval) => { const lastInterval: Interval = stack.pop()! if (interval[0] <= lastInterval[1] + 1) { stack.push([lastInterval[0], Math.max(interval[1], lastInterval[1])]) @@ -30,7 +30,7 @@ class RangeSet { serialize() { return this.ranges - .map(range => range[0].toString() + '-' + range[1].toString()) + .map((range) => range[0].toString() + '-' + range[1].toString()) .join(',') } @@ -45,14 +45,14 @@ class RangeSet { parseAndAddRanges(rangesString: string) { const rangeStrings = rangesString.split(',') - _.forEach(rangeStrings, rangeString => { + _.forEach(rangeStrings, (rangeString) => { const range = rangeString.split('-').map(Number) this.addRange(range[0], range.length === 1 ? range[0] : range[1]) }) } containsRange(start: number, end: number) { - return _.some(this.ranges, range => range[0] <= start && range[1] >= end) + return _.some(this.ranges, (range) => range[0] <= start && range[1] >= end) } containsValue(value: number) { diff --git a/src/common/schema-validator.ts b/src/common/schema-validator.ts index 20a6a93b..d761186b 100644 --- a/src/common/schema-validator.ts +++ b/src/common/schema-validator.ts @@ -123,8 +123,8 @@ function loadSchemas() { require('./schemas/input/verify-payment-channel-claim.json'), require('./schemas/input/combine.json') ] - const titles = schemas.map(schema => schema.title) - const duplicates = _.keys(_.pickBy(_.countBy(titles), count => count > 1)) + const titles = schemas.map((schema) => schema.title) + const duplicates = _.keys(_.pickBy(_.countBy(titles), (count) => count > 1)) assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates) const validator = new Validator() // Register custom format validators that ignore undefined instances @@ -132,7 +132,7 @@ function loadSchemas() { // (optional) property // This relies on "format": "xAddress" in `x-address.json`! - validator.customFormats.xAddress = function(instance) { + validator.customFormats.xAddress = function (instance) { if (instance === undefined) { return true } @@ -140,14 +140,14 @@ function loadSchemas() { } // This relies on "format": "classicAddress" in `classic-address.json`! - validator.customFormats.classicAddress = function(instance) { + validator.customFormats.classicAddress = function (instance) { if (instance === undefined) { return true } return isValidAddress(instance) } - validator.customFormats.secret = function(instance) { + validator.customFormats.secret = function (instance) { if (instance === undefined) { return true } @@ -155,7 +155,9 @@ function loadSchemas() { } // Register under the root URI '/' - _.forEach(schemas, schema => validator.addSchema(schema, '/' + schema.title)) + _.forEach(schemas, (schema) => + validator.addSchema(schema, '/' + schema.title) + ) return validator } diff --git a/src/common/serverinfo.ts b/src/common/serverinfo.ts index fde114ec..ab8a3670 100644 --- a/src/common/serverinfo.ts +++ b/src/common/serverinfo.ts @@ -41,7 +41,7 @@ function renameKeys(object, mapping) { } function getServerInfo(this: RippleAPI): Promise { - return this.request('server_info').then(response => { + return this.request('server_info').then((response) => { const info = convertKeysFromSnakeCaseToCamelCase(response.info) renameKeys(info, {hostid: 'hostID'}) if (info.validatedLedger) { diff --git a/src/common/utils.ts b/src/common/utils.ts index c565416e..c3a23caa 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -134,7 +134,7 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any { // taking this out of function leads to error in PhantomJS const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g if (FINDSNAKE.test(key)) { - newKey = key.replace(FINDSNAKE, r => r[0] + r[2].toUpperCase()) + newKey = key.replace(FINDSNAKE, (r) => r[0] + r[2].toUpperCase()) } result[newKey] = convertKeysFromSnakeCaseToCamelCase(value) return result diff --git a/src/common/wswrapper.ts b/src/common/wswrapper.ts index 985a079e..c6cd1a53 100644 --- a/src/common/wswrapper.ts +++ b/src/common/wswrapper.ts @@ -37,11 +37,11 @@ class WSWrapper extends EventEmitter { this.emit('open') } - this._ws.onerror = error => { + this._ws.onerror = (error) => { this.emit('error', error) } - this._ws.onmessage = message => { + this._ws.onmessage = (message) => { this.emit('message', message.data) } } diff --git a/src/ledger/balance-sheet.ts b/src/ledger/balance-sheet.ts index 0462293a..87961bc3 100644 --- a/src/ledger/balance-sheet.ts +++ b/src/ledger/balance-sheet.ts @@ -24,7 +24,7 @@ function formatBalanceSheet(balanceSheet): GetBalanceSheet { if (!_.isUndefined(balanceSheet.balances)) { result.balances = [] _.forEach(balanceSheet.balances, (balances, counterparty) => { - _.forEach(balances, balance => { + _.forEach(balances, (balance) => { result.balances.push(Object.assign({counterparty}, balance)) }) }) @@ -32,7 +32,7 @@ function formatBalanceSheet(balanceSheet): GetBalanceSheet { if (!_.isUndefined(balanceSheet.assets)) { result.assets = [] _.forEach(balanceSheet.assets, (assets, counterparty) => { - _.forEach(assets, balance => { + _.forEach(assets, (balance) => { result.assets.push(Object.assign({counterparty}, balance)) }) }) diff --git a/src/ledger/balances.ts b/src/ledger/balances.ts index a70ec151..96325224 100644 --- a/src/ledger/balances.ts +++ b/src/ledger/balances.ts @@ -67,11 +67,11 @@ function getBalances( getLedgerVersionHelper( this.connection, options.ledgerVersion - ).then(ledgerVersion => + ).then((ledgerVersion) => utils.getXRPBalance(this.connection, address, ledgerVersion) ), this.getTrustlines(address, options) - ]).then(results => + ]).then((results) => formatBalances(options, {xrp: results[0], trustlines: results[1]}) ) } diff --git a/src/ledger/orderbook.ts b/src/ledger/orderbook.ts index 98648bda..d15d27d4 100644 --- a/src/ledger/orderbook.ts +++ b/src/ledger/orderbook.ts @@ -116,11 +116,11 @@ export async function getOrderbook( // 3. Return Formatted Response const directOffers = _.flatMap( directOfferResults, - directOfferResult => directOfferResult.offers + (directOfferResult) => directOfferResult.offers ) const reverseOffers = _.flatMap( reverseOfferResults, - reverseOfferResult => reverseOfferResult.offers + (reverseOfferResult) => reverseOfferResult.offers ) return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers]) } diff --git a/src/ledger/orders.ts b/src/ledger/orders.ts index b849b1ea..717355a8 100644 --- a/src/ledger/orders.ts +++ b/src/ledger/orders.ts @@ -15,12 +15,12 @@ function formatResponse( ): FormattedAccountOrder[] { let orders: FormattedAccountOrder[] = [] for (const response of responses) { - const offers = response.offers.map(offer => { + const offers = response.offers.map((offer) => { return parseAccountOrder(address, offer) }) orders = orders.concat(offers) } - return _.sortBy(orders, order => order.properties.sequence) + return _.sortBy(orders, (order) => order.properties.sequence) } export default async function getOrders( diff --git a/src/ledger/parse/pathfind.ts b/src/ledger/parse/pathfind.ts index 88d08e6e..35de6197 100644 --- a/src/ledger/parse/pathfind.ts +++ b/src/ledger/parse/pathfind.ts @@ -4,8 +4,8 @@ import {Amount, RippledAmount} from '../../common/types/objects' import {Path, GetPaths, RippledPathsResponse} from '../pathfind-types' function parsePaths(paths) { - return paths.map(steps => - steps.map(step => _.omit(step, ['type', 'type_hex'])) + return paths.map((steps) => + steps.map((step) => _.omit(step, ['type', 'type_hex'])) ) } @@ -58,7 +58,7 @@ function parsePathfind(pathfindResult: RippledPathsResponse): GetPaths { const sourceAddress = pathfindResult.source_account const destinationAddress = pathfindResult.destination_account const destinationAmount = pathfindResult.destination_amount - return pathfindResult.alternatives.map(alt => + return pathfindResult.alternatives.map((alt) => parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt) ) } diff --git a/src/ledger/parse/settings.ts b/src/ledger/parse/settings.ts index b23eaf88..94a2a2da 100644 --- a/src/ledger/parse/settings.ts +++ b/src/ledger/parse/settings.ts @@ -6,7 +6,7 @@ import parseFields from './fields' function getAccountRootModifiedNode(tx: any) { const modifiedNodes = tx.meta.AffectedNodes.filter( - node => node.ModifiedNode.LedgerEntryType === 'AccountRoot' + (node) => node.ModifiedNode.LedgerEntryType === 'AccountRoot' ) assert.ok(modifiedNodes.length === 1) return modifiedNodes[0].ModifiedNode diff --git a/src/ledger/parse/utils.ts b/src/ledger/parse/utils.ts index e450aa4b..83a9f42f 100644 --- a/src/ledger/parse/utils.ts +++ b/src/ledger/parse/utils.ts @@ -42,14 +42,14 @@ function removeEmptyCounterparty(amount) { } function removeEmptyCounterpartyInBalanceChanges(balanceChanges) { - _.forEach(balanceChanges, changes => { + _.forEach(balanceChanges, (changes) => { _.forEach(changes, removeEmptyCounterparty) }) } function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) { - _.forEach(orderbookChanges, changes => { - _.forEach(changes, change => { + _.forEach(orderbookChanges, (changes) => { + _.forEach(changes, (change) => { _.forEach(change, removeEmptyCounterparty) }) }) @@ -132,7 +132,7 @@ function parseMemos(tx: any): Array | undefined { if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) { return undefined } - return tx.Memos.map(m => { + return tx.Memos.map((m) => { return common.removeUndefined({ type: m.Memo.parsed_memo_type || hexToString(m.Memo.MemoType), format: m.Memo.parsed_memo_format || hexToString(m.Memo.MemoFormat), diff --git a/src/ledger/pathfind.ts b/src/ledger/pathfind.ts index 36ee558c..3a0621aa 100644 --- a/src/ledger/pathfind.ts +++ b/src/ledger/pathfind.ts @@ -62,7 +62,7 @@ function requestPathFind( request.destination_amount.issuer = request.destination_account } if (pathfind.source.currencies && pathfind.source.currencies.length > 0) { - request.source_currencies = pathfind.source.currencies.map(amount => + request.source_currencies = pathfind.source.currencies.map((amount) => renameCounterpartyToIssuer(amount) ) } @@ -79,7 +79,7 @@ function requestPathFind( } } - return connection.request(request).then(paths => addParams(request, paths)) + return connection.request(request).then((paths) => addParams(request, paths)) } function addDirectXrpPath( @@ -116,7 +116,7 @@ function conditionallyAddDirectXRPPath( ) { return Promise.resolve(paths) } - return getXRPBalance(connection, address, undefined).then(xrpBalance => + return getXRPBalance(connection, address, undefined).then((xrpBalance) => addDirectXrpPath(paths, xrpBalance) ) } @@ -130,7 +130,7 @@ function filterSourceFundsLowPaths( pathfind.destination.amount.value === undefined && paths.alternatives ) { - paths.alternatives = _.filter(paths.alternatives, alt => { + paths.alternatives = _.filter(paths.alternatives, (alt) => { if (!alt.source_amount) { return false } @@ -191,11 +191,11 @@ function getPaths(this: RippleAPI, pathfind: PathFind): Promise { const address = pathfind.source.address return requestPathFind(this.connection, pathfind) - .then(paths => + .then((paths) => conditionallyAddDirectXRPPath(this.connection, address, paths) ) - .then(paths => filterSourceFundsLowPaths(pathfind, paths)) - .then(paths => formatResponse(pathfind, paths)) + .then((paths) => filterSourceFundsLowPaths(pathfind, paths)) + .then((paths) => formatResponse(pathfind, paths)) } export default getPaths diff --git a/src/ledger/transaction.ts b/src/ledger/transaction.ts index 46ae5133..43ca58b4 100644 --- a/src/ledger/transaction.ts +++ b/src/ledger/transaction.ts @@ -48,13 +48,13 @@ function attachTransactionDate( return connection .request(request) - .then(data => { + .then((data) => { if (typeof data.ledger.close_time === 'number') { return _.assign({date: data.ledger.close_time}, tx) } throw new errors.UnexpectedError('Ledger missing close_time') }) - .catch(error => { + .catch((error) => { if (error instanceof errors.UnexpectedError) { throw error } @@ -95,11 +95,11 @@ function convertError( options.minLedgerVersion, options.maxLedgerVersion ) - .then(hasCompleteLedgerRange => { + .then((hasCompleteLedgerRange) => { if (!hasCompleteLedgerRange) { return utils .isPendingLedgerVersion(connection, options.maxLedgerVersion) - .then(isPendingLedgerVersion => { + .then((isPendingLedgerVersion) => { return isPendingLedgerVersion ? new errors.PendingLedgerVersionError() : new errors.MissingLedgerHistoryError() diff --git a/src/ledger/transactions.ts b/src/ledger/transactions.ts index f660f88d..7cda0725 100644 --- a/src/ledger/transactions.ts +++ b/src/ledger/transactions.ts @@ -101,12 +101,12 @@ function formatPartialResponse( options: TransactionsOptions, data ) { - const parse = tx => + const parse = (tx) => parseAccountTxTransaction(tx, options.includeRawTransactions) return { marker: data.marker, results: data.transactions - .filter(tx => tx.validated) + .filter((tx) => tx.validated) .map(parse) .filter(_.partial(transactionFilter, address, options)) .filter(_.partial(orderFilter, options)) @@ -135,7 +135,7 @@ function getAccountTx( return connection .request(request) - .then(response => formatPartialResponse(address, options, response)) + .then((response) => formatPartialResponse(address, options, response)) } function checkForLedgerGaps( @@ -158,7 +158,7 @@ function checkForLedgerGaps( return utils .hasCompleteLedgerRange(connection, minLedgerVersion, maxLedgerVersion) - .then(hasCompleteLedgerRange => { + .then((hasCompleteLedgerRange) => { if (!hasCompleteLedgerRange) { throw new errors.MissingLedgerHistoryError() } @@ -204,7 +204,7 @@ function getTransactions( const defaults = {maxLedgerVersion: -1} if (options.start) { - return getTransaction.call(this, options.start).then(tx => { + return getTransaction.call(this, options.start).then((tx) => { const ledgerVersion = tx.outcome.ledgerVersion const bound = options.earliestFirst ? {minLedgerVersion: ledgerVersion} diff --git a/src/ledger/trustlines.ts b/src/ledger/trustlines.ts index 3c39a42b..310dd4fe 100644 --- a/src/ledger/trustlines.ts +++ b/src/ledger/trustlines.ts @@ -36,8 +36,8 @@ async function getTrustlines( peer: options.counterparty }) // 3. Return Formatted Response - const trustlines = _.flatMap(responses, response => response.lines) - return trustlines.map(parseAccountTrustline).filter(trustline => { + const trustlines = _.flatMap(responses, (response) => response.lines) + return trustlines.map(parseAccountTrustline).filter((trustline) => { return currencyFilter(options.currency || null, trustline) }) } diff --git a/src/ledger/utils.ts b/src/ledger/utils.ts index 204b2240..a1904602 100644 --- a/src/ledger/utils.ts +++ b/src/ledger/utils.ts @@ -30,7 +30,7 @@ function getXRPBalance( } return connection .request(request) - .then(data => common.dropsToXrp(data.account_data.Balance)) + .then((data) => common.dropsToXrp(data.account_data.Balance)) } // If the marker is omitted from a response, you have reached the end @@ -39,10 +39,10 @@ function getRecursiveRecur( marker: string | undefined, limit: number ): Promise> { - return getter(marker, limit).then(data => { + return getter(marker, limit).then((data) => { const remaining = limit - data.results.length if (remaining > 0 && data.marker !== undefined) { - return getRecursiveRecur(getter, data.marker, remaining).then(results => + return getRecursiveRecur(getter, data.marker, remaining).then((results) => data.results.concat(results) ) } @@ -118,7 +118,7 @@ function isPendingLedgerVersion( ): Promise { return connection .getLedgerVersion() - .then(ledgerVersion => ledgerVersion < (maxLedgerVersion || 0)) + .then((ledgerVersion) => ledgerVersion < (maxLedgerVersion || 0)) } function ensureLedgerVersion(this: RippleAPI, options: any): Promise { @@ -129,7 +129,7 @@ function ensureLedgerVersion(this: RippleAPI, options: any): Promise { ) { return Promise.resolve(options) } - return this.getLedgerVersion().then(ledgerVersion => + return this.getLedgerVersion().then((ledgerVersion) => _.assign({}, options, {ledgerVersion}) ) } diff --git a/src/offline/ledgerhash.ts b/src/offline/ledgerhash.ts index 6bac60cb..4eb75f43 100644 --- a/src/offline/ledgerhash.ts +++ b/src/offline/ledgerhash.ts @@ -38,7 +38,7 @@ function computeTransactionHash( transactions = JSON.parse(ledger.rawTransactions) } else if (ledger.transactions) { try { - transactions = ledger.transactions.map(tx => + transactions = ledger.transactions.map((tx) => JSON.parse(tx.rawTransaction) ) } catch (e) { @@ -60,7 +60,7 @@ function computeTransactionHash( } return ledger.transactionHash } - const txs = _.map(transactions, tx => { + const txs = _.map(transactions, (tx) => { const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {}) // rename `meta` back to `metaData` const renameMeta = _.assign( diff --git a/src/transaction/combine.ts b/src/transaction/combine.ts index db867b10..4a81ddba 100644 --- a/src/transaction/combine.ts +++ b/src/transaction/combine.ts @@ -24,7 +24,7 @@ function combine(signedTransactions: Array): object { // tests and this code handle it as an array of objects. Fix! const txs: any[] = _.map(signedTransactions, binary.decode) const tx = _.omit(txs[0], 'Signers') - if (!_.every(txs, _tx => _.isEqual(tx, _.omit(_tx, 'Signers')))) { + if (!_.every(txs, (_tx) => _.isEqual(tx, _.omit(_tx, 'Signers')))) { throw new utils.common.errors.ValidationError( 'txJSON is not the same for all signedTransactions' ) diff --git a/src/transaction/payment.ts b/src/transaction/payment.ts index ca7fa308..5a066722 100644 --- a/src/transaction/payment.ts +++ b/src/transaction/payment.ts @@ -76,8 +76,8 @@ function applyAnyCounterpartyEncoding(payment: Payment): void { // Convert blank counterparty to sender or receiver's address // (Ripple convention for 'any counterparty') // https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount - _.forEach([payment.source, payment.destination], adjustment => { - _.forEach(['amount', 'minAmount', 'maxAmount'], key => { + _.forEach([payment.source, payment.destination], (adjustment) => { + _.forEach(['amount', 'minAmount', 'maxAmount'], (key) => { if (isIOUWithoutCounterparty(adjustment[key])) { adjustment[key].counterparty = adjustment.address } @@ -91,7 +91,8 @@ function createMaximalAmount(amount: Amount): Amount { // Equivalent to '9999999999999999e80' but we cannot use that because sign() // now checks that the encoded representation exactly matches the transaction // as it was originally provided. - const maxIOUValue = '999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000' + const maxIOUValue = + '999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000' let maxValue if (amount.currency === 'XRP') { diff --git a/src/transaction/settings.ts b/src/transaction/settings.ts index c5e7f795..16374325 100644 --- a/src/transaction/settings.ts +++ b/src/transaction/settings.ts @@ -55,9 +55,7 @@ function setTransactionFields( if (field.encoding === 'hex' && !field.length) { // This is currently only used for Domain field - value = Buffer.from(value, 'ascii') - .toString('hex') - .toUpperCase() + value = Buffer.from(value, 'ascii').toString('hex').toUpperCase() } txJSON[fieldName] = value diff --git a/src/transaction/sign.ts b/src/transaction/sign.ts index 1ce5c7e5..bdebab90 100644 --- a/src/transaction/sign.ts +++ b/src/transaction/sign.ts @@ -79,7 +79,7 @@ function objectDiff(a: object, b: object): object { const diffs = {} // Compare two items and push non-matches to object - const compare = function(i1: any, i2: any, k: string): void { + const compare = function (i1: any, i2: any, k: string): void { const type1 = Object.prototype.toString.call(i1) const type2 = Object.prototype.toString.call(i2) if (type2 === '[object Undefined]') { diff --git a/src/transaction/utils.ts b/src/transaction/utils.ts index ebee8ad8..5c30d57f 100644 --- a/src/transaction/utils.ts +++ b/src/transaction/utils.ts @@ -52,10 +52,7 @@ function setCanonicalFlag(txJSON: TransactionJSON): void { } function scaleValue(value, multiplier, extra = 0) { - return new BigNumber(value) - .times(multiplier) - .plus(extra) - .toString() + return new BigNumber(value).times(multiplier).plus(extra).toString() } /** @@ -119,7 +116,7 @@ function prepareTransaction( 'fee', 'sequence' ] - const badFields = disallowedFieldsInTxJSON.filter(field => txJSON[field]) + const badFields = disallowedFieldsInTxJSON.filter((field) => txJSON[field]) if (badFields.length) { return Promise.reject( new ValidationError( @@ -236,7 +233,7 @@ function prepareTransaction( instructions.maxLedgerVersionOffset !== undefined ? instructions.maxLedgerVersionOffset : 3 - return api.connection.getLedgerVersion().then(ledgerVersion => { + return api.connection.getLedgerVersion().then((ledgerVersion) => { newTxJSON.LastLedgerSequence = ledgerVersion + offset return }) @@ -281,8 +278,8 @@ function prepareTransaction( return Promise.resolve() } const cushion = api._feeCushion - return api.getFee(cushion).then(fee => { - return api.connection.getFeeRef().then(feeRef => { + return api.getFee(cushion).then((fee) => { + return api.connection.getFeeRef().then((feeRef) => { const extraFee = newTxJSON.TransactionType !== 'EscrowFinish' || newTxJSON.Fulfillment === undefined @@ -347,9 +344,7 @@ function prepareTransaction( } function convertStringToHex(string: string): string { - return Buffer.from(string, 'utf8') - .toString('hex') - .toUpperCase() + return Buffer.from(string, 'utf8').toString('hex').toUpperCase() } function convertMemo(memo: Memo): {Memo: ApiMemo} { diff --git a/test/api/dropsToXrp/index.ts b/test/api/dropsToXrp/index.ts index 88b03ff1..aec39db6 100644 --- a/test/api/dropsToXrp/index.ts +++ b/test/api/dropsToXrp/index.ts @@ -8,11 +8,11 @@ import BigNumber from 'bignumber.js' * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'works with a typical amount': async api => { + 'works with a typical amount': async (api) => { const xrp = api.dropsToXrp('2000000') assert.strictEqual(xrp, '2', '2 million drops equals 2 XRP') }, - 'works with fractions': async api => { + 'works with fractions': async (api) => { let xrp = api.dropsToXrp('3456789') assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP') @@ -28,7 +28,7 @@ export default { xrp = api.dropsToXrp('1.00') assert.strictEqual(xrp, '0.000001', '1.00 drops equals 0.000001 XRP') }, - 'works with zero': async api => { + 'works with zero': async (api) => { let xrp = api.dropsToXrp('0') assert.strictEqual(xrp, '0', '0 drops equals 0 XRP') @@ -42,18 +42,18 @@ export default { xrp = api.dropsToXrp('000000000') assert.strictEqual(xrp, '0', '000000000 drops equals 0 XRP') }, - 'works with a negative value': async api => { + 'works with a negative value': async (api) => { const xrp = api.dropsToXrp('-2000000') assert.strictEqual(xrp, '-2', '-2 million drops equals -2 XRP') }, - 'works with a value ending with a decimal point': async api => { + 'works with a value ending with a decimal point': async (api) => { let xrp = api.dropsToXrp('2000000.') assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP') xrp = api.dropsToXrp('-2000000.') assert.strictEqual(xrp, '-2', '-2000000. drops equals -2 XRP') }, - 'works with BigNumber objects': async api => { + 'works with BigNumber objects': async (api) => { let xrp = api.dropsToXrp(new BigNumber(2000000)) assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP') @@ -74,14 +74,14 @@ export default { '(BigNumber) -2,345,678 drops equals -2.345678 XRP' ) }, - 'works with a number': async api => { + 'works with a number': async (api) => { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. let xrp = api.dropsToXrp(2000000) assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP') xrp = api.dropsToXrp(-2000000) assert.strictEqual(xrp, '-2', '(number) -2 million drops equals -2 XRP') }, - 'throws with an amount with too many decimal places': async api => { + 'throws with an amount with too many decimal places': async (api) => { assert.throws(() => { api.dropsToXrp('1.2') }, /has too many decimal places/) @@ -90,7 +90,7 @@ export default { api.dropsToXrp('0.10') }, /has too many decimal places/) }, - 'throws with an invalid value': async api => { + 'throws with an invalid value': async (api) => { assert.throws(() => { api.dropsToXrp('FOO') }, /invalid value/) @@ -107,7 +107,7 @@ export default { api.dropsToXrp('.') }, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./) }, - 'throws with an amount more than one decimal point': async api => { + 'throws with an amount more than one decimal point': async (api) => { assert.throws(() => { api.dropsToXrp('1.0.0') }, /dropsToXrp: invalid value '1\.0\.0'/) diff --git a/test/api/formatBidsAndAsks/index.ts b/test/api/formatBidsAndAsks/index.ts index c5351e06..60109cc3 100644 --- a/test/api/formatBidsAndAsks/index.ts +++ b/test/api/formatBidsAndAsks/index.ts @@ -267,16 +267,16 @@ export default { ]) const bidRates = orderbook.bids.map( - bid => bid.properties.makerExchangeRate + (bid) => bid.properties.makerExchangeRate ) const askRates = orderbook.asks.map( - ask => ask.properties.makerExchangeRate + (ask) => ask.properties.makerExchangeRate ) // makerExchangeRate = quality = takerPays.value/takerGets.value // so the best deal for the taker is the lowest makerExchangeRate // bids and asks should be sorted so that the best deals come first - assert.deepEqual(bidRates.map(x => Number(x)).sort(), bidRates) - assert.deepEqual(askRates.map(x => Number(x)).sort(), askRates) + assert.deepEqual(bidRates.map((x) => Number(x)).sort(), bidRates) + assert.deepEqual(askRates.map((x) => Number(x)).sort(), askRates) }) }, @@ -322,7 +322,7 @@ export default { ]) const orders = [...orderbook.bids, ...orderbook.asks] - orders.forEach(order => { + orders.forEach((order) => { const quantity = order.specification.quantity const totalPrice = order.specification.totalPrice const {base, counter} = requests.getOrderbook.normal @@ -375,9 +375,11 @@ export default { ...reverseOffers ]) - assert(orderbook.bids.every(bid => bid.specification.direction === 'buy')) assert( - orderbook.asks.every(ask => ask.specification.direction === 'sell') + orderbook.bids.every((bid) => bid.specification.direction === 'buy') + ) + assert( + orderbook.asks.every((ask) => ask.specification.direction === 'sell') ) }) } diff --git a/test/api/generateAddress/index.ts b/test/api/generateAddress/index.ts index 5ee0a6cd..e76b2dd2 100644 --- a/test/api/generateAddress/index.ts +++ b/test/api/generateAddress/index.ts @@ -10,7 +10,7 @@ const {generateAddress: RESPONSE_FIXTURES} = responses * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'generateAddress': async api => { + 'generateAddress': async (api) => { // GIVEN entropy of all zeros function random() { return new Array(16).fill(0) @@ -25,7 +25,7 @@ export default { ) }, - 'generateAddress invalid entropy': async api => { + 'generateAddress invalid entropy': async (api) => { assert.throws(() => { // GIVEN entropy of 1 byte function random() { @@ -40,7 +40,7 @@ export default { }, api.errors.UnexpectedError) }, - 'generateAddress with no options object': async api => { + 'generateAddress with no options object': async (api) => { // GIVEN no options // WHEN generating an address @@ -51,7 +51,7 @@ export default { assert(account.secret.startsWith('s'), 'Secret must start with `s`') }, - 'generateAddress with empty options object': async api => { + 'generateAddress with empty options object': async (api) => { // GIVEN an empty options object const options = {} @@ -63,7 +63,7 @@ export default { assert(account.secret.startsWith('s'), 'Secret must start with `s`') }, - 'generateAddress with algorithm `ecdsa-secp256k1`': async api => { + 'generateAddress with algorithm `ecdsa-secp256k1`': async (api) => { // GIVEN we want to use 'ecdsa-secp256k1' const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'} @@ -84,7 +84,7 @@ export default { ) }, - 'generateAddress with algorithm `ed25519`': async api => { + 'generateAddress with algorithm `ed25519`': async (api) => { // GIVEN we want to use 'ed25519' const options: GenerateAddressOptions = {algorithm: 'ed25519'} @@ -100,7 +100,9 @@ export default { ) }, - 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy': async api => { + 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -114,7 +116,7 @@ export default { assert.deepEqual(account, responses.generateAddress) }, - 'generateAddress with algorithm `ed25519` and given entropy': async api => { + 'generateAddress with algorithm `ed25519` and given entropy': async (api) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -135,7 +137,9 @@ export default { }) }, - 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async api => { + 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -150,7 +154,9 @@ export default { assert.deepEqual(account, responses.generateAddress) }, - 'generateAddress with algorithm `ed25519` and given entropy; include classic address': async api => { + 'generateAddress with algorithm `ed25519` and given entropy; include classic address': async ( + api + ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -172,7 +178,9 @@ export default { }) }, - 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async api => { + 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -192,7 +200,9 @@ export default { assert.deepEqual(account, response) }, - 'generateAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async api => { + 'generateAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async ( + api + ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -215,7 +225,7 @@ export default { }) }, - 'generateAddress for test network use': async api => { + 'generateAddress for test network use': async (api) => { // GIVEN we want an address for test network use const options: GenerateAddressOptions = {test: true} diff --git a/test/api/generateXAddress/index.ts b/test/api/generateXAddress/index.ts index 5b909e2e..189c2cfe 100644 --- a/test/api/generateXAddress/index.ts +++ b/test/api/generateXAddress/index.ts @@ -9,7 +9,7 @@ import {GenerateAddressOptions} from '../../../src/offline/generate-address' * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'generateXAddress': async api => { + 'generateXAddress': async (api) => { // GIVEN entropy of all zeros function random() { return new Array(16).fill(0) @@ -24,7 +24,7 @@ export default { ) }, - 'generateXAddress invalid entropy': async api => { + 'generateXAddress invalid entropy': async (api) => { assert.throws(() => { // GIVEN entropy of 1 byte function random() { @@ -39,7 +39,7 @@ export default { }, api.errors.UnexpectedError) }, - 'generateXAddress with no options object': async api => { + 'generateXAddress with no options object': async (api) => { // GIVEN no options // WHEN generating an X-address @@ -53,7 +53,7 @@ export default { assert(account.secret.startsWith('s'), 'Secrets start with s') }, - 'generateXAddress with empty options object': async api => { + 'generateXAddress with empty options object': async (api) => { // GIVEN an empty options object const options = {} @@ -68,7 +68,7 @@ export default { assert(account.secret.startsWith('s'), 'Secrets start with s') }, - 'generateXAddress with algorithm `ecdsa-secp256k1`': async api => { + 'generateXAddress with algorithm `ecdsa-secp256k1`': async (api) => { // GIVEN we want to use 'ecdsa-secp256k1' const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'} @@ -92,7 +92,7 @@ export default { ) }, - 'generateXAddress with algorithm `ed25519`': async api => { + 'generateXAddress with algorithm `ed25519`': async (api) => { // GIVEN we want to use 'ed25519' const options: GenerateAddressOptions = {algorithm: 'ed25519'} @@ -111,7 +111,9 @@ export default { ) }, - 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy': async api => { + 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -125,7 +127,9 @@ export default { assert.deepEqual(account, responses.generateXAddress) }, - 'generateXAddress with algorithm `ed25519` and given entropy': async api => { + 'generateXAddress with algorithm `ed25519` and given entropy': async ( + api + ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -142,7 +146,9 @@ export default { }) }, - 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async api => { + 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -157,7 +163,9 @@ export default { assert.deepEqual(account, responses.generateAddress) }, - 'generateXAddress with algorithm `ed25519` and given entropy; include classic address': async api => { + 'generateXAddress with algorithm `ed25519` and given entropy; include classic address': async ( + api + ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -177,7 +185,9 @@ export default { }) }, - 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async api => { + 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async ( + api + ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ecdsa-secp256k1', @@ -196,7 +206,9 @@ export default { assert.deepEqual(account, response) }, - 'generateXAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async api => { + 'generateXAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async ( + api + ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: 'ed25519', @@ -217,7 +229,7 @@ export default { }) }, - 'generateXAddress for test network use': async api => { + 'generateXAddress for test network use': async (api) => { // GIVEN we want an X-address for test network use const options: GenerateAddressOptions = {test: true} diff --git a/test/api/getBalances/index.ts b/test/api/getBalances/index.ts index 1ae08dca..c0a352b7 100644 --- a/test/api/getBalances/index.ts +++ b/test/api/getBalances/index.ts @@ -22,7 +22,7 @@ export default { 'getBalances - limit & currency': async (api, address) => { const options = {currency: 'USD', limit: 3} const expectedResponse = responses.getBalances - .filter(item => item.currency === 'USD') + .filter((item) => item.currency === 'USD') .slice(0, 3) const result = await api.getBalances(address, options) assertResultMatch(result, expectedResponse, 'getBalances') @@ -36,7 +36,7 @@ export default { } const expectedResponse = responses.getBalances .filter( - item => + (item) => item.currency === 'USD' && item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' ) diff --git a/test/api/getLedger/index.ts b/test/api/getLedger/index.ts index 1fd865bb..bdd75ed3 100644 --- a/test/api/getLedger/index.ts +++ b/test/api/getLedger/index.ts @@ -9,22 +9,22 @@ const {getLedger: RESPONSE_FIXTURES} = responses * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'simple test': async api => { + 'simple test': async (api) => { const response = await api.getLedger() assertResultMatch(response, RESPONSE_FIXTURES.header, 'getLedger') }, - 'by hash': async api => { + 'by hash': async (api) => { const response = await api.getLedger({ ledgerHash: '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D' }) assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger') }, - 'future ledger version': async api => { + 'future ledger version': async (api) => { const response = await api.getLedger({ledgerVersion: 14661789}) assert(!!response) }, - 'with state as hashes': async api => { + 'with state as hashes': async (api) => { const request = { includeTransactions: true, includeAllData: false, @@ -38,7 +38,7 @@ export default { 'getLedger' ) }, - 'with settings transaction': async api => { + 'with settings transaction': async (api) => { const request = { includeTransactions: true, includeAllData: true, @@ -47,7 +47,7 @@ export default { const response = await api.getLedger(request) assertResultMatch(response, RESPONSE_FIXTURES.withSettingsTx, 'getLedger') }, - 'with partial payment': async api => { + 'with partial payment': async (api) => { const request = { includeTransactions: true, includeAllData: true, @@ -56,7 +56,7 @@ export default { const response = await api.getLedger(request) assertResultMatch(response, RESPONSE_FIXTURES.withPartial, 'getLedger') }, - 'pre 2014 with partial payment': async api => { + 'pre 2014 with partial payment': async (api) => { const request = { includeTransactions: true, includeAllData: true, @@ -69,7 +69,7 @@ export default { 'getLedger' ) }, - 'full, then computeLedgerHash': async api => { + 'full, then computeLedgerHash': async (api) => { const request = { includeTransactions: true, includeState: true, diff --git a/test/api/getOrderbook/index.ts b/test/api/getOrderbook/index.ts index 04f4752c..1b43a2fa 100644 --- a/test/api/getOrderbook/index.ts +++ b/test/api/getOrderbook/index.ts @@ -108,17 +108,21 @@ export default { address, requests.getOrderbook.normal ) - const bidRates = response.bids.map(bid => bid.properties.makerExchangeRate) - const askRates = response.asks.map(ask => ask.properties.makerExchangeRate) + const bidRates = response.bids.map( + (bid) => bid.properties.makerExchangeRate + ) + const askRates = response.asks.map( + (ask) => ask.properties.makerExchangeRate + ) // makerExchangeRate = quality = takerPays.value/takerGets.value // so the best deal for the taker is the lowest makerExchangeRate // bids and asks should be sorted so that the best deals come first assert.deepEqual( - bidRates.sort(x => Number(x)), + bidRates.sort((x) => Number(x)), bidRates ) assert.deepEqual( - askRates.sort(x => Number(x)), + askRates.sort((x) => Number(x)), askRates ) }, @@ -128,7 +132,7 @@ export default { address, requests.getOrderbook.normal ) - ;[...response.bids, ...response.asks].forEach(order => { + ;[...response.bids, ...response.asks].forEach((order) => { const quantity = order.specification.quantity const totalPrice = order.specification.totalPrice const {base, counter} = requests.getOrderbook.normal @@ -144,7 +148,7 @@ export default { address, requests.getOrderbook.normal ) - assert(response.bids.every(bid => bid.specification.direction === 'buy')) - assert(response.asks.every(ask => ask.specification.direction === 'sell')) + assert(response.bids.every((bid) => bid.specification.direction === 'buy')) + assert(response.asks.every((ask) => ask.specification.direction === 'sell')) } } diff --git a/test/api/getPaths/index.ts b/test/api/getPaths/index.ts index 94301e1c..19e9eeb1 100644 --- a/test/api/getPaths/index.ts +++ b/test/api/getPaths/index.ts @@ -12,11 +12,11 @@ const {getPaths: RESPONSE_FIXTURES} = responses * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'simple test': async api => { + 'simple test': async (api) => { const response = await api.getPaths(REQUEST_FIXTURES.normal) assertResultMatch(response, RESPONSE_FIXTURES.XrpToUsd, 'getPaths') }, - 'queuing': async api => { + 'queuing': async (api) => { const [normalResult, usdOnlyResult, xrpOnlyResult] = await Promise.all([ api.getPaths(REQUEST_FIXTURES.normal), api.getPaths(REQUEST_FIXTURES.UsdToUsd), @@ -30,56 +30,56 @@ export default { // need decide what to do with currencies/XRP: // if add 'XRP' in currencies, then there will be exception in // xrpToDrops function (called from toRippledAmount) - 'getPaths USD 2 USD': async api => { + 'getPaths USD 2 USD': async (api) => { const response = await api.getPaths(REQUEST_FIXTURES.UsdToUsd) assertResultMatch(response, RESPONSE_FIXTURES.UsdToUsd, 'getPaths') }, - 'getPaths XRP 2 XRP': async api => { + 'getPaths XRP 2 XRP': async (api) => { const response = await api.getPaths(REQUEST_FIXTURES.XrpToXrp) assertResultMatch(response, RESPONSE_FIXTURES.XrpToXrp, 'getPaths') }, - 'source with issuer': async api => { + 'source with issuer': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.issuer), api.errors.NotFoundError ) }, - 'XRP 2 XRP - not enough': async api => { + 'XRP 2 XRP - not enough': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough), api.errors.NotFoundError ) }, - 'invalid PathFind': async api => { + 'invalid PathFind': async (api) => { assert.throws(() => { api.getPaths(REQUEST_FIXTURES.invalid) }, /Cannot specify both source.amount/) }, - 'does not accept currency': async api => { + 'does not accept currency': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.NotAcceptCurrency), api.errors.NotFoundError ) }, - 'no paths': async api => { + 'no paths': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.NoPaths), api.errors.NotFoundError ) }, - 'no paths source amount': async api => { + 'no paths source amount': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.NoPathsSource), api.errors.NotFoundError ) }, - 'no paths with source currencies': async api => { + 'no paths with source currencies': async (api) => { return assertRejects( api.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies), api.errors.NotFoundError ) }, - 'error: srcActNotFound': async api => { + 'error: srcActNotFound': async (api) => { return assertRejects( api.getPaths({ ...REQUEST_FIXTURES.normal, @@ -88,7 +88,7 @@ export default { api.errors.RippleError ) }, - 'send all': async api => { + 'send all': async (api) => { const response = await api.getPaths(REQUEST_FIXTURES.sendAll) assertResultMatch(response, RESPONSE_FIXTURES.sendAll, 'getPaths') } diff --git a/test/api/getTransactions/index.ts b/test/api/getTransactions/index.ts index 27579ac5..4f4b9178 100644 --- a/test/api/getTransactions/index.ts +++ b/test/api/getTransactions/index.ts @@ -100,8 +100,8 @@ export default { const response = await api.getTransactions(address, options) hack(response) assert.strictEqual(response.length, 10) - response.forEach(t => assert(t.type === 'payment' || t.type === 'order')) - response.forEach(t => assert(t.outcome.result === 'tesSUCCESS')) + response.forEach((t) => assert(t.type === 'payment' || t.type === 'order')) + response.forEach((t) => assert(t.outcome.result === 'tesSUCCESS')) }, 'filters for incoming': async (api, address) => { @@ -115,8 +115,8 @@ export default { const response = await api.getTransactions(address, options) hack(response) assert.strictEqual(response.length, 10) - response.forEach(t => assert(t.type === 'payment' || t.type === 'order')) - response.forEach(t => assert(t.outcome.result === 'tesSUCCESS')) + response.forEach((t) => assert(t.type === 'payment' || t.type === 'order')) + response.forEach((t) => assert(t.outcome.result === 'tesSUCCESS')) }, // this is the case where core.RippleError just falls @@ -162,7 +162,7 @@ export default { // the expected response. Long term, a better approach would be to use/test the json // format responses, instead of the binary. function hack(response) { - response.forEach(element => { + response.forEach((element) => { element.outcome.timestamp = '2019-04-01T07:39:01.000Z' }) } diff --git a/test/api/preparePayment/index.ts b/test/api/preparePayment/index.ts index f963636b..6e3cb17b 100644 --- a/test/api/preparePayment/index.ts +++ b/test/api/preparePayment/index.ts @@ -293,7 +293,10 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.noCounterparty, 'prepare') }, - 'preparePayment with source.amount/destination.minAmount can be signed': async (api, address) => { + 'preparePayment with source.amount/destination.minAmount can be signed': async ( + api, + address + ) => { // See also: 'sign succeeds with source.amount/destination.minAmount' const localInstructions = { @@ -303,20 +306,20 @@ export default { const response = await api.preparePayment( address, { - "source": { + source: { address, - "amount": { - "currency": "GBP", - "value": "0.1", - "counterparty": "rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro" + amount: { + currency: 'GBP', + value: '0.1', + counterparty: 'rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro' } }, - "destination": { - "address": "rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq", - "minAmount": { - "currency": "USD", - "value": "0.1248548562296331", - "counterparty": "rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH" + destination: { + address: 'rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq', + minAmount: { + currency: 'USD', + value: '0.1248548562296331', + counterparty: 'rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH' } } }, diff --git a/test/api/prepareTransaction/index.ts b/test/api/prepareTransaction/index.ts index 26309971..bf69f85c 100644 --- a/test/api/prepareTransaction/index.ts +++ b/test/api/prepareTransaction/index.ts @@ -569,7 +569,9 @@ export default { ) }, - 'rejects Promise when Account is valid but non-existent on the ledger': async api => { + 'rejects Promise when Account is valid but non-existent on the ledger': async ( + api + ) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' diff --git a/test/api/sign/index.ts b/test/api/sign/index.ts index 1276604f..6dcb20b6 100644 --- a/test/api/sign/index.ts +++ b/test/api/sign/index.ts @@ -146,7 +146,10 @@ export default { schemaValidator.schemaValidate('sign', result) }, - 'sign succeeds with source.amount/destination.minAmount': async (api, address) => { + 'sign succeeds with source.amount/destination.minAmount': async ( + api, + address + ) => { // See also: 'preparePayment with source.amount/destination.minAmount' const txJSON = diff --git a/test/api/xrpToDrops/index.ts b/test/api/xrpToDrops/index.ts index a46df6d4..627d2690 100644 --- a/test/api/xrpToDrops/index.ts +++ b/test/api/xrpToDrops/index.ts @@ -8,11 +8,11 @@ import {TestSuite} from '../../utils' * - Check out "test/api/index.ts" for more information about the test runner. */ export default { - 'works with a typical amount': function(api) { + 'works with a typical amount': function (api) { const drops = api.xrpToDrops('2') assert.strictEqual(drops, '2000000', '2 XRP equals 2 million drops') }, - 'works with fractions': function(api) { + 'works with fractions': function (api) { let drops = api.xrpToDrops('3.456789') assert.strictEqual(drops, '3456789', '3.456789 XRP equals 3,456,789 drops') drops = api.xrpToDrops('3.400000') @@ -22,7 +22,7 @@ export default { drops = api.xrpToDrops('0.0000010') assert.strictEqual(drops, '1', '0.0000010 XRP equals 1 drop') }, - 'works with zero': function(api) { + 'works with zero': function (api) { let drops = api.xrpToDrops('0') assert.strictEqual(drops, '0', '0 XRP equals 0 drops') drops = api.xrpToDrops('-0') // negative zero is equivalent to zero @@ -32,17 +32,17 @@ export default { drops = api.xrpToDrops('0.0000000') assert.strictEqual(drops, '0', '0.0000000 XRP equals 0 drops') }, - 'works with a negative value': function(api) { + 'works with a negative value': function (api) { const drops = api.xrpToDrops('-2') assert.strictEqual(drops, '-2000000', '-2 XRP equals -2 million drops') }, - 'works with a value ending with a decimal point': function(api) { + 'works with a value ending with a decimal point': function (api) { let drops = api.xrpToDrops('2.') assert.strictEqual(drops, '2000000', '2. XRP equals 2000000 drops') drops = api.xrpToDrops('-2.') assert.strictEqual(drops, '-2000000', '-2. XRP equals -2000000 drops') }, - 'works with BigNumber objects': function(api) { + 'works with BigNumber objects': function (api) { let drops = api.xrpToDrops(new BigNumber(2)) assert.strictEqual( drops, @@ -56,7 +56,7 @@ export default { '(BigNumber) -2 XRP equals -2 million drops' ) }, - 'works with a number': function(api) { + 'works with a number': function (api) { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. let drops = api.xrpToDrops(2) assert.strictEqual( @@ -71,7 +71,7 @@ export default { '(number) -2 XRP equals -2 million drops' ) }, - 'throws with an amount with too many decimal places': function(api) { + 'throws with an amount with too many decimal places': function (api) { assert.throws(() => { api.xrpToDrops('1.1234567') }, /has too many decimal places/) @@ -79,7 +79,7 @@ export default { api.xrpToDrops('0.0000001') }, /has too many decimal places/) }, - 'throws with an invalid value': function(api) { + 'throws with an invalid value': function (api) { assert.throws(() => { api.xrpToDrops('FOO') }, /invalid value/) @@ -93,7 +93,7 @@ export default { api.xrpToDrops('.') }, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./) }, - 'throws with an amount more than one decimal point': function(api) { + 'throws with an amount more than one decimal point': function (api) { assert.throws(() => { api.xrpToDrops('1.0.0') }, /xrpToDrops: invalid value '1\.0\.0'/) diff --git a/test/backoff-test.ts b/test/backoff-test.ts index a5121d7b..8afe8599 100644 --- a/test/backoff-test.ts +++ b/test/backoff-test.ts @@ -1,15 +1,15 @@ import assert from 'assert-diff' import {ExponentialBackoff} from '../src/common/backoff' -describe('ExponentialBackoff', function() { - it('duration() return value starts with the min value', function() { +describe('ExponentialBackoff', function () { + it('duration() return value starts with the min value', function () { // default: 100ms assert(new ExponentialBackoff().duration(), 100) assert(new ExponentialBackoff({min: 100}).duration(), 100) assert(new ExponentialBackoff({min: 123}).duration(), 123) }) - it('duration() return value increases when called multiple times', function() { + it('duration() return value increases when called multiple times', function () { const backoff = new ExponentialBackoff({min: 100, max: 1000}) assert.strictEqual(backoff.duration(), 100) assert.strictEqual(backoff.duration(), 200) @@ -17,7 +17,7 @@ describe('ExponentialBackoff', function() { assert.strictEqual(backoff.duration(), 800) }) - it('duration() never returns greater than the max value', function() { + it('duration() never returns greater than the max value', function () { const backoff = new ExponentialBackoff({min: 300, max: 1000}) assert.strictEqual(backoff.duration(), 300) assert.strictEqual(backoff.duration(), 600) @@ -25,7 +25,7 @@ describe('ExponentialBackoff', function() { assert.strictEqual(backoff.duration(), 1000) }) - it('reset() will reset the duration() value', function() { + it('reset() will reset the duration() value', function () { const backoff = new ExponentialBackoff({min: 100, max: 1000}) assert.strictEqual(backoff.duration(), 100) assert.strictEqual(backoff.duration(), 200) diff --git a/test/broadcast-api-test.ts b/test/broadcast-api-test.ts index 64ecc9b8..ddfe063f 100644 --- a/test/broadcast-api-test.ts +++ b/test/broadcast-api-test.ts @@ -21,21 +21,21 @@ function checkResult(expected, schemaName, response) { return response } -describe('RippleAPIBroadcast', function() { +describe('RippleAPIBroadcast', function () { this.timeout(TIMEOUT) beforeEach(setupAPI.setupBroadcast) afterEach(setupAPI.teardown) - it('base', function() { + it('base', function () { const expected = {request_server_info: 1} - this.mocks.forEach(mock => mock.expect(_.assign({}, expected))) + this.mocks.forEach((mock) => mock.expect(_.assign({}, expected))) assert(this.api.isConnected()) return this.api .getServerInfo() .then(_.partial(checkResult, responses.getServerInfo, 'getServerInfo')) }) - it('ledger', function(done) { + it('ledger', function (done) { let gotLedger = 0 this.api.on('ledger', () => { gotLedger++ @@ -43,7 +43,7 @@ describe('RippleAPIBroadcast', function() { const ledgerNext = _.assign({}, ledgerClosed) ledgerNext.ledger_index++ - this.api._apis.forEach(api => + this.api._apis.forEach((api) => api.connection .request({ command: 'echo', @@ -58,7 +58,7 @@ describe('RippleAPIBroadcast', function() { }, 1250) }) - it('error propagation', function(done) { + it('error propagation', function (done) { this.api.once('error', (type, info) => { assert.strictEqual(type, 'type') assert.strictEqual(info, 'info') diff --git a/test/connection-test.ts b/test/connection-test.ts index 6d298a4f..0bef31f8 100644 --- a/test/connection-test.ts +++ b/test/connection-test.ts @@ -13,22 +13,22 @@ const isBrowser = (process as any).browser function createServer() { return new Promise((resolve, reject) => { const server = net.createServer() - server.on('listening', function() { + server.on('listening', function () { resolve(server) }) - server.on('error', function(error) { + server.on('error', function (error) { reject(error) }) server.listen(0, '0.0.0.0') }) } -describe('Connection', function() { +describe('Connection', function () { this.timeout(TIMEOUT) beforeEach(setupAPI.setup) afterEach(setupAPI.teardown) - it('default options', function() { + it('default options', function () { const connection: any = new utils.common.Connection('url') assert.strictEqual(connection._url, 'url') assert(_.isUndefined(connection._config.proxy)) @@ -49,39 +49,39 @@ describe('Connection', function() { console.log = originalConsoleLog }) - it('as false', function() { + it('as false', function () { const messages = [] console.log = (id, message) => messages.push([id, message]) const connection: any = new utils.common.Connection('url', {trace: false}) - connection._ws = {send: function() {}} + connection._ws = {send: function () {}} connection.request(mockedRequestData) connection._onMessage(mockedResponse) assert.deepEqual(messages, []) }) - it('as true', function() { + it('as true', function () { const messages = [] console.log = (id, message) => messages.push([id, message]) const connection: any = new utils.common.Connection('url', {trace: true}) - connection._ws = {send: function() {}} + connection._ws = {send: function () {}} connection.request(mockedRequestData) connection._onMessage(mockedResponse) assert.deepEqual(messages, expectedMessages) }) - it('as a function', function() { + it('as a function', function () { const messages = [] const connection: any = new utils.common.Connection('url', { trace: (id, message) => messages.push([id, message]) }) - connection._ws = {send: function() {}} + connection._ws = {send: function () {}} connection.request(mockedRequestData) connection._onMessage(mockedResponse) assert.deepEqual(messages, expectedMessages) }) }) - it('ledger methods work as expected', async function() { + it('ledger methods work as expected', async function () { assert.strictEqual(await this.api.connection.getLedgerVersion(), 8819951) assert.strictEqual( await this.api.connection.hasLedgerVersion(8819951), @@ -101,7 +101,7 @@ describe('Connection', function() { assert.strictEqual(await this.api.connection.getReserveBase(), 20000000) // 20 XRP }) - it('with proxy', function(done) { + it('with proxy', function (done) { if (isBrowser) { done() return @@ -109,8 +109,8 @@ describe('Connection', function() { createServer().then((server: any) => { const port = server.address().port const expect = 'CONNECT localhost' - server.on('connection', socket => { - socket.on('data', data => { + server.on('connection', (socket) => { + socket.on('data', (data) => { const got = data.toString('ascii', 0, expect.length) assert.strictEqual(got, expect) server.close() @@ -128,34 +128,34 @@ describe('Connection', function() { this.api.connection._url, options ) - connection.connect().catch(err => { + connection.connect().catch((err) => { assert(err instanceof this.api.errors.NotConnectedError) }) }, done) }) - it('Multiply disconnect calls', function() { + it('Multiply disconnect calls', function () { this.api.disconnect() return this.api.disconnect() }) - it('reconnect', function() { + it('reconnect', function () { return this.api.connection.reconnect() }) - it('NotConnectedError', function() { + it('NotConnectedError', function () { const connection = new utils.common.Connection('url') return connection .getLedgerVersion() .then(() => { assert(false, 'Should throw NotConnectedError') }) - .catch(error => { + .catch((error) => { assert(error instanceof this.api.errors.NotConnectedError) }) }) - it('should throw NotConnectedError if server not responding ', function(done) { + it('should throw NotConnectedError if server not responding ', function (done) { if (isBrowser) { const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { @@ -170,13 +170,13 @@ describe('Connection', function() { 'ws://testripple.circleci.com:129' ) connection.on('error', done) - connection.connect().catch(error => { + connection.connect().catch((error) => { assert(error instanceof this.api.errors.NotConnectedError) done() }) }) - it('DisconnectedError', async function() { + it('DisconnectedError', async function () { await this.api.connection.request({ command: 'config', data: {disconnectOnServerInfo: true} @@ -186,13 +186,13 @@ describe('Connection', function() { .then(() => { assert(false, 'Should throw DisconnectedError') }) - .catch(error => { + .catch((error) => { assert(error instanceof this.api.errors.DisconnectedError) }) }) - it('TimeoutError', function() { - this.api.connection._ws.send = function(message, options, callback) { + it('TimeoutError', function () { + this.api.connection._ws.send = function (message, options, callback) { callback(null) } const request = {command: 'server_info'} @@ -201,13 +201,13 @@ describe('Connection', function() { .then(() => { assert(false, 'Should throw TimeoutError') }) - .catch(error => { + .catch((error) => { assert(error instanceof this.api.errors.TimeoutError) }) }) - it('DisconnectedError on send', function() { - this.api.connection._ws.send = function(message, options, callback) { + it('DisconnectedError on send', function () { + this.api.connection._ws.send = function (message, options, callback) { callback({message: 'not connected'}) } return this.api @@ -215,13 +215,13 @@ describe('Connection', function() { .then(() => { assert(false, 'Should throw DisconnectedError') }) - .catch(error => { + .catch((error) => { assert(error instanceof this.api.errors.DisconnectedError) assert.strictEqual(error.message, 'not connected') }) }) - it('DisconnectedError on initial _onOpen send', async function() { + it('DisconnectedError on initial _onOpen send', async function () { // _onOpen previously could throw PromiseRejectionHandledWarning: Promise rejection was handled asynchronously // do not rely on the api.setup hook to test this as it bypasses the case, disconnect api connection first await this.api.disconnect() @@ -229,7 +229,7 @@ describe('Connection', function() { // stub _onOpen to only run logic relevant to test case this.api.connection._onOpen = () => { // overload websocket send on open when _ws exists - this.api.connection._ws.send = function(data, options, cb) { + this.api.connection._ws.send = function (data, options, cb) { // recent ws throws this error instead of calling back throw new Error('WebSocket is not open: readyState 0 (CONNECTING)') } @@ -248,18 +248,18 @@ describe('Connection', function() { } }) - it('ResponseFormatError', function() { + it('ResponseFormatError', function () { return this.api .request('test_command', {data: {unrecognizedResponse: true}}) .then(() => { assert(false, 'Should throw ResponseFormatError') }) - .catch(error => { + .catch((error) => { assert(error instanceof this.api.errors.ResponseFormatError) }) }) - it('reconnect on unexpected close', function(done) { + it('reconnect on unexpected close', function (done) { this.api.connection.on('connected', () => { done() }) @@ -268,8 +268,8 @@ describe('Connection', function() { }, 1) }) - describe('reconnection test', function() { - it('reconnect on several unexpected close', function(done) { + describe('reconnection test', function () { + it('reconnect on several unexpected close', function (done) { if (isBrowser) { const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { @@ -296,7 +296,7 @@ describe('Connection', function() { this.api.connection.on('reconnecting', () => { reconnectsCount += 1 }) - this.api.connection.on('disconnected', _code => { + this.api.connection.on('disconnected', (_code) => { code = _code disconnectsCount += 1 }) @@ -343,7 +343,7 @@ describe('Connection', function() { }) }) - it('reconnect event on heartbeat failure', function(done) { + it('reconnect event on heartbeat failure', function (done) { if (isBrowser) { const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { @@ -359,12 +359,12 @@ describe('Connection', function() { // Hook up a listener for the reconnect event this.api.connection.on('reconnect', () => done()) // Trigger a heartbeat - this.api.connection._heartbeat().catch(error => { + this.api.connection._heartbeat().catch((error) => { /* ignore - test expects heartbeat failure */ }) }) - it('heartbeat failure and reconnect failure', function(done) { + it('heartbeat failure and reconnect failure', function (done) { if (isBrowser) { const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { @@ -392,19 +392,19 @@ describe('Connection', function() { this.api.connection._heartbeat() }) - it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function(done) { - this.api.once('disconnected', code => { + it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) { + this.api.once('disconnected', (code) => { assert.strictEqual(code, 1000) done() }) this.api.disconnect() }) - it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function(done) { - this.api.connection.once('error', error => { + it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) { + this.api.connection.once('error', (error) => { done(new Error('should not throw error, got ' + String(error))) }) - this.api.connection.once('disconnected', code => { + this.api.connection.once('disconnected', (code) => { assert.strictEqual(code, 1006) done() }) @@ -416,31 +416,31 @@ describe('Connection', function() { .catch(ignoreWebSocketDisconnect) }) - it('should emit connected event on after reconnect', function(done) { + it('should emit connected event on after reconnect', function (done) { this.api.once('connected', done) this.api.connection._ws.close() }) - it('Multiply connect calls', function() { + it('Multiply connect calls', function () { return this.api.connect().then(() => { return this.api.connect() }) }) - it('hasLedgerVersion', function() { - return this.api.connection.hasLedgerVersion(8819951).then(result => { + it('hasLedgerVersion', function () { + return this.api.connection.hasLedgerVersion(8819951).then((result) => { assert(result) }) }) - it('Cannot connect because no server', function() { + it('Cannot connect because no server', function () { const connection = new utils.common.Connection(undefined as string) return connection .connect() .then(() => { assert(false, 'Should throw ConnectionError') }) - .catch(error => { + .catch((error) => { assert( error instanceof this.api.errors.ConnectionError, 'Should throw ConnectionError' @@ -448,15 +448,15 @@ describe('Connection', function() { }) }) - it('connect multiserver error', function() { - assert.throws(function() { + it('connect multiserver error', function () { + assert.throws(function () { new RippleAPI({ servers: ['wss://server1.com', 'wss://server2.com'] } as any) }, this.api.errors.RippleError) }) - it('connect throws error', function(done) { + it('connect throws error', function (done) { this.api.once('error', (type, info) => { assert.strictEqual(type, 'type') assert.strictEqual(info, 'info') @@ -465,7 +465,7 @@ describe('Connection', function() { this.api.connection.emit('error', 'type', 'info') }) - it('emit stream messages', function(done) { + it('emit stream messages', function (done) { let transactionCount = 0 let pathFindCount = 0 this.api.connection.on('transaction', () => { @@ -474,7 +474,7 @@ describe('Connection', function() { this.api.connection.on('path_find', () => { pathFindCount++ }) - this.api.connection.on('response', message => { + this.api.connection.on('response', (message) => { assert.strictEqual(message.id, 1) assert.strictEqual(transactionCount, 1) assert.strictEqual(pathFindCount, 1) @@ -499,7 +499,7 @@ describe('Connection', function() { ) }) - it('invalid message id', function(done) { + it('invalid message id', function (done) { this.api.on('error', (errorCode, errorMessage, message) => { assert.strictEqual(errorCode, 'badMessage') assert.strictEqual(errorMessage, 'valid id not found in response') @@ -514,7 +514,7 @@ describe('Connection', function() { ) }) - it('propagates error message', function(done) { + it('propagates error message', function (done) { this.api.on('error', (errorCode, errorMessage, data) => { assert.strictEqual(errorCode, 'slowDown') assert.strictEqual(errorMessage, 'slow down') @@ -529,8 +529,8 @@ describe('Connection', function() { ) }) - it('propagates RippledError data', function(done) { - this.api.request('subscribe', {streams: 'validations'}).catch(error => { + it('propagates RippledError data', function (done) { + this.api.request('subscribe', {streams: 'validations'}).catch((error) => { assert.strictEqual(error.name, 'RippledError') assert.strictEqual(error.data.error, 'invalidParams') assert.strictEqual(error.message, 'Invalid parameters.') @@ -547,10 +547,10 @@ describe('Connection', function() { }) }) - it('unrecognized message type', function(done) { + it('unrecognized message type', function (done) { // This enables us to automatically support any // new messages added by rippled in the future. - this.api.connection.on('unknown', event => { + this.api.connection.on('unknown', (event) => { assert.deepEqual(event, {type: 'unknown'}) done() }) @@ -558,9 +558,9 @@ describe('Connection', function() { this.api.connection._onMessage(JSON.stringify({type: 'unknown'})) }) - it('ledger close without validated_ledgers', function(done) { + it('ledger close without validated_ledgers', function (done) { const message = _.omit(ledgerClose, 'validated_ledgers') - this.api.on('ledger', function(ledger) { + this.api.on('ledger', function (ledger) { assert.strictEqual(ledger.ledgerVersion, 8819951) done() }) @@ -570,7 +570,7 @@ describe('Connection', function() { it( 'should throw RippledNotInitializedError if server does not have ' + 'validated ledgers', - async function() { + async function () { this.timeout(3000) await this.api.connection.request({ @@ -583,7 +583,7 @@ describe('Connection', function() { () => { assert(false, 'Must have thrown!') }, - error => { + (error) => { assert( error instanceof this.api.errors.RippledNotInitializedError, 'Must throw RippledNotInitializedError, got instead ' + @@ -594,7 +594,7 @@ describe('Connection', function() { } ) - it('should clean up websocket connection if error after websocket is opened', async function() { + it('should clean up websocket connection if error after websocket is opened', async function () { await this.api.disconnect() // fail on connection this.api.connection._subscribeToLedger = async () => { @@ -612,9 +612,9 @@ describe('Connection', function() { } }) - it('should try to reconnect on empty subscribe response on reconnect', function(done) { + it('should try to reconnect on empty subscribe response on reconnect', function (done) { this.timeout(23000) - this.api.on('error', error => { + this.api.on('error', (error) => { done(error || new Error('Should not emit error.')) }) let disconnectedCount = 0 diff --git a/test/hashes-test.ts b/test/hashes-test.ts index 6972d9d8..3e99376c 100644 --- a/test/hashes-test.ts +++ b/test/hashes-test.ts @@ -6,7 +6,7 @@ import * as hashes from '../src/common/hashes' * Expects a corresponding ledger dump in $repo/test/fixtures/rippled folder */ function createLedgerTest(ledgerIndex: number) { - describe(String(ledgerIndex), function() { + describe(String(ledgerIndex), function () { var path = __dirname + '/fixtures/rippled/ledger-full-' + ledgerIndex + '.json' @@ -18,14 +18,14 @@ function createLedgerTest(ledgerIndex: number) { ledgerJSON.accountState.length > 0 if (hasAccounts) { - it('has account_hash of ' + ledgerJSON.account_hash, function() { + it('has account_hash of ' + ledgerJSON.account_hash, function () { assert.equal( ledgerJSON.account_hash, hashes.computeStateTreeHash(ledgerJSON.accountState) ) }) } - it('has transaction_hash of ' + ledgerJSON.transaction_hash, function() { + it('has transaction_hash of ' + ledgerJSON.transaction_hash, function () { assert.equal( ledgerJSON.transaction_hash, hashes.computeTransactionTreeHash(ledgerJSON.transactions) @@ -34,7 +34,7 @@ function createLedgerTest(ledgerIndex: number) { }) } -describe('Ledger', function() { +describe('Ledger', function () { // This is the first recorded ledger with a non empty transaction set createLedgerTest(38129) // Because, why not. @@ -42,8 +42,8 @@ describe('Ledger', function() { // 1311 AffectedNodes, no accounts createLedgerTest(7501326) - describe('calcAccountRootEntryHash', function() { - it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function() { + describe('calcAccountRootEntryHash', function () { + it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () { var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' var expectedEntryHash = '2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8' @@ -53,8 +53,8 @@ describe('Ledger', function() { }) }) - describe('calcRippleStateEntryHash', function() { - it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function() { + describe('calcRippleStateEntryHash', function () { + it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function () { var account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' var account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY' var currency = 'USD' @@ -76,7 +76,7 @@ describe('Ledger', function() { assert.equal(actualEntryHash2, expectedEntryHash) }) - it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function() { + it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function () { var account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV' var account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj' var currency = 'UAM' @@ -99,8 +99,8 @@ describe('Ledger', function() { }) }) - describe('calcOfferEntryHash', function() { - it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function() { + describe('calcOfferEntryHash', function () { + it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function () { var account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw' var sequence = 137 var expectedEntryHash = @@ -111,8 +111,8 @@ describe('Ledger', function() { }) }) - describe('computeSignerListLedgerObjectID', function() { - it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function() { + describe('computeSignerListLedgerObjectID', function () { + it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function () { var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' var expectedEntryHash = '778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF' @@ -121,8 +121,8 @@ describe('Ledger', function() { }) }) - describe('calcEscrowEntryHash', function() { - it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function() { + describe('calcEscrowEntryHash', function () { + it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function () { var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' var sequence = 84 var expectedEntryHash = @@ -133,8 +133,8 @@ describe('Ledger', function() { }) }) - describe('calcPaymentChannelEntryHash', function() { - it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function() { + describe('calcPaymentChannelEntryHash', function () { + it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function () { var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' var dstAccount = 'rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso' var sequence = 82 diff --git a/test/integration/broadcast-test.ts b/test/integration/broadcast-test.ts index 11da1dd4..f114d205 100644 --- a/test/integration/broadcast-test.ts +++ b/test/integration/broadcast-test.ts @@ -4,10 +4,10 @@ function main() { const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com'] const api = new RippleAPIBroadcast(servers) api.connect().then(() => { - api.getServerInfo().then(info => { + api.getServerInfo().then((info) => { console.log(JSON.stringify(info, null, 2)) }) - api.on('ledger', ledger => { + api.on('ledger', (ledger) => { console.log(JSON.stringify(ledger, null, 2)) }) }) diff --git a/test/integration/connection-test.ts b/test/integration/connection-test.ts index 14ac350c..79b1760c 100644 --- a/test/integration/connection-test.ts +++ b/test/integration/connection-test.ts @@ -21,11 +21,11 @@ const request4 = { function makeRequest(connection, request) { return connection .request(request) - .then(response => { + .then((response) => { console.log(request) console.log(JSON.stringify(response, null, 2)) }) - .catch(error => { + .catch((error) => { console.log(request) console.log(error) }) @@ -44,7 +44,7 @@ function main() { console.log('Done') }) connection.getLedgerVersion().then(console.log) - connection.on('ledgerClosed', ledger => { + connection.on('ledgerClosed', (ledger) => { console.log(ledger) connection.getLedgerVersion().then(console.log) }) diff --git a/test/integration/integration-test.ts b/test/integration/integration-test.ts index 7117d290..4672c42a 100644 --- a/test/integration/integration-test.ts +++ b/test/integration/integration-test.ts @@ -22,7 +22,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) { console.log('VERIFY...') return testcase.api .getTransaction(hash, options) - .then(data => { + .then((data) => { assert(data && data.outcome) assert.strictEqual(data.type, type) assert.strictEqual(data.address, address) @@ -32,7 +32,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) { } return {txJSON: JSON.stringify(txData), id: hash, tx: data} }) - .catch(error => { + .catch((error) => { if (error instanceof errors.PendingLedgerVersionError) { console.log('NOT VALIDATED YET...') return new Promise((resolve, reject) => { @@ -71,12 +71,12 @@ function testTransaction( console.log('PREPARED...') return testcase.api .submit(signedData.signedTransaction) - .then(data => + .then((data) => testcase.test.title.indexOf('multisign') !== -1 ? acceptLedger(testcase.api).then(() => data) : data ) - .then(data => { + .then((data) => { console.log('SUBMITTED...') assert.strictEqual(data.resultCode, 'tesSUCCESS') const options = { @@ -108,7 +108,7 @@ function setup(this: any, server = 'wss://s1.ripple.com') { () => { console.log('CONNECTED...') }, - error => { + (error) => { console.log('ERROR:', error) throw error } @@ -128,7 +128,7 @@ function makeTrustLine(testcase, address, secret) { } const trust = api .prepareTrustline(address, specification, {}) - .then(data => { + .then((data) => { const signed = api.sign(data.txJSON, secret) if (address === wallet.getAddress()) { testcase.transactions.push(signed.id) @@ -142,8 +142,8 @@ function makeTrustLine(testcase, address, secret) { function makeOrder(api, address, specification, secret) { return api .prepareOrder(address, specification) - .then(data => api.sign(data.txJSON, secret)) - .then(signed => api.submit(signed.signedTransaction)) + .then((data) => api.sign(data.txJSON, secret)) + .then((signed) => api.submit(signed.signedTransaction)) .then(() => ledgerAccept(api)) } @@ -158,8 +158,8 @@ function setupAccounts(testcase) { .then(() => { return api .prepareSettings(masterAccount, {defaultRipple: true}) - .then(data => api.sign(data.txJSON, masterSecret)) - .then(signed => api.submit(signed.signedTransaction)) + .then((data) => api.sign(data.txJSON, masterSecret)) + .then((signed) => api.submit(signed.signedTransaction)) .then(() => ledgerAccept(api)) }) .then(() => @@ -233,7 +233,7 @@ function suiteSetup(this: any) { // so getLedgerVersion will return right value .then(() => ledgerAccept(this.api)) .then(() => this.api.getLedgerVersion()) - .then(ledgerVersion => { + .then((ledgerVersion) => { this.startLedgerVersion = ledgerVersion }) .then(() => setupAccounts(this)) @@ -241,7 +241,7 @@ function suiteSetup(this: any) { ) } -describe('integration tests', function() { +describe('integration tests', function () { const address = wallet.getAddress() const instructions = {maxLedgerVersionOffset: 10} this.timeout(TIMEOUT) @@ -250,31 +250,31 @@ describe('integration tests', function() { beforeEach(_.partial(setup, serverUrl)) afterEach(teardown) - it('settings', function() { - return this.api.getLedgerVersion().then(ledgerVersion => { + it('settings', function () { + return this.api.getLedgerVersion().then((ledgerVersion) => { return this.api .prepareSettings(address, requests.prepareSettings.domain, instructions) - .then(prepared => + .then((prepared) => testTransaction(this, 'settings', ledgerVersion, prepared) ) }) }) - it('trustline', function() { - return this.api.getLedgerVersion().then(ledgerVersion => { + it('trustline', function () { + return this.api.getLedgerVersion().then((ledgerVersion) => { return this.api .prepareTrustline( address, requests.prepareTrustline.simple, instructions ) - .then(prepared => + .then((prepared) => testTransaction(this, 'trustline', ledgerVersion, prepared) ) }) }) - it('payment', function() { + it('payment', function () { const amount = {currency: 'XRP', value: '0.000001'} const paymentSpecification = { source: { @@ -286,16 +286,16 @@ describe('integration tests', function() { amount: amount } } - return this.api.getLedgerVersion().then(ledgerVersion => { + return this.api.getLedgerVersion().then((ledgerVersion) => { return this.api .preparePayment(address, paymentSpecification, instructions) - .then(prepared => + .then((prepared) => testTransaction(this, 'payment', ledgerVersion, prepared) ) }) }) - it('order', function() { + it('order', function () { const orderSpecification = { direction: 'buy', quantity: { @@ -308,18 +308,18 @@ describe('integration tests', function() { value: '0.0002' } } - return this.api.getLedgerVersion().then(ledgerVersion => { + return this.api.getLedgerVersion().then((ledgerVersion) => { return this.api .prepareOrder(address, orderSpecification, instructions) - .then(prepared => + .then((prepared) => testTransaction(this, 'order', ledgerVersion, prepared) ) - .then(result => { + .then((result) => { const txData = JSON.parse(result.txJSON) - return this.api.getOrders(address).then(orders => { + return this.api.getOrders(address).then((orders) => { assert(orders && orders.length > 0) const createdOrder = _.first( - _.filter(orders, order => { + _.filter(orders, (order) => { return order.properties.sequence === txData.Sequence }) ) @@ -329,14 +329,14 @@ describe('integration tests', function() { return txData }) }) - .then(txData => + .then((txData) => this.api .prepareOrderCancellation( address, {orderSequence: txData.Sequence}, instructions ) - .then(prepared => + .then((prepared) => testTransaction( this, 'orderCancellation', @@ -348,46 +348,48 @@ describe('integration tests', function() { }) }) - it('isConnected', function() { + it('isConnected', function () { assert(this.api.isConnected()) }) - it('getServerInfo', function() { - return this.api.getServerInfo().then(data => { + it('getServerInfo', function () { + return this.api.getServerInfo().then((data) => { assert(data && data.pubkeyNode) }) }) - it('getFee', function() { - return this.api.getFee().then(fee => { + it('getFee', function () { + return this.api.getFee().then((fee) => { assert.strictEqual(typeof fee, 'string') assert(!isNaN(Number(fee))) assert(parseFloat(fee) === Number(fee)) }) }) - it('getLedgerVersion', function() { - return this.api.getLedgerVersion().then(ledgerVersion => { + it('getLedgerVersion', function () { + return this.api.getLedgerVersion().then((ledgerVersion) => { assert.strictEqual(typeof ledgerVersion, 'number') assert(ledgerVersion >= this.startLedgerVersion) }) }) - it('getTransactions', function() { + it('getTransactions', function () { const options = { initiated: true, minLedgerVersion: this.startLedgerVersion } - return this.api.getTransactions(address, options).then(transactionsData => { - assert(transactionsData) - assert.strictEqual(transactionsData.length, this.transactions.length) - }) + return this.api + .getTransactions(address, options) + .then((transactionsData) => { + assert(transactionsData) + assert.strictEqual(transactionsData.length, this.transactions.length) + }) }) - it('getTrustlines', function() { + it('getTrustlines', function () { const fixture = requests.prepareTrustline.simple const options = _.pick(fixture, ['currency', 'counterparty']) - return this.api.getTrustlines(address, options).then(data => { + return this.api.getTrustlines(address, options).then((data) => { assert(data && data.length > 0 && data[0] && data[0].specification) const specification = data[0].specification assert.strictEqual(Number(specification.limit), Number(fixture.limit)) @@ -396,24 +398,24 @@ describe('integration tests', function() { }) }) - it('getBalances', function() { + it('getBalances', function () { const fixture = requests.prepareTrustline.simple const options = _.pick(fixture, ['currency', 'counterparty']) - return this.api.getBalances(address, options).then(data => { + return this.api.getBalances(address, options).then((data) => { assert(data && data.length > 0 && data[0]) assert.strictEqual(data[0].currency, fixture.currency) assert.strictEqual(data[0].counterparty, fixture.counterparty) }) }) - it('getSettings', function() { - return this.api.getSettings(address).then(data => { + it('getSettings', function () { + return this.api.getSettings(address).then((data) => { assert(data) assert.strictEqual(data.domain, requests.prepareSettings.domain.domain) }) }) - it('getOrderbook', function() { + it('getOrderbook', function () { const orderbook = { base: { currency: 'XRP' @@ -423,7 +425,7 @@ describe('integration tests', function() { counterparty: masterAccount } } - return this.api.getOrderbook(address, orderbook).then(book => { + return this.api.getOrderbook(address, orderbook).then((book) => { assert(book && book.bids && book.bids.length > 0) assert(book.asks && book.asks.length > 0) const bid = book.bids[0] @@ -441,7 +443,7 @@ describe('integration tests', function() { }) }) - it('getPaths', function() { + it('getPaths', function () { const pathfind = { source: { address: address @@ -455,7 +457,7 @@ describe('integration tests', function() { } } } - return this.api.getPaths(pathfind).then(data => { + return this.api.getPaths(pathfind).then((data) => { assert(data && data.length > 0) const path = data[0] assert(path && path.source) @@ -464,7 +466,7 @@ describe('integration tests', function() { }) }) - it('getPaths - send all', function() { + it('getPaths - send all', function () { const pathfind = { source: { address: address, @@ -481,10 +483,10 @@ describe('integration tests', function() { } } - return this.api.getPaths(pathfind).then(data => { + return this.api.getPaths(pathfind).then((data) => { assert(data && data.length > 0) assert( - _.every(data, path => { + _.every(data, (path) => { return ( parseFloat(path.source.amount.value) <= parseFloat(pathfind.source.amount.value) @@ -498,7 +500,7 @@ describe('integration tests', function() { }) }) - it('generateWallet', function() { + it('generateWallet', function () { const newWallet = this.api.generateAddress() assert(newWallet && newWallet.address && newWallet.secret) assert(isValidAddress(newWallet.address)) @@ -506,7 +508,7 @@ describe('integration tests', function() { }) }) -describe('integration tests - standalone rippled', function() { +describe('integration tests - standalone rippled', function () { const instructions = {maxLedgerVersionOffset: 10} this.timeout(TIMEOUT) @@ -519,7 +521,7 @@ describe('integration tests - standalone rippled', function() { const signer2address = 'r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud' const signer2secret = 'shUHQnL4EH27V4EiBrj6EfhWvZngF' - it('submit multisigned transaction', function() { + it('submit multisigned transaction', function () { const signers = { threshold: 2, weights: [ @@ -530,11 +532,11 @@ describe('integration tests - standalone rippled', function() { let minLedgerVersion = null return payTo(this.api, address) .then(() => { - return this.api.getLedgerVersion().then(ledgerVersion => { + return this.api.getLedgerVersion().then((ledgerVersion) => { minLedgerVersion = ledgerVersion return this.api .prepareSettings(address, {signers}, instructions) - .then(prepared => { + .then((prepared) => { return testTransaction( this, 'settings', @@ -556,7 +558,7 @@ describe('integration tests - standalone rippled', function() { {domain: 'example.com'}, multisignInstructions ) - .then(prepared => { + .then((prepared) => { const signed1 = this.api.sign(prepared.txJSON, signer1secret, { signAs: signer1address }) @@ -569,8 +571,8 @@ describe('integration tests - standalone rippled', function() { ]) return this.api .submit(combined.signedTransaction) - .then(response => acceptLedger(this.api).then(() => response)) - .then(response => { + .then((response) => acceptLedger(this.api).then(() => response)) + .then((response) => { assert.strictEqual(response.resultCode, 'tesSUCCESS') const options = {minLedgerVersion} return verifyTransaction( @@ -582,7 +584,7 @@ describe('integration tests - standalone rippled', function() { address ) }) - .catch(error => { + .catch((error) => { console.log(error.message) throw error }) diff --git a/test/mock-rippled.ts b/test/mock-rippled.ts index 56409e66..4b4edc72 100644 --- a/test/mock-rippled.ts +++ b/test/mock-rippled.ts @@ -59,9 +59,11 @@ export function createMockRippled(port) { _.assign(mock, EventEmitter2.prototype) const close = mock.close - mock.close = function() { + mock.close = function () { if (mock.expectedRequests !== undefined) { - const allRequestsMade = _.every(mock.expectedRequests, function(counter) { + const allRequestsMade = _.every(mock.expectedRequests, function ( + counter + ) { return counter === 0 }) if (!allRequestsMade) { @@ -74,11 +76,11 @@ export function createMockRippled(port) { close.call(mock) } - mock.expect = function(expectedRequests) { + mock.expect = function (expectedRequests) { mock.expectedRequests = expectedRequests } - mock.on('connection', function(this: MockedWebSocketServer, conn: any) { + mock.on('connection', function (this: MockedWebSocketServer, conn: any) { if (mock.config.breakNextConnection) { mock.config.breakNextConnection = false conn.terminate() @@ -86,7 +88,7 @@ export function createMockRippled(port) { } this.socket = conn conn.config = {} - conn.on('message', function(requestJSON) { + conn.on('message', function (requestJSON) { try { const request = JSON.parse(requestJSON) mock.emit('request_' + request.command, request, conn) @@ -99,7 +101,7 @@ export function createMockRippled(port) { mock.config = {} - mock.onAny(function(this: MockedWebSocketServer) { + mock.onAny(function (this: MockedWebSocketServer) { if (this.event.indexOf('request_') !== 0) { return } @@ -116,7 +118,7 @@ export function createMockRippled(port) { mock.expectedRequests[this.event] -= 1 }) - mock.on('request_config', function(request, conn) { + mock.on('request_config', function (request, conn) { assert.strictEqual(request.command, 'config') conn.config = _.assign(conn.config, request.data) conn.send( @@ -128,7 +130,7 @@ export function createMockRippled(port) { ) }) - mock.on('request_test_command', function(request, conn) { + mock.on('request_test_command', function (request, conn) { assert.strictEqual(request.command, 'test_command') if (request.data.disconnectIn) { setTimeout(conn.terminate.bind(conn), request.data.disconnectIn) @@ -140,7 +142,7 @@ export function createMockRippled(port) { }) ) } else if (request.data.openOnOtherPort) { - getFreePort().then(newPort => { + getFreePort().then((newPort) => { createMockRippled(newPort) conn.send( createResponse(request, { @@ -170,7 +172,7 @@ export function createMockRippled(port) { } }) - mock.on('request_global_config', function(request, conn) { + mock.on('request_global_config', function (request, conn) { assert.strictEqual(request.command, 'global_config') mock.config = _.assign(conn.config, request.data) conn.send( @@ -182,12 +184,12 @@ export function createMockRippled(port) { ) }) - mock.on('request_echo', function(request, conn) { + mock.on('request_echo', function (request, conn) { assert.strictEqual(request.command, 'echo') conn.send(JSON.stringify(request.data)) }) - mock.on('request_server_info', function(request, conn) { + mock.on('request_server_info', function (request, conn) { assert.strictEqual(request.command, 'server_info') if (conn.config.highLoadFactor || conn.config.loadFactor) { const response = { @@ -236,7 +238,7 @@ export function createMockRippled(port) { } }) - mock.on('request_subscribe', function(request, conn) { + mock.on('request_subscribe', function (request, conn) { assert.strictEqual(request.command, 'subscribe') if (request && request.streams === 'validations') { conn.send(createResponse(request, fixtures.subscribe_error)) @@ -249,7 +251,7 @@ export function createMockRippled(port) { conn.send(createResponse(request, fixtures.subscribe)) }) - mock.on('request_unsubscribe', function(request, conn) { + mock.on('request_unsubscribe', function (request, conn) { assert.strictEqual(request.command, 'unsubscribe') if (request.accounts) { assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1) @@ -259,7 +261,7 @@ export function createMockRippled(port) { conn.send(createResponse(request, fixtures.unsubscribe)) }) - mock.on('request_account_objects', function(request, conn) { + mock.on('request_account_objects', function (request, conn) { assert.strictEqual(request.command, 'account_objects') if (request.account === addresses.ACCOUNT) { conn.send(accountObjectsResponse(request)) @@ -268,7 +270,7 @@ export function createMockRippled(port) { } }) - mock.on('request_account_info', function(request, conn) { + mock.on('request_account_info', function (request, conn) { assert.strictEqual(request.command, 'account_info') if (request.account === addresses.ACCOUNT) { conn.send(createResponse(request, fixtures.account_info.normal)) @@ -319,7 +321,7 @@ export function createMockRippled(port) { } }) - mock.on('request_ledger', function(request, conn) { + mock.on('request_ledger', function (request, conn) { assert.strictEqual(request.command, 'ledger') if (request.ledger_index === 34) { conn.send(createLedgerResponse(request, fixtures.ledger.notFound)) @@ -362,7 +364,7 @@ export function createMockRippled(port) { } }) - mock.on('request_ledger_data', function(request, conn) { + mock.on('request_ledger_data', function (request, conn) { assert.strictEqual(request.command, 'ledger_data') if (request.marker) { conn.send(createResponse(request, fixtures.ledger_data.last_page)) @@ -371,7 +373,7 @@ export function createMockRippled(port) { } }) - mock.on('request_ledger_entry', function(request, conn) { + mock.on('request_ledger_entry', function (request, conn) { assert.strictEqual(request.command, 'ledger_entry') if ( request.index === @@ -393,7 +395,7 @@ export function createMockRippled(port) { } }) - mock.on('request_ping', function(request, conn) { + mock.on('request_ping', function (request, conn) { // NOTE: We give the response a timeout of 2 second, so that tests can // set their timeout threshold to greater than or less than this number // to test timeouts. @@ -408,7 +410,7 @@ export function createMockRippled(port) { }, 1000 * 2) }) - mock.on('request_tx', function(request, conn) { + mock.on('request_tx', function (request, conn) { assert.strictEqual(request.command, 'tx') if (request.transaction === hashes.VALID_TRANSACTION_HASH) { conn.send(createResponse(request, fixtures.tx.Payment)) @@ -588,7 +590,7 @@ export function createMockRippled(port) { } }) - mock.on('request_submit', function(request, conn) { + mock.on('request_submit', function (request, conn) { assert.strictEqual(request.command, 'submit') if (request.tx_blob === 'BAD') { conn.send(createResponse(request, fixtures.submit.failure)) @@ -597,12 +599,12 @@ export function createMockRippled(port) { } }) - mock.on('request_submit_multisigned', function(request, conn) { + mock.on('request_submit_multisigned', function (request, conn) { assert.strictEqual(request.command, 'submit_multisigned') conn.send(createResponse(request, fixtures.submit.success)) }) - mock.on('request_account_lines', function(request, conn) { + mock.on('request_account_lines', function (request, conn) { if (request.account === addresses.ACCOUNT) { conn.send(accountLinesResponse.normal(request)) } else if (request.account === addresses.OTHER_ACCOUNT) { @@ -616,7 +618,7 @@ export function createMockRippled(port) { } }) - mock.on('request_account_tx', function(request, conn) { + mock.on('request_account_tx', function (request, conn) { if (request.account === addresses.ACCOUNT) { conn.send(transactionsResponse(request)) } else if (request.account === addresses.OTHER_ACCOUNT) { @@ -626,7 +628,7 @@ export function createMockRippled(port) { } }) - mock.on('request_account_offers', function(request, conn) { + mock.on('request_account_offers', function (request, conn) { if (request.account === addresses.ACCOUNT) { conn.send(fixtures.account_offers(request)) } else { @@ -636,7 +638,7 @@ export function createMockRippled(port) { let requestsCache = undefined - mock.on('request_book_offers', function(request, conn) { + mock.on('request_book_offers', function (request, conn) { if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') { conn.send(createResponse(request, fixtures.book_offers.xrp_usd)) } else if ( @@ -687,7 +689,7 @@ export function createMockRippled(port) { } }) - mock.on('request_ripple_path_find', function(request, conn) { + mock.on('request_ripple_path_find', function (request, conn) { let response = null if (request.subcommand === 'close') { // for path_find command @@ -775,7 +777,7 @@ export function createMockRippled(port) { conn.send(response) }) - mock.on('request_gateway_balances', function(request, conn) { + mock.on('request_gateway_balances', function (request, conn) { if (request.ledger_index === 123456) { conn.send(createResponse(request, fixtures.unsubscribe)) } else { diff --git a/test/rangeset-test.ts b/test/rangeset-test.ts index aa10898a..0849846e 100644 --- a/test/rangeset-test.ts +++ b/test/rangeset-test.ts @@ -2,8 +2,8 @@ import assert from 'assert' import {RippleAPI} from 'ripple-api' const RangeSet = RippleAPI._PRIVATE.RangeSet -describe('RangeSet', function() { - it('addRange()/addValue()', function() { +describe('RangeSet', function () { + it('addRange()/addValue()', function () { const r = new RangeSet() r.addRange(4, 5) @@ -14,19 +14,19 @@ describe('RangeSet', function() { assert.deepEqual(r.serialize(), '1-5,7-10') }) - it('addValue()/addRange() -- malformed', function() { + it('addValue()/addRange() -- malformed', function () { const r = new RangeSet() - assert.throws(function() { + assert.throws(function () { r.addRange(2, 1) }) }) - it('parseAndAddRanges()', function() { + it('parseAndAddRanges()', function () { const r = new RangeSet() r.parseAndAddRanges('4-5,7-10,1-2,3-3') assert.deepEqual(r.serialize(), '1-5,7-10') }) - it('parseAndAddRanges() -- single ledger', function() { + it('parseAndAddRanges() -- single ledger', function () { const r = new RangeSet() r.parseAndAddRanges('3') @@ -52,7 +52,7 @@ describe('RangeSet', function() { assert(!r.containsRange(0, 3)) }) - it('containsValue()', function() { + it('containsValue()', function () { const r = new RangeSet() r.addRange(32570, 11005146) @@ -68,7 +68,7 @@ describe('RangeSet', function() { assert.strictEqual(r.containsValue(12000000), false) }) - it('reset()', function() { + it('reset()', function () { const r = new RangeSet() r.addRange(4, 5) diff --git a/test/ripple-api-test-private.ts b/test/ripple-api-test-private.ts index 1c712d01..c6bfb52a 100644 --- a/test/ripple-api-test-private.ts +++ b/test/ripple-api-test-private.ts @@ -15,46 +15,46 @@ assert.options.strict = true // how long before each test case times out const TIMEOUT = 20000 -describe('RippleAPI', function() { +describe('RippleAPI', function () { this.timeout(TIMEOUT) beforeEach(setupAPI.setup) afterEach(setupAPI.teardown) - it('RippleAPI - implicit server port', function() { + it('RippleAPI - implicit server port', function () { new RippleAPI({server: 'wss://s1.ripple.com'}) }) - it('RippleAPI invalid options', function() { + it('RippleAPI invalid options', function () { // @ts-ignore - This is intentionally invalid assert.throws(() => new RippleAPI({invalid: true})) }) - it('RippleAPI valid options', function() { + it('RippleAPI valid options', function () { const api = new RippleAPI({server: 'wss://s:1'}) const privateConnectionUrl = (api.connection as any)._url assert.deepEqual(privateConnectionUrl, 'wss://s:1') }) - it('RippleAPI invalid server uri', function() { + it('RippleAPI invalid server uri', function () { assert.throws(() => new RippleAPI({server: 'wss//s:1'})) }) - xit('RippleAPI connect() times out after 2 seconds', function() { + xit('RippleAPI connect() times out after 2 seconds', function () { // TODO: Use a timer mock like https://jestjs.io/docs/en/timer-mocks // to test that connect() times out after 2 seconds. }) - it('ledger closed event', function(done) { - this.api.on('ledger', message => { + it('ledger closed event', function (done) { + this.api.on('ledger', (message) => { assertResultMatch(message, responses.ledgerEvent, 'ledgerEvent') done() }) this.api.connection._ws.emit('message', JSON.stringify(ledgerClosed)) }) - describe('[private] schema-validator', function() { - it('valid', function() { - assert.doesNotThrow(function() { + describe('[private] schema-validator', function () { + it('valid', function () { + assert.doesNotThrow(function () { schemaValidator.schemaValidate( 'hash256', '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A0F' @@ -62,27 +62,27 @@ describe('RippleAPI', function() { }) }) - it('invalid', function() { - assert.throws(function() { + it('invalid', function () { + assert.throws(function () { schemaValidator.schemaValidate('hash256', 'invalid') }, this.api.errors.ValidationError) }) - it('invalid - empty value', function() { - assert.throws(function() { + it('invalid - empty value', function () { + assert.throws(function () { schemaValidator.schemaValidate('hash256', '') }, this.api.errors.ValidationError) }) - it('schema not found error', function() { - assert.throws(function() { + it('schema not found error', function () { + assert.throws(function () { schemaValidator.schemaValidate('unexisting', 'anything') }, /no schema/) }) }) - describe('[private] validator', function() { - it('validateLedgerRange', function() { + describe('[private] validator', function () { + it('validateLedgerRange', function () { const options = { minLedgerVersion: 20000, maxLedgerVersion: 10000 @@ -95,7 +95,7 @@ describe('RippleAPI', function() { ) }) - it('secret', function() { + it('secret', function () { function validateSecret(secret) { validate.sign({txJSON: '', secret}) } diff --git a/test/ripple-api-test.ts b/test/ripple-api-test.ts index ce8f38b2..f8b12e6e 100644 --- a/test/ripple-api-test.ts +++ b/test/ripple-api-test.ts @@ -21,7 +21,7 @@ import {getAllPublicMethods, loadTestSuites} from './utils' * - Type the API object under test and catch typing issues (currently untyped). * - Sets the stage for more cleanup, like moving test-specific fixtures closer to their tests. */ -describe('RippleAPI [Test Runner]', function() { +describe('RippleAPI [Test Runner]', function () { beforeEach(setupAPI.setup) afterEach(setupAPI.teardown) @@ -35,7 +35,7 @@ describe('RippleAPI [Test Runner]', function() { // Run each test that does not use an address. for (const [testName, fn] of tests) { if (fn.length === 1) { - it(testName, function() { + it(testName, function () { return fn(this.api, addresses.ACCOUNT) }) } @@ -44,7 +44,7 @@ describe('RippleAPI [Test Runner]', function() { describe(`[Classic Address]`, () => { for (const [testName, fn] of tests) { if (fn.length === 2) { - it(testName, function() { + it(testName, function () { return fn(this.api, addresses.ACCOUNT) }) } @@ -55,7 +55,7 @@ describe('RippleAPI [Test Runner]', function() { describe(`[X-address]`, () => { for (const [testName, fn] of tests) { if (fn.length === 2) { - it(testName, function() { + it(testName, function () { return fn(this.api, addresses.ACCOUNT_X) }) } @@ -66,7 +66,7 @@ describe('RippleAPI [Test Runner]', function() { } // Report any missing tests. - const allTestedMethods = new Set(allTestSuites.map(s => s.name)) + const allTestedMethods = new Set(allTestSuites.map((s) => s.name)) for (const methodName of allPublicMethods) { if (!allTestedMethods.has(methodName)) { // TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures. diff --git a/test/setup-api-web.ts b/test/setup-api-web.ts index d5698b4c..fe52c18e 100644 --- a/test/setup-api-web.ts +++ b/test/setup-api-web.ts @@ -14,7 +14,7 @@ function setup(this: any, port_ = port) { data: {openOnOtherPort: true} }) }) - .then(got => { + .then((got) => { return new Promise((resolve, reject) => { this.api = new RippleAPI({server: baseUrl + got.port}) this.api @@ -35,7 +35,7 @@ function setup(this: any, port_ = port) { } function setupBroadcast(this: any) { - const servers = [port, port + 1].map(port_ => baseUrl + port_) + const servers = [port, port + 1].map((port_) => baseUrl + port_) this.api = new RippleAPIBroadcast(servers) return new Promise((resolve, reject) => { this.api diff --git a/test/setup-api.ts b/test/setup-api.ts index 82828a76..95bb70ca 100644 --- a/test/setup-api.ts +++ b/test/setup-api.ts @@ -23,8 +23,8 @@ function setupMockRippledConnection(testcase, port) { function setupMockRippledConnectionForBroadcast(testcase, ports) { return new Promise((resolve, reject) => { - const servers = ports.map(port => 'ws://localhost:' + port) - testcase.mocks = ports.map(port => createMockRippled(port)) + const servers = ports.map((port) => 'ws://localhost:' + port) + testcase.mocks = ports.map((port) => createMockRippled(port)) testcase.api = new RippleAPIBroadcast(servers) testcase.api .connect() @@ -37,13 +37,13 @@ function setupMockRippledConnectionForBroadcast(testcase, ports) { } function setup(this: any) { - return getFreePort().then(port => { + return getFreePort().then((port) => { return setupMockRippledConnection(this, port) }) } function setupBroadcast(this: any) { - return Promise.all([getFreePort(), getFreePort()]).then(ports => { + return Promise.all([getFreePort(), getFreePort()]).then((ports) => { return setupMockRippledConnectionForBroadcast(this, ports) }) } @@ -55,7 +55,7 @@ function teardown(this: any, done) { if (this.mockRippled !== undefined) { this.mockRippled.close() } else { - this.mocks.forEach(mock => mock.close()) + this.mocks.forEach((mock) => mock.close()) } setImmediate(done) }) diff --git a/test/shamap-test.ts b/test/shamap-test.ts index cfeedccb..e1d125ef 100644 --- a/test/shamap-test.ts +++ b/test/shamap-test.ts @@ -26,9 +26,9 @@ function fillShamapTest(shamap: any, keys: string[], hashes: string[]) { } } -describe('SHAMap', function() { - describe('#addItem', function() { - it('will add new nodes to v1', function() { +describe('SHAMap', function () { + describe('#addItem', function () { + it('will add new nodes to v1', function () { var keys = [ 'b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', 'b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', diff --git a/test/utils.ts b/test/utils.ts index bac10a70..1d4da715 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -98,14 +98,14 @@ export function getFreePort() { return new Promise((resolve, reject) => { const server = net.createServer() let port - server.on('listening', function() { + server.on('listening', function () { port = (server.address() as any).port server.close() }) - server.on('close', function() { + server.on('close', function () { resolve(port) }) - server.on('error', function(error) { + server.on('error', function (error) { reject(error) }) server.listen(0) @@ -118,7 +118,7 @@ export function getAllPublicMethods(api: RippleAPI) { ...Object.getOwnPropertyNames(api), ...Object.getOwnPropertyNames(RippleAPI.prototype) ]) - ).filter(key => !key.startsWith('_')) + ).filter((key) => !key.startsWith('_')) } export function loadTestSuites(): LoadedTestSuite[] { @@ -126,7 +126,7 @@ export function loadTestSuites(): LoadedTestSuite[] { encoding: 'utf8' }) return allTests - .map(methodName => { + .map((methodName) => { if (methodName.startsWith('.DS_Store')) { return null }