style: yarn format (run prettier) (#1327)

This commit is contained in:
Elliot Lee
2020-11-12 11:49:53 -08:00
committed by GitHub
parent 9e96fa3473
commit 4eb64b5e72
56 changed files with 480 additions and 447 deletions

View File

@@ -155,7 +155,7 @@ class RippleAPI extends EventEmitter {
const serverURL = options.server const serverURL = options.server
if (serverURL !== undefined) { if (serverURL !== undefined) {
this.connection = new Connection(serverURL, options) this.connection = new Connection(serverURL, options)
this.connection.on('ledgerClosed', message => { this.connection.on('ledgerClosed', (message) => {
this.emit('ledger', formatLedgerClose(message)) this.emit('ledger', formatLedgerClose(message))
}) })
this.connection.on('error', (errorCode, errorMessage, data) => { this.connection.on('error', (errorCode, errorMessage, data) => {
@@ -164,7 +164,7 @@ class RippleAPI extends EventEmitter {
this.connection.on('connected', () => { this.connection.on('connected', () => {
this.emit('connected') this.emit('connected')
}) })
this.connection.on('disconnected', code => { this.connection.on('disconnected', (code) => {
let finalCode = 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 // 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 // 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close

View File

@@ -9,38 +9,38 @@ class RippleAPIBroadcast extends RippleAPI {
super(options) super(options)
const apis: RippleAPI[] = servers.map( const apis: RippleAPI[] = servers.map(
server => new RippleAPI(_.assign({}, options, {server})) (server) => new RippleAPI(_.assign({}, options, {server}))
) )
// exposed for testing // exposed for testing
this._apis = apis this._apis = apis
this.getMethodNames().forEach(name => { this.getMethodNames().forEach((name) => {
this[name] = function () { this[name] = function () {
// eslint-disable-line no-loop-func // 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 // connection methods must be overridden to apply to all api instances
this.connect = async function () { this.connect = async function () {
await Promise.all(apis.map(api => api.connect())) await Promise.all(apis.map((api) => api.connect()))
} }
this.disconnect = async function () { this.disconnect = async function () {
await Promise.all(apis.map(api => api.disconnect())) await Promise.all(apis.map((api) => api.disconnect()))
} }
this.isConnected = function () { this.isConnected = function () {
return apis.map(api => api.isConnected()).every(Boolean) return apis.map((api) => api.isConnected()).every(Boolean)
} }
// synchronous methods are all passed directly to the first api instance // synchronous methods are all passed directly to the first api instance
const defaultAPI = apis[0] const defaultAPI = apis[0]
const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash'] const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash']
syncMethods.forEach(name => { syncMethods.forEach((name) => {
this[name] = defaultAPI[name].bind(defaultAPI) this[name] = defaultAPI[name].bind(defaultAPI)
}) })
apis.forEach(api => { apis.forEach((api) => {
api.on('ledger', this.onLedgerEvent.bind(this)) api.on('ledger', this.onLedgerEvent.bind(this))
api.on('error', (errorCode, errorMessage, data) => api.on('error', (errorCode, errorMessage, data) =>
this.emit('error', errorCode, errorMessage, data) this.emit('error', errorCode, errorMessage, data)

View File

@@ -120,7 +120,7 @@ function createWebSocket(url: string, config: ConnectionOptions): WebSocket {
*/ */
function websocketSendAsync(ws: WebSocket, message: string) { function websocketSendAsync(ws: WebSocket, message: string) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
ws.send(message, undefined, error => { ws.send(message, undefined, (error) => {
if (error) { if (error) {
reject(new DisconnectedError(error.message, error)) reject(new DisconnectedError(error.message, error))
} else { } else {
@@ -390,7 +390,7 @@ export class Connection extends EventEmitter {
*/ */
private _heartbeat = () => { private _heartbeat = () => {
return this.request({command: 'ping'}).catch(() => { return this.request({command: 'ping'}).catch(() => {
this.reconnect().catch(error => { this.reconnect().catch((error) => {
this.emit('error', 'reconnect', error.message, error) this.emit('error', 'reconnect', error.message, error)
}) })
}) })
@@ -504,11 +504,11 @@ export class Connection extends EventEmitter {
clearTimeout(connectionTimeoutID) clearTimeout(connectionTimeoutID)
// Add new, long-term connected listeners for messages and errors // Add new, long-term connected listeners for messages and errors
this._ws.on('message', (message: string) => this._onMessage(message)) 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) this.emit('error', 'websocket', error.message, error)
) )
// Handle a closed connection: reconnect if it was unexpected // Handle a closed connection: reconnect if it was unexpected
this._ws.once('close', code => { this._ws.once('close', (code) => {
this._clearHeartbeatInterval() this._clearHeartbeatInterval()
this._requestManager.rejectAll( this._requestManager.rejectAll(
new DisconnectedError('websocket was closed') new DisconnectedError('websocket was closed')
@@ -524,7 +524,7 @@ export class Connection extends EventEmitter {
// Start the reconnect timeout, but set it to `this._reconnectTimeoutID` // Start the reconnect timeout, but set it to `this._reconnectTimeoutID`
// so that we can cancel one in-progress on disconnect. // so that we can cancel one in-progress on disconnect.
this._reconnectTimeoutID = setTimeout(() => { this._reconnectTimeoutID = setTimeout(() => {
this.reconnect().catch(error => { this.reconnect().catch((error) => {
this.emit('error', 'reconnect', error.message, error) this.emit('error', 'reconnect', error.message, error)
}) })
}, retryTimeout) }, retryTimeout)
@@ -558,8 +558,8 @@ export class Connection extends EventEmitter {
if (this._state === WebSocket.CLOSED || !this._ws) { if (this._state === WebSocket.CLOSED || !this._ws) {
return Promise.resolve(undefined) return Promise.resolve(undefined)
} }
return new Promise(resolve => { return new Promise((resolve) => {
this._ws.once('close', code => resolve(code)) this._ws.once('close', (code) => resolve(code))
// Connection already has a disconnect handler for the disconnect logic. // Connection already has a disconnect handler for the disconnect logic.
// Just close the websocket manually (with our "intentional" code) to // Just close the websocket manually (with our "intentional" code) to
// trigger that. // trigger that.
@@ -635,7 +635,7 @@ export class Connection extends EventEmitter {
timeout || this._config.timeout timeout || this._config.timeout
) )
this._trace('send', message) this._trace('send', message)
websocketSendAsync(this._ws, message).catch(error => { websocketSendAsync(this._ws, message).catch((error) => {
this._requestManager.reject(id, error) this._requestManager.reject(id, error)
}) })

View File

@@ -36,10 +36,7 @@ const addressToHex = (address: string): string => {
const currencyToHex = (currency: string): string => { const currencyToHex = (currency: string): string => {
if (currency.length === 3) { if (currency.length === 3) {
const bytes = new Array(20 + 1) const bytes = new Array(20 + 1).join('0').split('').map(parseFloat)
.join('0')
.split('')
.map(parseFloat)
bytes[12] = currency.charCodeAt(0) & 0xff bytes[12] = currency.charCodeAt(0) & 0xff
bytes[13] = currency.charCodeAt(1) & 0xff bytes[13] = currency.charCodeAt(1) & 0xff
bytes[14] = currency.charCodeAt(2) & 0xff bytes[14] = currency.charCodeAt(2) & 0xff
@@ -163,7 +160,7 @@ export const computeTrustlineHash = (
export const computeTransactionTreeHash = (transactions: any[]): string => { export const computeTransactionTreeHash = (transactions: any[]): string => {
const shamap = new SHAMap() const shamap = new SHAMap()
transactions.forEach(txJSON => { transactions.forEach((txJSON) => {
const txBlobHex = encode(txJSON) const txBlobHex = encode(txJSON)
const metaHex = encode(txJSON.metaData) const metaHex = encode(txJSON.metaData)
const txHash = computeBinaryTransactionHash(txBlobHex) const txHash = computeBinaryTransactionHash(txBlobHex)
@@ -177,7 +174,7 @@ export const computeTransactionTreeHash = (transactions: any[]): string => {
export const computeStateTreeHash = (entries: any[]): string => { export const computeStateTreeHash = (entries: any[]): string => {
const shamap = new SHAMap() const shamap = new SHAMap()
entries.forEach(ledgerEntry => { entries.forEach((ledgerEntry) => {
const data = encode(ledgerEntry) const data = encode(ledgerEntry)
shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE) shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE)
}) })

View File

@@ -5,7 +5,7 @@ type Interval = [number, number]
function mergeIntervals(intervals: Interval[]): Interval[] { function mergeIntervals(intervals: Interval[]): Interval[] {
const stack: Interval[] = [[-Infinity, -Infinity]] const stack: Interval[] = [[-Infinity, -Infinity]]
_.sortBy(intervals, x => x[0]).forEach(interval => { _.sortBy(intervals, (x) => x[0]).forEach((interval) => {
const lastInterval: Interval = stack.pop()! const lastInterval: Interval = stack.pop()!
if (interval[0] <= lastInterval[1] + 1) { if (interval[0] <= lastInterval[1] + 1) {
stack.push([lastInterval[0], Math.max(interval[1], lastInterval[1])]) stack.push([lastInterval[0], Math.max(interval[1], lastInterval[1])])
@@ -30,7 +30,7 @@ class RangeSet {
serialize() { serialize() {
return this.ranges return this.ranges
.map(range => range[0].toString() + '-' + range[1].toString()) .map((range) => range[0].toString() + '-' + range[1].toString())
.join(',') .join(',')
} }
@@ -45,14 +45,14 @@ class RangeSet {
parseAndAddRanges(rangesString: string) { parseAndAddRanges(rangesString: string) {
const rangeStrings = rangesString.split(',') const rangeStrings = rangesString.split(',')
_.forEach(rangeStrings, rangeString => { _.forEach(rangeStrings, (rangeString) => {
const range = rangeString.split('-').map(Number) const range = rangeString.split('-').map(Number)
this.addRange(range[0], range.length === 1 ? range[0] : range[1]) this.addRange(range[0], range.length === 1 ? range[0] : range[1])
}) })
} }
containsRange(start: number, end: number) { 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) { containsValue(value: number) {

View File

@@ -123,8 +123,8 @@ function loadSchemas() {
require('./schemas/input/verify-payment-channel-claim.json'), require('./schemas/input/verify-payment-channel-claim.json'),
require('./schemas/input/combine.json') require('./schemas/input/combine.json')
] ]
const titles = schemas.map(schema => schema.title) const titles = schemas.map((schema) => schema.title)
const duplicates = _.keys(_.pickBy(_.countBy(titles), count => count > 1)) const duplicates = _.keys(_.pickBy(_.countBy(titles), (count) => count > 1))
assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates) assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates)
const validator = new Validator() const validator = new Validator()
// Register custom format validators that ignore undefined instances // Register custom format validators that ignore undefined instances
@@ -155,7 +155,9 @@ function loadSchemas() {
} }
// Register under the root URI '/' // Register under the root URI '/'
_.forEach(schemas, schema => validator.addSchema(schema, '/' + schema.title)) _.forEach(schemas, (schema) =>
validator.addSchema(schema, '/' + schema.title)
)
return validator return validator
} }

View File

@@ -41,7 +41,7 @@ function renameKeys(object, mapping) {
} }
function getServerInfo(this: RippleAPI): Promise<GetServerInfoResponse> { function getServerInfo(this: RippleAPI): Promise<GetServerInfoResponse> {
return this.request('server_info').then(response => { return this.request('server_info').then((response) => {
const info = convertKeysFromSnakeCaseToCamelCase(response.info) const info = convertKeysFromSnakeCaseToCamelCase(response.info)
renameKeys(info, {hostid: 'hostID'}) renameKeys(info, {hostid: 'hostID'})
if (info.validatedLedger) { if (info.validatedLedger) {

View File

@@ -134,7 +134,7 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
// taking this out of function leads to error in PhantomJS // taking this out of function leads to error in PhantomJS
const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g
if (FINDSNAKE.test(key)) { 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) result[newKey] = convertKeysFromSnakeCaseToCamelCase(value)
return result return result

View File

@@ -37,11 +37,11 @@ class WSWrapper extends EventEmitter {
this.emit('open') this.emit('open')
} }
this._ws.onerror = error => { this._ws.onerror = (error) => {
this.emit('error', error) this.emit('error', error)
} }
this._ws.onmessage = message => { this._ws.onmessage = (message) => {
this.emit('message', message.data) this.emit('message', message.data)
} }
} }

View File

@@ -24,7 +24,7 @@ function formatBalanceSheet(balanceSheet): GetBalanceSheet {
if (!_.isUndefined(balanceSheet.balances)) { if (!_.isUndefined(balanceSheet.balances)) {
result.balances = [] result.balances = []
_.forEach(balanceSheet.balances, (balances, counterparty) => { _.forEach(balanceSheet.balances, (balances, counterparty) => {
_.forEach(balances, balance => { _.forEach(balances, (balance) => {
result.balances.push(Object.assign({counterparty}, balance)) result.balances.push(Object.assign({counterparty}, balance))
}) })
}) })
@@ -32,7 +32,7 @@ function formatBalanceSheet(balanceSheet): GetBalanceSheet {
if (!_.isUndefined(balanceSheet.assets)) { if (!_.isUndefined(balanceSheet.assets)) {
result.assets = [] result.assets = []
_.forEach(balanceSheet.assets, (assets, counterparty) => { _.forEach(balanceSheet.assets, (assets, counterparty) => {
_.forEach(assets, balance => { _.forEach(assets, (balance) => {
result.assets.push(Object.assign({counterparty}, balance)) result.assets.push(Object.assign({counterparty}, balance))
}) })
}) })

View File

@@ -67,11 +67,11 @@ function getBalances(
getLedgerVersionHelper( getLedgerVersionHelper(
this.connection, this.connection,
options.ledgerVersion options.ledgerVersion
).then(ledgerVersion => ).then((ledgerVersion) =>
utils.getXRPBalance(this.connection, address, ledgerVersion) utils.getXRPBalance(this.connection, address, ledgerVersion)
), ),
this.getTrustlines(address, options) this.getTrustlines(address, options)
]).then(results => ]).then((results) =>
formatBalances(options, {xrp: results[0], trustlines: results[1]}) formatBalances(options, {xrp: results[0], trustlines: results[1]})
) )
} }

View File

@@ -116,11 +116,11 @@ export async function getOrderbook(
// 3. Return Formatted Response // 3. Return Formatted Response
const directOffers = _.flatMap( const directOffers = _.flatMap(
directOfferResults, directOfferResults,
directOfferResult => directOfferResult.offers (directOfferResult) => directOfferResult.offers
) )
const reverseOffers = _.flatMap( const reverseOffers = _.flatMap(
reverseOfferResults, reverseOfferResults,
reverseOfferResult => reverseOfferResult.offers (reverseOfferResult) => reverseOfferResult.offers
) )
return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers]) return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers])
} }

View File

@@ -15,12 +15,12 @@ function formatResponse(
): FormattedAccountOrder[] { ): FormattedAccountOrder[] {
let orders: FormattedAccountOrder[] = [] let orders: FormattedAccountOrder[] = []
for (const response of responses) { for (const response of responses) {
const offers = response.offers.map(offer => { const offers = response.offers.map((offer) => {
return parseAccountOrder(address, offer) return parseAccountOrder(address, offer)
}) })
orders = orders.concat(offers) orders = orders.concat(offers)
} }
return _.sortBy(orders, order => order.properties.sequence) return _.sortBy(orders, (order) => order.properties.sequence)
} }
export default async function getOrders( export default async function getOrders(

View File

@@ -4,8 +4,8 @@ import {Amount, RippledAmount} from '../../common/types/objects'
import {Path, GetPaths, RippledPathsResponse} from '../pathfind-types' import {Path, GetPaths, RippledPathsResponse} from '../pathfind-types'
function parsePaths(paths) { function parsePaths(paths) {
return paths.map(steps => return paths.map((steps) =>
steps.map(step => _.omit(step, ['type', 'type_hex'])) steps.map((step) => _.omit(step, ['type', 'type_hex']))
) )
} }
@@ -58,7 +58,7 @@ function parsePathfind(pathfindResult: RippledPathsResponse): GetPaths {
const sourceAddress = pathfindResult.source_account const sourceAddress = pathfindResult.source_account
const destinationAddress = pathfindResult.destination_account const destinationAddress = pathfindResult.destination_account
const destinationAmount = pathfindResult.destination_amount const destinationAmount = pathfindResult.destination_amount
return pathfindResult.alternatives.map(alt => return pathfindResult.alternatives.map((alt) =>
parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt) parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt)
) )
} }

View File

@@ -6,7 +6,7 @@ import parseFields from './fields'
function getAccountRootModifiedNode(tx: any) { function getAccountRootModifiedNode(tx: any) {
const modifiedNodes = tx.meta.AffectedNodes.filter( const modifiedNodes = tx.meta.AffectedNodes.filter(
node => node.ModifiedNode.LedgerEntryType === 'AccountRoot' (node) => node.ModifiedNode.LedgerEntryType === 'AccountRoot'
) )
assert.ok(modifiedNodes.length === 1) assert.ok(modifiedNodes.length === 1)
return modifiedNodes[0].ModifiedNode return modifiedNodes[0].ModifiedNode

View File

@@ -42,14 +42,14 @@ function removeEmptyCounterparty(amount) {
} }
function removeEmptyCounterpartyInBalanceChanges(balanceChanges) { function removeEmptyCounterpartyInBalanceChanges(balanceChanges) {
_.forEach(balanceChanges, changes => { _.forEach(balanceChanges, (changes) => {
_.forEach(changes, removeEmptyCounterparty) _.forEach(changes, removeEmptyCounterparty)
}) })
} }
function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) { function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) {
_.forEach(orderbookChanges, changes => { _.forEach(orderbookChanges, (changes) => {
_.forEach(changes, change => { _.forEach(changes, (change) => {
_.forEach(change, removeEmptyCounterparty) _.forEach(change, removeEmptyCounterparty)
}) })
}) })
@@ -132,7 +132,7 @@ function parseMemos(tx: any): Array<Memo> | undefined {
if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) { if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) {
return undefined return undefined
} }
return tx.Memos.map(m => { return tx.Memos.map((m) => {
return common.removeUndefined({ return common.removeUndefined({
type: m.Memo.parsed_memo_type || hexToString(m.Memo.MemoType), type: m.Memo.parsed_memo_type || hexToString(m.Memo.MemoType),
format: m.Memo.parsed_memo_format || hexToString(m.Memo.MemoFormat), format: m.Memo.parsed_memo_format || hexToString(m.Memo.MemoFormat),

View File

@@ -62,7 +62,7 @@ function requestPathFind(
request.destination_amount.issuer = request.destination_account request.destination_amount.issuer = request.destination_account
} }
if (pathfind.source.currencies && pathfind.source.currencies.length > 0) { 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) 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( function addDirectXrpPath(
@@ -116,7 +116,7 @@ function conditionallyAddDirectXRPPath(
) { ) {
return Promise.resolve(paths) return Promise.resolve(paths)
} }
return getXRPBalance(connection, address, undefined).then(xrpBalance => return getXRPBalance(connection, address, undefined).then((xrpBalance) =>
addDirectXrpPath(paths, xrpBalance) addDirectXrpPath(paths, xrpBalance)
) )
} }
@@ -130,7 +130,7 @@ function filterSourceFundsLowPaths(
pathfind.destination.amount.value === undefined && pathfind.destination.amount.value === undefined &&
paths.alternatives paths.alternatives
) { ) {
paths.alternatives = _.filter(paths.alternatives, alt => { paths.alternatives = _.filter(paths.alternatives, (alt) => {
if (!alt.source_amount) { if (!alt.source_amount) {
return false return false
} }
@@ -191,11 +191,11 @@ function getPaths(this: RippleAPI, pathfind: PathFind): Promise<GetPaths> {
const address = pathfind.source.address const address = pathfind.source.address
return requestPathFind(this.connection, pathfind) return requestPathFind(this.connection, pathfind)
.then(paths => .then((paths) =>
conditionallyAddDirectXRPPath(this.connection, address, paths) conditionallyAddDirectXRPPath(this.connection, address, paths)
) )
.then(paths => filterSourceFundsLowPaths(pathfind, paths)) .then((paths) => filterSourceFundsLowPaths(pathfind, paths))
.then(paths => formatResponse(pathfind, paths)) .then((paths) => formatResponse(pathfind, paths))
} }
export default getPaths export default getPaths

View File

@@ -48,13 +48,13 @@ function attachTransactionDate(
return connection return connection
.request(request) .request(request)
.then(data => { .then((data) => {
if (typeof data.ledger.close_time === 'number') { if (typeof data.ledger.close_time === 'number') {
return _.assign({date: data.ledger.close_time}, tx) return _.assign({date: data.ledger.close_time}, tx)
} }
throw new errors.UnexpectedError('Ledger missing close_time') throw new errors.UnexpectedError('Ledger missing close_time')
}) })
.catch(error => { .catch((error) => {
if (error instanceof errors.UnexpectedError) { if (error instanceof errors.UnexpectedError) {
throw error throw error
} }
@@ -95,11 +95,11 @@ function convertError(
options.minLedgerVersion, options.minLedgerVersion,
options.maxLedgerVersion options.maxLedgerVersion
) )
.then(hasCompleteLedgerRange => { .then((hasCompleteLedgerRange) => {
if (!hasCompleteLedgerRange) { if (!hasCompleteLedgerRange) {
return utils return utils
.isPendingLedgerVersion(connection, options.maxLedgerVersion) .isPendingLedgerVersion(connection, options.maxLedgerVersion)
.then(isPendingLedgerVersion => { .then((isPendingLedgerVersion) => {
return isPendingLedgerVersion return isPendingLedgerVersion
? new errors.PendingLedgerVersionError() ? new errors.PendingLedgerVersionError()
: new errors.MissingLedgerHistoryError() : new errors.MissingLedgerHistoryError()

View File

@@ -101,12 +101,12 @@ function formatPartialResponse(
options: TransactionsOptions, options: TransactionsOptions,
data data
) { ) {
const parse = tx => const parse = (tx) =>
parseAccountTxTransaction(tx, options.includeRawTransactions) parseAccountTxTransaction(tx, options.includeRawTransactions)
return { return {
marker: data.marker, marker: data.marker,
results: data.transactions results: data.transactions
.filter(tx => tx.validated) .filter((tx) => tx.validated)
.map(parse) .map(parse)
.filter(_.partial(transactionFilter, address, options)) .filter(_.partial(transactionFilter, address, options))
.filter(_.partial(orderFilter, options)) .filter(_.partial(orderFilter, options))
@@ -135,7 +135,7 @@ function getAccountTx(
return connection return connection
.request(request) .request(request)
.then(response => formatPartialResponse(address, options, response)) .then((response) => formatPartialResponse(address, options, response))
} }
function checkForLedgerGaps( function checkForLedgerGaps(
@@ -158,7 +158,7 @@ function checkForLedgerGaps(
return utils return utils
.hasCompleteLedgerRange(connection, minLedgerVersion, maxLedgerVersion) .hasCompleteLedgerRange(connection, minLedgerVersion, maxLedgerVersion)
.then(hasCompleteLedgerRange => { .then((hasCompleteLedgerRange) => {
if (!hasCompleteLedgerRange) { if (!hasCompleteLedgerRange) {
throw new errors.MissingLedgerHistoryError() throw new errors.MissingLedgerHistoryError()
} }
@@ -204,7 +204,7 @@ function getTransactions(
const defaults = {maxLedgerVersion: -1} const defaults = {maxLedgerVersion: -1}
if (options.start) { 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 ledgerVersion = tx.outcome.ledgerVersion
const bound = options.earliestFirst const bound = options.earliestFirst
? {minLedgerVersion: ledgerVersion} ? {minLedgerVersion: ledgerVersion}

View File

@@ -36,8 +36,8 @@ async function getTrustlines(
peer: options.counterparty peer: options.counterparty
}) })
// 3. Return Formatted Response // 3. Return Formatted Response
const trustlines = _.flatMap(responses, response => response.lines) const trustlines = _.flatMap(responses, (response) => response.lines)
return trustlines.map(parseAccountTrustline).filter(trustline => { return trustlines.map(parseAccountTrustline).filter((trustline) => {
return currencyFilter(options.currency || null, trustline) return currencyFilter(options.currency || null, trustline)
}) })
} }

View File

@@ -30,7 +30,7 @@ function getXRPBalance(
} }
return connection return connection
.request(request) .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 // If the marker is omitted from a response, you have reached the end
@@ -39,10 +39,10 @@ function getRecursiveRecur(
marker: string | undefined, marker: string | undefined,
limit: number limit: number
): Promise<Array<any>> { ): Promise<Array<any>> {
return getter(marker, limit).then(data => { return getter(marker, limit).then((data) => {
const remaining = limit - data.results.length const remaining = limit - data.results.length
if (remaining > 0 && data.marker !== undefined) { 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) data.results.concat(results)
) )
} }
@@ -118,7 +118,7 @@ function isPendingLedgerVersion(
): Promise<boolean> { ): Promise<boolean> {
return connection return connection
.getLedgerVersion() .getLedgerVersion()
.then(ledgerVersion => ledgerVersion < (maxLedgerVersion || 0)) .then((ledgerVersion) => ledgerVersion < (maxLedgerVersion || 0))
} }
function ensureLedgerVersion(this: RippleAPI, options: any): Promise<object> { function ensureLedgerVersion(this: RippleAPI, options: any): Promise<object> {
@@ -129,7 +129,7 @@ function ensureLedgerVersion(this: RippleAPI, options: any): Promise<object> {
) { ) {
return Promise.resolve(options) return Promise.resolve(options)
} }
return this.getLedgerVersion().then(ledgerVersion => return this.getLedgerVersion().then((ledgerVersion) =>
_.assign({}, options, {ledgerVersion}) _.assign({}, options, {ledgerVersion})
) )
} }

View File

@@ -38,7 +38,7 @@ function computeTransactionHash(
transactions = JSON.parse(ledger.rawTransactions) transactions = JSON.parse(ledger.rawTransactions)
} else if (ledger.transactions) { } else if (ledger.transactions) {
try { try {
transactions = ledger.transactions.map(tx => transactions = ledger.transactions.map((tx) =>
JSON.parse(tx.rawTransaction) JSON.parse(tx.rawTransaction)
) )
} catch (e) { } catch (e) {
@@ -60,7 +60,7 @@ function computeTransactionHash(
} }
return ledger.transactionHash return ledger.transactionHash
} }
const txs = _.map(transactions, tx => { const txs = _.map(transactions, (tx) => {
const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {}) const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {})
// rename `meta` back to `metaData` // rename `meta` back to `metaData`
const renameMeta = _.assign( const renameMeta = _.assign(

View File

@@ -24,7 +24,7 @@ function combine(signedTransactions: Array<string>): object {
// tests and this code handle it as an array of objects. Fix! // tests and this code handle it as an array of objects. Fix!
const txs: any[] = _.map(signedTransactions, binary.decode) const txs: any[] = _.map(signedTransactions, binary.decode)
const tx = _.omit(txs[0], 'Signers') 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( throw new utils.common.errors.ValidationError(
'txJSON is not the same for all signedTransactions' 'txJSON is not the same for all signedTransactions'
) )

View File

@@ -76,8 +76,8 @@ function applyAnyCounterpartyEncoding(payment: Payment): void {
// Convert blank counterparty to sender or receiver's address // Convert blank counterparty to sender or receiver's address
// (Ripple convention for 'any counterparty') // (Ripple convention for 'any counterparty')
// https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount // https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount
_.forEach([payment.source, payment.destination], adjustment => { _.forEach([payment.source, payment.destination], (adjustment) => {
_.forEach(['amount', 'minAmount', 'maxAmount'], key => { _.forEach(['amount', 'minAmount', 'maxAmount'], (key) => {
if (isIOUWithoutCounterparty(adjustment[key])) { if (isIOUWithoutCounterparty(adjustment[key])) {
adjustment[key].counterparty = adjustment.address adjustment[key].counterparty = adjustment.address
} }
@@ -91,7 +91,8 @@ function createMaximalAmount(amount: Amount): Amount {
// Equivalent to '9999999999999999e80' but we cannot use that because sign() // Equivalent to '9999999999999999e80' but we cannot use that because sign()
// now checks that the encoded representation exactly matches the transaction // now checks that the encoded representation exactly matches the transaction
// as it was originally provided. // as it was originally provided.
const maxIOUValue = '999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000' const maxIOUValue =
'999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000'
let maxValue let maxValue
if (amount.currency === 'XRP') { if (amount.currency === 'XRP') {

View File

@@ -55,9 +55,7 @@ function setTransactionFields(
if (field.encoding === 'hex' && !field.length) { if (field.encoding === 'hex' && !field.length) {
// This is currently only used for Domain field // This is currently only used for Domain field
value = Buffer.from(value, 'ascii') value = Buffer.from(value, 'ascii').toString('hex').toUpperCase()
.toString('hex')
.toUpperCase()
} }
txJSON[fieldName] = value txJSON[fieldName] = value

View File

@@ -52,10 +52,7 @@ function setCanonicalFlag(txJSON: TransactionJSON): void {
} }
function scaleValue(value, multiplier, extra = 0) { function scaleValue(value, multiplier, extra = 0) {
return new BigNumber(value) return new BigNumber(value).times(multiplier).plus(extra).toString()
.times(multiplier)
.plus(extra)
.toString()
} }
/** /**
@@ -119,7 +116,7 @@ function prepareTransaction(
'fee', 'fee',
'sequence' 'sequence'
] ]
const badFields = disallowedFieldsInTxJSON.filter(field => txJSON[field]) const badFields = disallowedFieldsInTxJSON.filter((field) => txJSON[field])
if (badFields.length) { if (badFields.length) {
return Promise.reject( return Promise.reject(
new ValidationError( new ValidationError(
@@ -236,7 +233,7 @@ function prepareTransaction(
instructions.maxLedgerVersionOffset !== undefined instructions.maxLedgerVersionOffset !== undefined
? instructions.maxLedgerVersionOffset ? instructions.maxLedgerVersionOffset
: 3 : 3
return api.connection.getLedgerVersion().then(ledgerVersion => { return api.connection.getLedgerVersion().then((ledgerVersion) => {
newTxJSON.LastLedgerSequence = ledgerVersion + offset newTxJSON.LastLedgerSequence = ledgerVersion + offset
return return
}) })
@@ -281,8 +278,8 @@ function prepareTransaction(
return Promise.resolve() return Promise.resolve()
} }
const cushion = api._feeCushion const cushion = api._feeCushion
return api.getFee(cushion).then(fee => { return api.getFee(cushion).then((fee) => {
return api.connection.getFeeRef().then(feeRef => { return api.connection.getFeeRef().then((feeRef) => {
const extraFee = const extraFee =
newTxJSON.TransactionType !== 'EscrowFinish' || newTxJSON.TransactionType !== 'EscrowFinish' ||
newTxJSON.Fulfillment === undefined newTxJSON.Fulfillment === undefined
@@ -347,9 +344,7 @@ function prepareTransaction(
} }
function convertStringToHex(string: string): string { function convertStringToHex(string: string): string {
return Buffer.from(string, 'utf8') return Buffer.from(string, 'utf8').toString('hex').toUpperCase()
.toString('hex')
.toUpperCase()
} }
function convertMemo(memo: Memo): {Memo: ApiMemo} { function convertMemo(memo: Memo): {Memo: ApiMemo} {

View File

@@ -8,11 +8,11 @@ import BigNumber from 'bignumber.js'
* - Check out "test/api/index.ts" for more information about the test runner. * - Check out "test/api/index.ts" for more information about the test runner.
*/ */
export default <TestSuite>{ export default <TestSuite>{
'works with a typical amount': async api => { 'works with a typical amount': async (api) => {
const xrp = api.dropsToXrp('2000000') const xrp = api.dropsToXrp('2000000')
assert.strictEqual(xrp, '2', '2 million drops equals 2 XRP') 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') let xrp = api.dropsToXrp('3456789')
assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP') assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP')
@@ -28,7 +28,7 @@ export default <TestSuite>{
xrp = api.dropsToXrp('1.00') xrp = api.dropsToXrp('1.00')
assert.strictEqual(xrp, '0.000001', '1.00 drops equals 0.000001 XRP') 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') let xrp = api.dropsToXrp('0')
assert.strictEqual(xrp, '0', '0 drops equals 0 XRP') assert.strictEqual(xrp, '0', '0 drops equals 0 XRP')
@@ -42,18 +42,18 @@ export default <TestSuite>{
xrp = api.dropsToXrp('000000000') xrp = api.dropsToXrp('000000000')
assert.strictEqual(xrp, '0', '000000000 drops equals 0 XRP') 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') const xrp = api.dropsToXrp('-2000000')
assert.strictEqual(xrp, '-2', '-2 million drops equals -2 XRP') 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.') let xrp = api.dropsToXrp('2000000.')
assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP') assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP')
xrp = api.dropsToXrp('-2000000.') xrp = api.dropsToXrp('-2000000.')
assert.strictEqual(xrp, '-2', '-2000000. drops equals -2 XRP') 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)) let xrp = api.dropsToXrp(new BigNumber(2000000))
assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP') assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP')
@@ -74,14 +74,14 @@ export default <TestSuite>{
'(BigNumber) -2,345,678 drops equals -2.345678 XRP' '(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. // This is not recommended. Use strings or BigNumber objects to avoid precision errors.
let xrp = api.dropsToXrp(2000000) let xrp = api.dropsToXrp(2000000)
assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP') assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP')
xrp = api.dropsToXrp(-2000000) xrp = api.dropsToXrp(-2000000)
assert.strictEqual(xrp, '-2', '(number) -2 million drops equals -2 XRP') 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(() => { assert.throws(() => {
api.dropsToXrp('1.2') api.dropsToXrp('1.2')
}, /has too many decimal places/) }, /has too many decimal places/)
@@ -90,7 +90,7 @@ export default <TestSuite>{
api.dropsToXrp('0.10') api.dropsToXrp('0.10')
}, /has too many decimal places/) }, /has too many decimal places/)
}, },
'throws with an invalid value': async api => { 'throws with an invalid value': async (api) => {
assert.throws(() => { assert.throws(() => {
api.dropsToXrp('FOO') api.dropsToXrp('FOO')
}, /invalid value/) }, /invalid value/)
@@ -107,7 +107,7 @@ export default <TestSuite>{
api.dropsToXrp('.') api.dropsToXrp('.')
}, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./) }, /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(() => { assert.throws(() => {
api.dropsToXrp('1.0.0') api.dropsToXrp('1.0.0')
}, /dropsToXrp: invalid value '1\.0\.0'/) }, /dropsToXrp: invalid value '1\.0\.0'/)

View File

@@ -267,16 +267,16 @@ export default <TestSuite>{
]) ])
const bidRates = orderbook.bids.map( const bidRates = orderbook.bids.map(
bid => bid.properties.makerExchangeRate (bid) => bid.properties.makerExchangeRate
) )
const askRates = orderbook.asks.map( const askRates = orderbook.asks.map(
ask => ask.properties.makerExchangeRate (ask) => ask.properties.makerExchangeRate
) )
// makerExchangeRate = quality = takerPays.value/takerGets.value // makerExchangeRate = quality = takerPays.value/takerGets.value
// so the best deal for the taker is the lowest makerExchangeRate // so the best deal for the taker is the lowest makerExchangeRate
// bids and asks should be sorted so that the best deals come first // bids and asks should be sorted so that the best deals come first
assert.deepEqual(bidRates.map(x => Number(x)).sort(), bidRates) assert.deepEqual(bidRates.map((x) => Number(x)).sort(), bidRates)
assert.deepEqual(askRates.map(x => Number(x)).sort(), askRates) assert.deepEqual(askRates.map((x) => Number(x)).sort(), askRates)
}) })
}, },
@@ -322,7 +322,7 @@ export default <TestSuite>{
]) ])
const orders = [...orderbook.bids, ...orderbook.asks] const orders = [...orderbook.bids, ...orderbook.asks]
orders.forEach(order => { orders.forEach((order) => {
const quantity = order.specification.quantity const quantity = order.specification.quantity
const totalPrice = order.specification.totalPrice const totalPrice = order.specification.totalPrice
const {base, counter} = requests.getOrderbook.normal const {base, counter} = requests.getOrderbook.normal
@@ -375,9 +375,11 @@ export default <TestSuite>{
...reverseOffers ...reverseOffers
]) ])
assert(orderbook.bids.every(bid => bid.specification.direction === 'buy'))
assert( 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')
) )
}) })
} }

View File

@@ -10,7 +10,7 @@ const {generateAddress: RESPONSE_FIXTURES} = responses
* - Check out "test/api/index.ts" for more information about the test runner. * - Check out "test/api/index.ts" for more information about the test runner.
*/ */
export default <TestSuite>{ export default <TestSuite>{
'generateAddress': async api => { 'generateAddress': async (api) => {
// GIVEN entropy of all zeros // GIVEN entropy of all zeros
function random() { function random() {
return new Array(16).fill(0) return new Array(16).fill(0)
@@ -25,7 +25,7 @@ export default <TestSuite>{
) )
}, },
'generateAddress invalid entropy': async api => { 'generateAddress invalid entropy': async (api) => {
assert.throws(() => { assert.throws(() => {
// GIVEN entropy of 1 byte // GIVEN entropy of 1 byte
function random() { function random() {
@@ -40,7 +40,7 @@ export default <TestSuite>{
}, api.errors.UnexpectedError) }, api.errors.UnexpectedError)
}, },
'generateAddress with no options object': async api => { 'generateAddress with no options object': async (api) => {
// GIVEN no options // GIVEN no options
// WHEN generating an address // WHEN generating an address
@@ -51,7 +51,7 @@ export default <TestSuite>{
assert(account.secret.startsWith('s'), 'Secret must start with `s`') 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 // GIVEN an empty options object
const options = {} const options = {}
@@ -63,7 +63,7 @@ export default <TestSuite>{
assert(account.secret.startsWith('s'), 'Secret must start with `s`') 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' // GIVEN we want to use 'ecdsa-secp256k1'
const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'} const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'}
@@ -84,7 +84,7 @@ export default <TestSuite>{
) )
}, },
'generateAddress with algorithm `ed25519`': async api => { 'generateAddress with algorithm `ed25519`': async (api) => {
// GIVEN we want to use 'ed25519' // GIVEN we want to use 'ed25519'
const options: GenerateAddressOptions = {algorithm: 'ed25519'} const options: GenerateAddressOptions = {algorithm: 'ed25519'}
@@ -100,7 +100,9 @@ export default <TestSuite>{
) )
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -114,7 +116,7 @@ export default <TestSuite>{
assert.deepEqual(account, responses.generateAddress) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -135,7 +137,9 @@ export default <TestSuite>{
}) })
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -150,7 +154,9 @@ export default <TestSuite>{
assert.deepEqual(account, responses.generateAddress) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -172,7 +178,9 @@ export default <TestSuite>{
}) })
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -192,7 +200,9 @@ export default <TestSuite>{
assert.deepEqual(account, response) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -215,7 +225,7 @@ export default <TestSuite>{
}) })
}, },
'generateAddress for test network use': async api => { 'generateAddress for test network use': async (api) => {
// GIVEN we want an address for test network use // GIVEN we want an address for test network use
const options: GenerateAddressOptions = {test: true} const options: GenerateAddressOptions = {test: true}

View File

@@ -9,7 +9,7 @@ import {GenerateAddressOptions} from '../../../src/offline/generate-address'
* - Check out "test/api/index.ts" for more information about the test runner. * - Check out "test/api/index.ts" for more information about the test runner.
*/ */
export default <TestSuite>{ export default <TestSuite>{
'generateXAddress': async api => { 'generateXAddress': async (api) => {
// GIVEN entropy of all zeros // GIVEN entropy of all zeros
function random() { function random() {
return new Array(16).fill(0) return new Array(16).fill(0)
@@ -24,7 +24,7 @@ export default <TestSuite>{
) )
}, },
'generateXAddress invalid entropy': async api => { 'generateXAddress invalid entropy': async (api) => {
assert.throws(() => { assert.throws(() => {
// GIVEN entropy of 1 byte // GIVEN entropy of 1 byte
function random() { function random() {
@@ -39,7 +39,7 @@ export default <TestSuite>{
}, api.errors.UnexpectedError) }, api.errors.UnexpectedError)
}, },
'generateXAddress with no options object': async api => { 'generateXAddress with no options object': async (api) => {
// GIVEN no options // GIVEN no options
// WHEN generating an X-address // WHEN generating an X-address
@@ -53,7 +53,7 @@ export default <TestSuite>{
assert(account.secret.startsWith('s'), 'Secrets start with s') 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 // GIVEN an empty options object
const options = {} const options = {}
@@ -68,7 +68,7 @@ export default <TestSuite>{
assert(account.secret.startsWith('s'), 'Secrets start with s') 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' // GIVEN we want to use 'ecdsa-secp256k1'
const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'} const options: GenerateAddressOptions = {algorithm: 'ecdsa-secp256k1'}
@@ -92,7 +92,7 @@ export default <TestSuite>{
) )
}, },
'generateXAddress with algorithm `ed25519`': async api => { 'generateXAddress with algorithm `ed25519`': async (api) => {
// GIVEN we want to use 'ed25519' // GIVEN we want to use 'ed25519'
const options: GenerateAddressOptions = {algorithm: 'ed25519'} const options: GenerateAddressOptions = {algorithm: 'ed25519'}
@@ -111,7 +111,9 @@ export default <TestSuite>{
) )
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -125,7 +127,9 @@ export default <TestSuite>{
assert.deepEqual(account, responses.generateXAddress) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -142,7 +146,9 @@ export default <TestSuite>{
}) })
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -157,7 +163,9 @@ export default <TestSuite>{
assert.deepEqual(account, responses.generateAddress) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -177,7 +185,9 @@ export default <TestSuite>{
}) })
}, },
'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 // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ecdsa-secp256k1', algorithm: 'ecdsa-secp256k1',
@@ -196,7 +206,9 @@ export default <TestSuite>{
assert.deepEqual(account, response) 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 // GIVEN we want to use 'ed25519' with entropy of zero
const options: GenerateAddressOptions = { const options: GenerateAddressOptions = {
algorithm: 'ed25519', algorithm: 'ed25519',
@@ -217,7 +229,7 @@ export default <TestSuite>{
}) })
}, },
'generateXAddress for test network use': async api => { 'generateXAddress for test network use': async (api) => {
// GIVEN we want an X-address for test network use // GIVEN we want an X-address for test network use
const options: GenerateAddressOptions = {test: true} const options: GenerateAddressOptions = {test: true}

View File

@@ -22,7 +22,7 @@ export default <TestSuite>{
'getBalances - limit & currency': async (api, address) => { 'getBalances - limit & currency': async (api, address) => {
const options = {currency: 'USD', limit: 3} const options = {currency: 'USD', limit: 3}
const expectedResponse = responses.getBalances const expectedResponse = responses.getBalances
.filter(item => item.currency === 'USD') .filter((item) => item.currency === 'USD')
.slice(0, 3) .slice(0, 3)
const result = await api.getBalances(address, options) const result = await api.getBalances(address, options)
assertResultMatch(result, expectedResponse, 'getBalances') assertResultMatch(result, expectedResponse, 'getBalances')
@@ -36,7 +36,7 @@ export default <TestSuite>{
} }
const expectedResponse = responses.getBalances const expectedResponse = responses.getBalances
.filter( .filter(
item => (item) =>
item.currency === 'USD' && item.currency === 'USD' &&
item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B'
) )

View File

@@ -9,22 +9,22 @@ const {getLedger: RESPONSE_FIXTURES} = responses
* - Check out "test/api/index.ts" for more information about the test runner. * - Check out "test/api/index.ts" for more information about the test runner.
*/ */
export default <TestSuite>{ export default <TestSuite>{
'simple test': async api => { 'simple test': async (api) => {
const response = await api.getLedger() const response = await api.getLedger()
assertResultMatch(response, RESPONSE_FIXTURES.header, 'getLedger') assertResultMatch(response, RESPONSE_FIXTURES.header, 'getLedger')
}, },
'by hash': async api => { 'by hash': async (api) => {
const response = await api.getLedger({ const response = await api.getLedger({
ledgerHash: ledgerHash:
'15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D' '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D'
}) })
assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger') assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger')
}, },
'future ledger version': async api => { 'future ledger version': async (api) => {
const response = await api.getLedger({ledgerVersion: 14661789}) const response = await api.getLedger({ledgerVersion: 14661789})
assert(!!response) assert(!!response)
}, },
'with state as hashes': async api => { 'with state as hashes': async (api) => {
const request = { const request = {
includeTransactions: true, includeTransactions: true,
includeAllData: false, includeAllData: false,
@@ -38,7 +38,7 @@ export default <TestSuite>{
'getLedger' 'getLedger'
) )
}, },
'with settings transaction': async api => { 'with settings transaction': async (api) => {
const request = { const request = {
includeTransactions: true, includeTransactions: true,
includeAllData: true, includeAllData: true,
@@ -47,7 +47,7 @@ export default <TestSuite>{
const response = await api.getLedger(request) const response = await api.getLedger(request)
assertResultMatch(response, RESPONSE_FIXTURES.withSettingsTx, 'getLedger') assertResultMatch(response, RESPONSE_FIXTURES.withSettingsTx, 'getLedger')
}, },
'with partial payment': async api => { 'with partial payment': async (api) => {
const request = { const request = {
includeTransactions: true, includeTransactions: true,
includeAllData: true, includeAllData: true,
@@ -56,7 +56,7 @@ export default <TestSuite>{
const response = await api.getLedger(request) const response = await api.getLedger(request)
assertResultMatch(response, RESPONSE_FIXTURES.withPartial, 'getLedger') assertResultMatch(response, RESPONSE_FIXTURES.withPartial, 'getLedger')
}, },
'pre 2014 with partial payment': async api => { 'pre 2014 with partial payment': async (api) => {
const request = { const request = {
includeTransactions: true, includeTransactions: true,
includeAllData: true, includeAllData: true,
@@ -69,7 +69,7 @@ export default <TestSuite>{
'getLedger' 'getLedger'
) )
}, },
'full, then computeLedgerHash': async api => { 'full, then computeLedgerHash': async (api) => {
const request = { const request = {
includeTransactions: true, includeTransactions: true,
includeState: true, includeState: true,

View File

@@ -108,17 +108,21 @@ export default <TestSuite>{
address, address,
requests.getOrderbook.normal requests.getOrderbook.normal
) )
const bidRates = response.bids.map(bid => bid.properties.makerExchangeRate) const bidRates = response.bids.map(
const askRates = response.asks.map(ask => ask.properties.makerExchangeRate) (bid) => bid.properties.makerExchangeRate
)
const askRates = response.asks.map(
(ask) => ask.properties.makerExchangeRate
)
// makerExchangeRate = quality = takerPays.value/takerGets.value // makerExchangeRate = quality = takerPays.value/takerGets.value
// so the best deal for the taker is the lowest makerExchangeRate // so the best deal for the taker is the lowest makerExchangeRate
// bids and asks should be sorted so that the best deals come first // bids and asks should be sorted so that the best deals come first
assert.deepEqual( assert.deepEqual(
bidRates.sort(x => Number(x)), bidRates.sort((x) => Number(x)),
bidRates bidRates
) )
assert.deepEqual( assert.deepEqual(
askRates.sort(x => Number(x)), askRates.sort((x) => Number(x)),
askRates askRates
) )
}, },
@@ -128,7 +132,7 @@ export default <TestSuite>{
address, address,
requests.getOrderbook.normal requests.getOrderbook.normal
) )
;[...response.bids, ...response.asks].forEach(order => { ;[...response.bids, ...response.asks].forEach((order) => {
const quantity = order.specification.quantity const quantity = order.specification.quantity
const totalPrice = order.specification.totalPrice const totalPrice = order.specification.totalPrice
const {base, counter} = requests.getOrderbook.normal const {base, counter} = requests.getOrderbook.normal
@@ -144,7 +148,7 @@ export default <TestSuite>{
address, address,
requests.getOrderbook.normal requests.getOrderbook.normal
) )
assert(response.bids.every(bid => bid.specification.direction === 'buy')) assert(response.bids.every((bid) => bid.specification.direction === 'buy'))
assert(response.asks.every(ask => ask.specification.direction === 'sell')) assert(response.asks.every((ask) => ask.specification.direction === 'sell'))
} }
} }

View File

@@ -12,11 +12,11 @@ const {getPaths: RESPONSE_FIXTURES} = responses
* - Check out "test/api/index.ts" for more information about the test runner. * - Check out "test/api/index.ts" for more information about the test runner.
*/ */
export default <TestSuite>{ export default <TestSuite>{
'simple test': async api => { 'simple test': async (api) => {
const response = await api.getPaths(REQUEST_FIXTURES.normal) const response = await api.getPaths(REQUEST_FIXTURES.normal)
assertResultMatch(response, RESPONSE_FIXTURES.XrpToUsd, 'getPaths') assertResultMatch(response, RESPONSE_FIXTURES.XrpToUsd, 'getPaths')
}, },
'queuing': async api => { 'queuing': async (api) => {
const [normalResult, usdOnlyResult, xrpOnlyResult] = await Promise.all([ const [normalResult, usdOnlyResult, xrpOnlyResult] = await Promise.all([
api.getPaths(REQUEST_FIXTURES.normal), api.getPaths(REQUEST_FIXTURES.normal),
api.getPaths(REQUEST_FIXTURES.UsdToUsd), api.getPaths(REQUEST_FIXTURES.UsdToUsd),
@@ -30,56 +30,56 @@ export default <TestSuite>{
// need decide what to do with currencies/XRP: // need decide what to do with currencies/XRP:
// if add 'XRP' in currencies, then there will be exception in // if add 'XRP' in currencies, then there will be exception in
// xrpToDrops function (called from toRippledAmount) // 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) const response = await api.getPaths(REQUEST_FIXTURES.UsdToUsd)
assertResultMatch(response, RESPONSE_FIXTURES.UsdToUsd, 'getPaths') 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) const response = await api.getPaths(REQUEST_FIXTURES.XrpToXrp)
assertResultMatch(response, RESPONSE_FIXTURES.XrpToXrp, 'getPaths') assertResultMatch(response, RESPONSE_FIXTURES.XrpToXrp, 'getPaths')
}, },
'source with issuer': async api => { 'source with issuer': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.issuer), api.getPaths(REQUEST_FIXTURES.issuer),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'XRP 2 XRP - not enough': async api => { 'XRP 2 XRP - not enough': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough), api.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'invalid PathFind': async api => { 'invalid PathFind': async (api) => {
assert.throws(() => { assert.throws(() => {
api.getPaths(REQUEST_FIXTURES.invalid) api.getPaths(REQUEST_FIXTURES.invalid)
}, /Cannot specify both source.amount/) }, /Cannot specify both source.amount/)
}, },
'does not accept currency': async api => { 'does not accept currency': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.NotAcceptCurrency), api.getPaths(REQUEST_FIXTURES.NotAcceptCurrency),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'no paths': async api => { 'no paths': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.NoPaths), api.getPaths(REQUEST_FIXTURES.NoPaths),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'no paths source amount': async api => { 'no paths source amount': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.NoPathsSource), api.getPaths(REQUEST_FIXTURES.NoPathsSource),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'no paths with source currencies': async api => { 'no paths with source currencies': async (api) => {
return assertRejects( return assertRejects(
api.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies), api.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies),
api.errors.NotFoundError api.errors.NotFoundError
) )
}, },
'error: srcActNotFound': async api => { 'error: srcActNotFound': async (api) => {
return assertRejects( return assertRejects(
api.getPaths({ api.getPaths({
...REQUEST_FIXTURES.normal, ...REQUEST_FIXTURES.normal,
@@ -88,7 +88,7 @@ export default <TestSuite>{
api.errors.RippleError api.errors.RippleError
) )
}, },
'send all': async api => { 'send all': async (api) => {
const response = await api.getPaths(REQUEST_FIXTURES.sendAll) const response = await api.getPaths(REQUEST_FIXTURES.sendAll)
assertResultMatch(response, RESPONSE_FIXTURES.sendAll, 'getPaths') assertResultMatch(response, RESPONSE_FIXTURES.sendAll, 'getPaths')
} }

View File

@@ -100,8 +100,8 @@ export default <TestSuite>{
const response = await api.getTransactions(address, options) const response = await api.getTransactions(address, options)
hack(response) hack(response)
assert.strictEqual(response.length, 10) assert.strictEqual(response.length, 10)
response.forEach(t => assert(t.type === 'payment' || t.type === 'order')) response.forEach((t) => assert(t.type === 'payment' || t.type === 'order'))
response.forEach(t => assert(t.outcome.result === 'tesSUCCESS')) response.forEach((t) => assert(t.outcome.result === 'tesSUCCESS'))
}, },
'filters for incoming': async (api, address) => { 'filters for incoming': async (api, address) => {
@@ -115,8 +115,8 @@ export default <TestSuite>{
const response = await api.getTransactions(address, options) const response = await api.getTransactions(address, options)
hack(response) hack(response)
assert.strictEqual(response.length, 10) assert.strictEqual(response.length, 10)
response.forEach(t => assert(t.type === 'payment' || t.type === 'order')) response.forEach((t) => assert(t.type === 'payment' || t.type === 'order'))
response.forEach(t => assert(t.outcome.result === 'tesSUCCESS')) response.forEach((t) => assert(t.outcome.result === 'tesSUCCESS'))
}, },
// this is the case where core.RippleError just falls // this is the case where core.RippleError just falls
@@ -162,7 +162,7 @@ export default <TestSuite>{
// the expected response. Long term, a better approach would be to use/test the json // the expected response. Long term, a better approach would be to use/test the json
// format responses, instead of the binary. // format responses, instead of the binary.
function hack(response) { function hack(response) {
response.forEach(element => { response.forEach((element) => {
element.outcome.timestamp = '2019-04-01T07:39:01.000Z' element.outcome.timestamp = '2019-04-01T07:39:01.000Z'
}) })
} }

View File

@@ -293,7 +293,10 @@ export default <TestSuite>{
assertResultMatch(response, RESPONSE_FIXTURES.noCounterparty, 'prepare') 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' // See also: 'sign succeeds with source.amount/destination.minAmount'
const localInstructions = { const localInstructions = {
@@ -303,20 +306,20 @@ export default <TestSuite>{
const response = await api.preparePayment( const response = await api.preparePayment(
address, address,
{ {
"source": { source: {
address, address,
"amount": { amount: {
"currency": "GBP", currency: 'GBP',
"value": "0.1", value: '0.1',
"counterparty": "rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro" counterparty: 'rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro'
} }
}, },
"destination": { destination: {
"address": "rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq", address: 'rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq',
"minAmount": { minAmount: {
"currency": "USD", currency: 'USD',
"value": "0.1248548562296331", value: '0.1248548562296331',
"counterparty": "rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH" counterparty: 'rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH'
} }
} }
}, },

View File

@@ -569,7 +569,9 @@ export default <TestSuite>{
) )
}, },
'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 = { const localInstructions = {
...instructionsWithMaxLedgerVersionOffset, ...instructionsWithMaxLedgerVersionOffset,
maxFee: '0.000012' maxFee: '0.000012'

View File

@@ -146,7 +146,10 @@ export default <TestSuite>{
schemaValidator.schemaValidate('sign', result) 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' // See also: 'preparePayment with source.amount/destination.minAmount'
const txJSON = const txJSON =

View File

@@ -28,7 +28,7 @@ describe('RippleAPIBroadcast', function() {
it('base', function () { it('base', function () {
const expected = {request_server_info: 1} 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()) assert(this.api.isConnected())
return this.api return this.api
.getServerInfo() .getServerInfo()
@@ -43,7 +43,7 @@ describe('RippleAPIBroadcast', function() {
const ledgerNext = _.assign({}, ledgerClosed) const ledgerNext = _.assign({}, ledgerClosed)
ledgerNext.ledger_index++ ledgerNext.ledger_index++
this.api._apis.forEach(api => this.api._apis.forEach((api) =>
api.connection api.connection
.request({ .request({
command: 'echo', command: 'echo',

View File

@@ -109,8 +109,8 @@ describe('Connection', function() {
createServer().then((server: any) => { createServer().then((server: any) => {
const port = server.address().port const port = server.address().port
const expect = 'CONNECT localhost' const expect = 'CONNECT localhost'
server.on('connection', socket => { server.on('connection', (socket) => {
socket.on('data', data => { socket.on('data', (data) => {
const got = data.toString('ascii', 0, expect.length) const got = data.toString('ascii', 0, expect.length)
assert.strictEqual(got, expect) assert.strictEqual(got, expect)
server.close() server.close()
@@ -128,7 +128,7 @@ describe('Connection', function() {
this.api.connection._url, this.api.connection._url,
options options
) )
connection.connect().catch(err => { connection.connect().catch((err) => {
assert(err instanceof this.api.errors.NotConnectedError) assert(err instanceof this.api.errors.NotConnectedError)
}) })
}, done) }, done)
@@ -150,7 +150,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw NotConnectedError') assert(false, 'Should throw NotConnectedError')
}) })
.catch(error => { .catch((error) => {
assert(error instanceof this.api.errors.NotConnectedError) assert(error instanceof this.api.errors.NotConnectedError)
}) })
}) })
@@ -170,7 +170,7 @@ describe('Connection', function() {
'ws://testripple.circleci.com:129' 'ws://testripple.circleci.com:129'
) )
connection.on('error', done) connection.on('error', done)
connection.connect().catch(error => { connection.connect().catch((error) => {
assert(error instanceof this.api.errors.NotConnectedError) assert(error instanceof this.api.errors.NotConnectedError)
done() done()
}) })
@@ -186,7 +186,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw DisconnectedError') assert(false, 'Should throw DisconnectedError')
}) })
.catch(error => { .catch((error) => {
assert(error instanceof this.api.errors.DisconnectedError) assert(error instanceof this.api.errors.DisconnectedError)
}) })
}) })
@@ -201,7 +201,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw TimeoutError') assert(false, 'Should throw TimeoutError')
}) })
.catch(error => { .catch((error) => {
assert(error instanceof this.api.errors.TimeoutError) assert(error instanceof this.api.errors.TimeoutError)
}) })
}) })
@@ -215,7 +215,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw DisconnectedError') assert(false, 'Should throw DisconnectedError')
}) })
.catch(error => { .catch((error) => {
assert(error instanceof this.api.errors.DisconnectedError) assert(error instanceof this.api.errors.DisconnectedError)
assert.strictEqual(error.message, 'not connected') assert.strictEqual(error.message, 'not connected')
}) })
@@ -254,7 +254,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw ResponseFormatError') assert(false, 'Should throw ResponseFormatError')
}) })
.catch(error => { .catch((error) => {
assert(error instanceof this.api.errors.ResponseFormatError) assert(error instanceof this.api.errors.ResponseFormatError)
}) })
}) })
@@ -296,7 +296,7 @@ describe('Connection', function() {
this.api.connection.on('reconnecting', () => { this.api.connection.on('reconnecting', () => {
reconnectsCount += 1 reconnectsCount += 1
}) })
this.api.connection.on('disconnected', _code => { this.api.connection.on('disconnected', (_code) => {
code = _code code = _code
disconnectsCount += 1 disconnectsCount += 1
}) })
@@ -359,7 +359,7 @@ describe('Connection', function() {
// Hook up a listener for the reconnect event // Hook up a listener for the reconnect event
this.api.connection.on('reconnect', () => done()) this.api.connection.on('reconnect', () => done())
// Trigger a heartbeat // Trigger a heartbeat
this.api.connection._heartbeat().catch(error => { this.api.connection._heartbeat().catch((error) => {
/* ignore - test expects heartbeat failure */ /* ignore - test expects heartbeat failure */
}) })
}) })
@@ -393,7 +393,7 @@ describe('Connection', function() {
}) })
it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) { it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) {
this.api.once('disconnected', code => { this.api.once('disconnected', (code) => {
assert.strictEqual(code, 1000) assert.strictEqual(code, 1000)
done() done()
}) })
@@ -401,10 +401,10 @@ describe('Connection', function() {
}) })
it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) { it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) {
this.api.connection.once('error', error => { this.api.connection.once('error', (error) => {
done(new Error('should not throw error, got ' + String(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) assert.strictEqual(code, 1006)
done() done()
}) })
@@ -428,7 +428,7 @@ describe('Connection', function() {
}) })
it('hasLedgerVersion', function () { it('hasLedgerVersion', function () {
return this.api.connection.hasLedgerVersion(8819951).then(result => { return this.api.connection.hasLedgerVersion(8819951).then((result) => {
assert(result) assert(result)
}) })
}) })
@@ -440,7 +440,7 @@ describe('Connection', function() {
.then(() => { .then(() => {
assert(false, 'Should throw ConnectionError') assert(false, 'Should throw ConnectionError')
}) })
.catch(error => { .catch((error) => {
assert( assert(
error instanceof this.api.errors.ConnectionError, error instanceof this.api.errors.ConnectionError,
'Should throw ConnectionError' 'Should throw ConnectionError'
@@ -474,7 +474,7 @@ describe('Connection', function() {
this.api.connection.on('path_find', () => { this.api.connection.on('path_find', () => {
pathFindCount++ pathFindCount++
}) })
this.api.connection.on('response', message => { this.api.connection.on('response', (message) => {
assert.strictEqual(message.id, 1) assert.strictEqual(message.id, 1)
assert.strictEqual(transactionCount, 1) assert.strictEqual(transactionCount, 1)
assert.strictEqual(pathFindCount, 1) assert.strictEqual(pathFindCount, 1)
@@ -530,7 +530,7 @@ describe('Connection', function() {
}) })
it('propagates RippledError data', function (done) { it('propagates RippledError data', function (done) {
this.api.request('subscribe', {streams: 'validations'}).catch(error => { this.api.request('subscribe', {streams: 'validations'}).catch((error) => {
assert.strictEqual(error.name, 'RippledError') assert.strictEqual(error.name, 'RippledError')
assert.strictEqual(error.data.error, 'invalidParams') assert.strictEqual(error.data.error, 'invalidParams')
assert.strictEqual(error.message, 'Invalid parameters.') assert.strictEqual(error.message, 'Invalid parameters.')
@@ -550,7 +550,7 @@ describe('Connection', function() {
it('unrecognized message type', function (done) { it('unrecognized message type', function (done) {
// This enables us to automatically support any // This enables us to automatically support any
// new messages added by rippled in the future. // 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'}) assert.deepEqual(event, {type: 'unknown'})
done() done()
}) })
@@ -583,7 +583,7 @@ describe('Connection', function() {
() => { () => {
assert(false, 'Must have thrown!') assert(false, 'Must have thrown!')
}, },
error => { (error) => {
assert( assert(
error instanceof this.api.errors.RippledNotInitializedError, error instanceof this.api.errors.RippledNotInitializedError,
'Must throw RippledNotInitializedError, got instead ' + 'Must throw RippledNotInitializedError, got instead ' +
@@ -614,7 +614,7 @@ 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.timeout(23000)
this.api.on('error', error => { this.api.on('error', (error) => {
done(error || new Error('Should not emit error.')) done(error || new Error('Should not emit error.'))
}) })
let disconnectedCount = 0 let disconnectedCount = 0

View File

@@ -4,10 +4,10 @@ function main() {
const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com'] const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com']
const api = new RippleAPIBroadcast(servers) const api = new RippleAPIBroadcast(servers)
api.connect().then(() => { api.connect().then(() => {
api.getServerInfo().then(info => { api.getServerInfo().then((info) => {
console.log(JSON.stringify(info, null, 2)) console.log(JSON.stringify(info, null, 2))
}) })
api.on('ledger', ledger => { api.on('ledger', (ledger) => {
console.log(JSON.stringify(ledger, null, 2)) console.log(JSON.stringify(ledger, null, 2))
}) })
}) })

View File

@@ -21,11 +21,11 @@ const request4 = {
function makeRequest(connection, request) { function makeRequest(connection, request) {
return connection return connection
.request(request) .request(request)
.then(response => { .then((response) => {
console.log(request) console.log(request)
console.log(JSON.stringify(response, null, 2)) console.log(JSON.stringify(response, null, 2))
}) })
.catch(error => { .catch((error) => {
console.log(request) console.log(request)
console.log(error) console.log(error)
}) })
@@ -44,7 +44,7 @@ function main() {
console.log('Done') console.log('Done')
}) })
connection.getLedgerVersion().then(console.log) connection.getLedgerVersion().then(console.log)
connection.on('ledgerClosed', ledger => { connection.on('ledgerClosed', (ledger) => {
console.log(ledger) console.log(ledger)
connection.getLedgerVersion().then(console.log) connection.getLedgerVersion().then(console.log)
}) })

View File

@@ -22,7 +22,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) {
console.log('VERIFY...') console.log('VERIFY...')
return testcase.api return testcase.api
.getTransaction(hash, options) .getTransaction(hash, options)
.then(data => { .then((data) => {
assert(data && data.outcome) assert(data && data.outcome)
assert.strictEqual(data.type, type) assert.strictEqual(data.type, type)
assert.strictEqual(data.address, address) 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} return {txJSON: JSON.stringify(txData), id: hash, tx: data}
}) })
.catch(error => { .catch((error) => {
if (error instanceof errors.PendingLedgerVersionError) { if (error instanceof errors.PendingLedgerVersionError) {
console.log('NOT VALIDATED YET...') console.log('NOT VALIDATED YET...')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -71,12 +71,12 @@ function testTransaction(
console.log('PREPARED...') console.log('PREPARED...')
return testcase.api return testcase.api
.submit(signedData.signedTransaction) .submit(signedData.signedTransaction)
.then(data => .then((data) =>
testcase.test.title.indexOf('multisign') !== -1 testcase.test.title.indexOf('multisign') !== -1
? acceptLedger(testcase.api).then(() => data) ? acceptLedger(testcase.api).then(() => data)
: data : data
) )
.then(data => { .then((data) => {
console.log('SUBMITTED...') console.log('SUBMITTED...')
assert.strictEqual(data.resultCode, 'tesSUCCESS') assert.strictEqual(data.resultCode, 'tesSUCCESS')
const options = { const options = {
@@ -108,7 +108,7 @@ function setup(this: any, server = 'wss://s1.ripple.com') {
() => { () => {
console.log('CONNECTED...') console.log('CONNECTED...')
}, },
error => { (error) => {
console.log('ERROR:', error) console.log('ERROR:', error)
throw error throw error
} }
@@ -128,7 +128,7 @@ function makeTrustLine(testcase, address, secret) {
} }
const trust = api const trust = api
.prepareTrustline(address, specification, {}) .prepareTrustline(address, specification, {})
.then(data => { .then((data) => {
const signed = api.sign(data.txJSON, secret) const signed = api.sign(data.txJSON, secret)
if (address === wallet.getAddress()) { if (address === wallet.getAddress()) {
testcase.transactions.push(signed.id) testcase.transactions.push(signed.id)
@@ -142,8 +142,8 @@ function makeTrustLine(testcase, address, secret) {
function makeOrder(api, address, specification, secret) { function makeOrder(api, address, specification, secret) {
return api return api
.prepareOrder(address, specification) .prepareOrder(address, specification)
.then(data => api.sign(data.txJSON, secret)) .then((data) => api.sign(data.txJSON, secret))
.then(signed => api.submit(signed.signedTransaction)) .then((signed) => api.submit(signed.signedTransaction))
.then(() => ledgerAccept(api)) .then(() => ledgerAccept(api))
} }
@@ -158,8 +158,8 @@ function setupAccounts(testcase) {
.then(() => { .then(() => {
return api return api
.prepareSettings(masterAccount, {defaultRipple: true}) .prepareSettings(masterAccount, {defaultRipple: true})
.then(data => api.sign(data.txJSON, masterSecret)) .then((data) => api.sign(data.txJSON, masterSecret))
.then(signed => api.submit(signed.signedTransaction)) .then((signed) => api.submit(signed.signedTransaction))
.then(() => ledgerAccept(api)) .then(() => ledgerAccept(api))
}) })
.then(() => .then(() =>
@@ -233,7 +233,7 @@ function suiteSetup(this: any) {
// so getLedgerVersion will return right value // so getLedgerVersion will return right value
.then(() => ledgerAccept(this.api)) .then(() => ledgerAccept(this.api))
.then(() => this.api.getLedgerVersion()) .then(() => this.api.getLedgerVersion())
.then(ledgerVersion => { .then((ledgerVersion) => {
this.startLedgerVersion = ledgerVersion this.startLedgerVersion = ledgerVersion
}) })
.then(() => setupAccounts(this)) .then(() => setupAccounts(this))
@@ -251,24 +251,24 @@ describe('integration tests', function() {
afterEach(teardown) afterEach(teardown)
it('settings', function () { it('settings', function () {
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api return this.api
.prepareSettings(address, requests.prepareSettings.domain, instructions) .prepareSettings(address, requests.prepareSettings.domain, instructions)
.then(prepared => .then((prepared) =>
testTransaction(this, 'settings', ledgerVersion, prepared) testTransaction(this, 'settings', ledgerVersion, prepared)
) )
}) })
}) })
it('trustline', function () { it('trustline', function () {
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api return this.api
.prepareTrustline( .prepareTrustline(
address, address,
requests.prepareTrustline.simple, requests.prepareTrustline.simple,
instructions instructions
) )
.then(prepared => .then((prepared) =>
testTransaction(this, 'trustline', ledgerVersion, prepared) testTransaction(this, 'trustline', ledgerVersion, prepared)
) )
}) })
@@ -286,10 +286,10 @@ describe('integration tests', function() {
amount: amount amount: amount
} }
} }
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api return this.api
.preparePayment(address, paymentSpecification, instructions) .preparePayment(address, paymentSpecification, instructions)
.then(prepared => .then((prepared) =>
testTransaction(this, 'payment', ledgerVersion, prepared) testTransaction(this, 'payment', ledgerVersion, prepared)
) )
}) })
@@ -308,18 +308,18 @@ describe('integration tests', function() {
value: '0.0002' value: '0.0002'
} }
} }
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api return this.api
.prepareOrder(address, orderSpecification, instructions) .prepareOrder(address, orderSpecification, instructions)
.then(prepared => .then((prepared) =>
testTransaction(this, 'order', ledgerVersion, prepared) testTransaction(this, 'order', ledgerVersion, prepared)
) )
.then(result => { .then((result) => {
const txData = JSON.parse(result.txJSON) 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) assert(orders && orders.length > 0)
const createdOrder = _.first( const createdOrder = _.first(
_.filter(orders, order => { _.filter(orders, (order) => {
return order.properties.sequence === txData.Sequence return order.properties.sequence === txData.Sequence
}) })
) )
@@ -329,14 +329,14 @@ describe('integration tests', function() {
return txData return txData
}) })
}) })
.then(txData => .then((txData) =>
this.api this.api
.prepareOrderCancellation( .prepareOrderCancellation(
address, address,
{orderSequence: txData.Sequence}, {orderSequence: txData.Sequence},
instructions instructions
) )
.then(prepared => .then((prepared) =>
testTransaction( testTransaction(
this, this,
'orderCancellation', 'orderCancellation',
@@ -353,13 +353,13 @@ describe('integration tests', function() {
}) })
it('getServerInfo', function () { it('getServerInfo', function () {
return this.api.getServerInfo().then(data => { return this.api.getServerInfo().then((data) => {
assert(data && data.pubkeyNode) assert(data && data.pubkeyNode)
}) })
}) })
it('getFee', function () { it('getFee', function () {
return this.api.getFee().then(fee => { return this.api.getFee().then((fee) => {
assert.strictEqual(typeof fee, 'string') assert.strictEqual(typeof fee, 'string')
assert(!isNaN(Number(fee))) assert(!isNaN(Number(fee)))
assert(parseFloat(fee) === Number(fee)) assert(parseFloat(fee) === Number(fee))
@@ -367,7 +367,7 @@ describe('integration tests', function() {
}) })
it('getLedgerVersion', function () { it('getLedgerVersion', function () {
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
assert.strictEqual(typeof ledgerVersion, 'number') assert.strictEqual(typeof ledgerVersion, 'number')
assert(ledgerVersion >= this.startLedgerVersion) assert(ledgerVersion >= this.startLedgerVersion)
}) })
@@ -378,7 +378,9 @@ describe('integration tests', function() {
initiated: true, initiated: true,
minLedgerVersion: this.startLedgerVersion minLedgerVersion: this.startLedgerVersion
} }
return this.api.getTransactions(address, options).then(transactionsData => { return this.api
.getTransactions(address, options)
.then((transactionsData) => {
assert(transactionsData) assert(transactionsData)
assert.strictEqual(transactionsData.length, this.transactions.length) assert.strictEqual(transactionsData.length, this.transactions.length)
}) })
@@ -387,7 +389,7 @@ describe('integration tests', function() {
it('getTrustlines', function () { it('getTrustlines', function () {
const fixture = requests.prepareTrustline.simple const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty']) 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) assert(data && data.length > 0 && data[0] && data[0].specification)
const specification = data[0].specification const specification = data[0].specification
assert.strictEqual(Number(specification.limit), Number(fixture.limit)) assert.strictEqual(Number(specification.limit), Number(fixture.limit))
@@ -399,7 +401,7 @@ describe('integration tests', function() {
it('getBalances', function () { it('getBalances', function () {
const fixture = requests.prepareTrustline.simple const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty']) 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(data && data.length > 0 && data[0])
assert.strictEqual(data[0].currency, fixture.currency) assert.strictEqual(data[0].currency, fixture.currency)
assert.strictEqual(data[0].counterparty, fixture.counterparty) assert.strictEqual(data[0].counterparty, fixture.counterparty)
@@ -407,7 +409,7 @@ describe('integration tests', function() {
}) })
it('getSettings', function () { it('getSettings', function () {
return this.api.getSettings(address).then(data => { return this.api.getSettings(address).then((data) => {
assert(data) assert(data)
assert.strictEqual(data.domain, requests.prepareSettings.domain.domain) assert.strictEqual(data.domain, requests.prepareSettings.domain.domain)
}) })
@@ -423,7 +425,7 @@ describe('integration tests', function() {
counterparty: masterAccount 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 && book.bids && book.bids.length > 0)
assert(book.asks && book.asks.length > 0) assert(book.asks && book.asks.length > 0)
const bid = book.bids[0] const bid = book.bids[0]
@@ -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) assert(data && data.length > 0)
const path = data[0] const path = data[0]
assert(path && path.source) assert(path && path.source)
@@ -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(data && data.length > 0)
assert( assert(
_.every(data, path => { _.every(data, (path) => {
return ( return (
parseFloat(path.source.amount.value) <= parseFloat(path.source.amount.value) <=
parseFloat(pathfind.source.amount.value) parseFloat(pathfind.source.amount.value)
@@ -530,11 +532,11 @@ describe('integration tests - standalone rippled', function() {
let minLedgerVersion = null let minLedgerVersion = null
return payTo(this.api, address) return payTo(this.api, address)
.then(() => { .then(() => {
return this.api.getLedgerVersion().then(ledgerVersion => { return this.api.getLedgerVersion().then((ledgerVersion) => {
minLedgerVersion = ledgerVersion minLedgerVersion = ledgerVersion
return this.api return this.api
.prepareSettings(address, {signers}, instructions) .prepareSettings(address, {signers}, instructions)
.then(prepared => { .then((prepared) => {
return testTransaction( return testTransaction(
this, this,
'settings', 'settings',
@@ -556,7 +558,7 @@ describe('integration tests - standalone rippled', function() {
{domain: 'example.com'}, {domain: 'example.com'},
multisignInstructions multisignInstructions
) )
.then(prepared => { .then((prepared) => {
const signed1 = this.api.sign(prepared.txJSON, signer1secret, { const signed1 = this.api.sign(prepared.txJSON, signer1secret, {
signAs: signer1address signAs: signer1address
}) })
@@ -569,8 +571,8 @@ describe('integration tests - standalone rippled', function() {
]) ])
return this.api return this.api
.submit(combined.signedTransaction) .submit(combined.signedTransaction)
.then(response => acceptLedger(this.api).then(() => response)) .then((response) => acceptLedger(this.api).then(() => response))
.then(response => { .then((response) => {
assert.strictEqual(response.resultCode, 'tesSUCCESS') assert.strictEqual(response.resultCode, 'tesSUCCESS')
const options = {minLedgerVersion} const options = {minLedgerVersion}
return verifyTransaction( return verifyTransaction(
@@ -582,7 +584,7 @@ describe('integration tests - standalone rippled', function() {
address address
) )
}) })
.catch(error => { .catch((error) => {
console.log(error.message) console.log(error.message)
throw error throw error
}) })

View File

@@ -61,7 +61,9 @@ export function createMockRippled(port) {
const close = mock.close const close = mock.close
mock.close = function () { mock.close = function () {
if (mock.expectedRequests !== undefined) { if (mock.expectedRequests !== undefined) {
const allRequestsMade = _.every(mock.expectedRequests, function(counter) { const allRequestsMade = _.every(mock.expectedRequests, function (
counter
) {
return counter === 0 return counter === 0
}) })
if (!allRequestsMade) { if (!allRequestsMade) {
@@ -140,7 +142,7 @@ export function createMockRippled(port) {
}) })
) )
} else if (request.data.openOnOtherPort) { } else if (request.data.openOnOtherPort) {
getFreePort().then(newPort => { getFreePort().then((newPort) => {
createMockRippled(newPort) createMockRippled(newPort)
conn.send( conn.send(
createResponse(request, { createResponse(request, {

View File

@@ -45,7 +45,7 @@ describe('RippleAPI', function() {
}) })
it('ledger closed event', function (done) { it('ledger closed event', function (done) {
this.api.on('ledger', message => { this.api.on('ledger', (message) => {
assertResultMatch(message, responses.ledgerEvent, 'ledgerEvent') assertResultMatch(message, responses.ledgerEvent, 'ledgerEvent')
done() done()
}) })

View File

@@ -66,7 +66,7 @@ describe('RippleAPI [Test Runner]', function() {
} }
// Report any missing tests. // 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) { for (const methodName of allPublicMethods) {
if (!allTestedMethods.has(methodName)) { if (!allTestedMethods.has(methodName)) {
// TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures. // TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures.

View File

@@ -14,7 +14,7 @@ function setup(this: any, port_ = port) {
data: {openOnOtherPort: true} data: {openOnOtherPort: true}
}) })
}) })
.then(got => { .then((got) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.api = new RippleAPI({server: baseUrl + got.port}) this.api = new RippleAPI({server: baseUrl + got.port})
this.api this.api
@@ -35,7 +35,7 @@ function setup(this: any, port_ = port) {
} }
function setupBroadcast(this: any) { 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) this.api = new RippleAPIBroadcast(servers)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.api this.api

View File

@@ -23,8 +23,8 @@ function setupMockRippledConnection(testcase, port) {
function setupMockRippledConnectionForBroadcast(testcase, ports) { function setupMockRippledConnectionForBroadcast(testcase, ports) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const servers = ports.map(port => 'ws://localhost:' + port) const servers = ports.map((port) => 'ws://localhost:' + port)
testcase.mocks = ports.map(port => createMockRippled(port)) testcase.mocks = ports.map((port) => createMockRippled(port))
testcase.api = new RippleAPIBroadcast(servers) testcase.api = new RippleAPIBroadcast(servers)
testcase.api testcase.api
.connect() .connect()
@@ -37,13 +37,13 @@ function setupMockRippledConnectionForBroadcast(testcase, ports) {
} }
function setup(this: any) { function setup(this: any) {
return getFreePort().then(port => { return getFreePort().then((port) => {
return setupMockRippledConnection(this, port) return setupMockRippledConnection(this, port)
}) })
} }
function setupBroadcast(this: any) { function setupBroadcast(this: any) {
return Promise.all([getFreePort(), getFreePort()]).then(ports => { return Promise.all([getFreePort(), getFreePort()]).then((ports) => {
return setupMockRippledConnectionForBroadcast(this, ports) return setupMockRippledConnectionForBroadcast(this, ports)
}) })
} }
@@ -55,7 +55,7 @@ function teardown(this: any, done) {
if (this.mockRippled !== undefined) { if (this.mockRippled !== undefined) {
this.mockRippled.close() this.mockRippled.close()
} else { } else {
this.mocks.forEach(mock => mock.close()) this.mocks.forEach((mock) => mock.close())
} }
setImmediate(done) setImmediate(done)
}) })

View File

@@ -118,7 +118,7 @@ export function getAllPublicMethods(api: RippleAPI) {
...Object.getOwnPropertyNames(api), ...Object.getOwnPropertyNames(api),
...Object.getOwnPropertyNames(RippleAPI.prototype) ...Object.getOwnPropertyNames(RippleAPI.prototype)
]) ])
).filter(key => !key.startsWith('_')) ).filter((key) => !key.startsWith('_'))
} }
export function loadTestSuites(): LoadedTestSuite[] { export function loadTestSuites(): LoadedTestSuite[] {
@@ -126,7 +126,7 @@ export function loadTestSuites(): LoadedTestSuite[] {
encoding: 'utf8' encoding: 'utf8'
}) })
return allTests return allTests
.map(methodName => { .map((methodName) => {
if (methodName.startsWith('.DS_Store')) { if (methodName.startsWith('.DS_Store')) {
return null return null
} }