fix: sequence 0 check, lint and format

This commit is contained in:
Javi
2020-11-06 10:58:21 +01:00
parent 6b4fa159ea
commit 9f6fa6a4fd
65 changed files with 562 additions and 498 deletions

View File

@@ -156,7 +156,7 @@ class RippleAPI extends EventEmitter {
const serverURL = options.server
if (serverURL !== undefined) {
this.connection = new Connection(serverURL, options)
this.connection.on('ledgerClosed', message => {
this.connection.on('ledgerClosed', (message) => {
this.emit('ledger', formatLedgerClose(message))
})
this.connection.on('error', (errorCode, errorMessage, data) => {
@@ -165,7 +165,7 @@ class RippleAPI extends EventEmitter {
this.connection.on('connected', () => {
this.emit('connected')
})
this.connection.on('disconnected', code => {
this.connection.on('disconnected', (code) => {
let finalCode = code
// 1005: This is a backwards-compatible fix for this change in the ws library: https://github.com/websockets/ws/issues/1257
// 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -41,7 +41,7 @@ function renameKeys(object, mapping) {
}
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)
renameKeys(info, {hostid: 'hostID'})
if (info.validatedLedger) {

View File

@@ -134,7 +134,7 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
// taking this out of function leads to error in PhantomJS
const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g
if (FINDSNAKE.test(key)) {
newKey = key.replace(FINDSNAKE, r => r[0] + r[2].toUpperCase())
newKey = key.replace(FINDSNAKE, (r) => r[0] + r[2].toUpperCase())
}
result[newKey] = convertKeysFromSnakeCaseToCamelCase(value)
return result

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ const validate = utils.common.validate
const ValidationError = utils.common.errors.ValidationError
export interface Ticket {
account: string,
account: string
sequence: number
}
@@ -15,8 +15,8 @@ function createTicketTransaction(
account: string,
ticketCount: number
): TransactionJSON {
if (!ticketCount || ticketCount === 0) throw new ValidationError('Ticket count must be greater than 0.')
if (!ticketCount || ticketCount === 0)
throw new ValidationError('Ticket count must be greater than 0.')
const txJSON: any = {
TransactionType: 'TicketCreate',

View File

@@ -56,10 +56,7 @@ function setCanonicalFlag(txJSON: TransactionJSON): void {
}
function scaleValue(value, multiplier, extra = 0) {
return new BigNumber(value)
.times(multiplier)
.plus(extra)
.toString()
return new BigNumber(value).times(multiplier).plus(extra).toString()
}
/**
@@ -115,9 +112,16 @@ function prepareTransaction(
api: RippleAPI,
instructions: Instructions
): Promise<Prepare> {
common.validate.instructions(instructions)
common.validate.tx_json(txJSON)
// We allow 0 values in the Sequence schema to support the Tickets feature
// When a ticketSequence is used, sequence has to be 0
// We validate that a sequence with value 0 is not passed even if the json schema allows it
if (instructions.sequence !== undefined && instructions.sequence === 0) {
return Promise.reject(new ValidationError('`sequence` cannot be 0'))
}
const disallowedFieldsInTxJSON = [
'maxLedgerVersion',
'maxLedgerVersionOffset',
@@ -125,7 +129,7 @@ function prepareTransaction(
'sequence',
'ticketSequence'
]
const badFields = disallowedFieldsInTxJSON.filter(field => txJSON[field])
const badFields = disallowedFieldsInTxJSON.filter((field) => txJSON[field])
if (badFields.length) {
return Promise.reject(
new ValidationError(
@@ -242,7 +246,7 @@ function prepareTransaction(
instructions.maxLedgerVersionOffset !== undefined
? instructions.maxLedgerVersionOffset
: 3
return api.connection.getLedgerVersion().then(ledgerVersion => {
return api.connection.getLedgerVersion().then((ledgerVersion) => {
newTxJSON.LastLedgerSequence = ledgerVersion + offset
return
})
@@ -287,8 +291,8 @@ function prepareTransaction(
return Promise.resolve()
}
const cushion = api._feeCushion
return api.getFee(cushion).then(fee => {
return api.connection.getFeeRef().then(feeRef => {
return api.getFee(cushion).then((fee) => {
return api.connection.getFeeRef().then((feeRef) => {
const extraFee =
newTxJSON.TransactionType !== 'EscrowFinish' ||
newTxJSON.Fulfillment === undefined
@@ -313,7 +317,6 @@ function prepareTransaction(
}
async function prepareSequence(): Promise<void> {
if (instructions.sequence !== undefined) {
if (
newTxJSON.Sequence === undefined ||
@@ -362,9 +365,7 @@ function prepareTransaction(
}
function convertStringToHex(string: string): string {
return Buffer.from(string, 'utf8')
.toString('hex')
.toUpperCase()
return Buffer.from(string, 'utf8').toString('hex').toUpperCase()
}
function convertMemo(memo: Memo): {Memo: ApiMemo} {

View File

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

View File

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

View File

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

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

View File

@@ -22,7 +22,7 @@ export default <TestSuite>{
'getBalances - limit & currency': async (api, address) => {
const options = {currency: 'USD', limit: 3}
const expectedResponse = responses.getBalances
.filter(item => item.currency === 'USD')
.filter((item) => item.currency === 'USD')
.slice(0, 3)
const result = await api.getBalances(address, options)
assertResultMatch(result, expectedResponse, 'getBalances')
@@ -36,7 +36,7 @@ export default <TestSuite>{
}
const expectedResponse = responses.getBalances
.filter(
item =>
(item) =>
item.currency === 'USD' &&
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.
*/
export default <TestSuite>{
'simple test': async api => {
'simple test': async (api) => {
const response = await api.getLedger()
assertResultMatch(response, RESPONSE_FIXTURES.header, 'getLedger')
},
'by hash': async api => {
'by hash': async (api) => {
const response = await api.getLedger({
ledgerHash:
'15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D'
})
assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger')
},
'future ledger version': async api => {
'future ledger version': async (api) => {
const response = await api.getLedger({ledgerVersion: 14661789})
assert(!!response)
},
'with state as hashes': async api => {
'with state as hashes': async (api) => {
const request = {
includeTransactions: true,
includeAllData: false,
@@ -38,7 +38,7 @@ export default <TestSuite>{
'getLedger'
)
},
'with settings transaction': async api => {
'with settings transaction': async (api) => {
const request = {
includeTransactions: true,
includeAllData: true,
@@ -47,7 +47,7 @@ export default <TestSuite>{
const response = await api.getLedger(request)
assertResultMatch(response, RESPONSE_FIXTURES.withSettingsTx, 'getLedger')
},
'with partial payment': async api => {
'with partial payment': async (api) => {
const request = {
includeTransactions: true,
includeAllData: true,
@@ -56,7 +56,7 @@ export default <TestSuite>{
const response = await api.getLedger(request)
assertResultMatch(response, RESPONSE_FIXTURES.withPartial, 'getLedger')
},
'pre 2014 with partial payment': async api => {
'pre 2014 with partial payment': async (api) => {
const request = {
includeTransactions: true,
includeAllData: true,
@@ -69,7 +69,7 @@ export default <TestSuite>{
'getLedger'
)
},
'full, then computeLedgerHash': async api => {
'full, then computeLedgerHash': async (api) => {
const request = {
includeTransactions: true,
includeState: true,

View File

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

View File

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

View File

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

View File

@@ -37,5 +37,5 @@ export default <TestSuite>{
localInstructions
)
assertResultMatch(result, responses.prepareCheckCash.ticket, 'prepare')
},
}
}

View File

@@ -50,5 +50,5 @@ export default <TestSuite>{
responses.prepareEscrowCancellation.ticket,
'prepare'
)
},
}
}

View File

@@ -59,5 +59,5 @@ export default <TestSuite>{
localInstructions
)
assertResultMatch(result, responses.prepareEscrowCreation.ticket, 'prepare')
},
}
}

View File

@@ -74,5 +74,5 @@ export default <TestSuite>{
responses.prepareEscrowExecution.ticket,
'prepare'
)
},
}
}

View File

@@ -57,11 +57,7 @@ export default <TestSuite>{
maxFee: '0.000012',
ticketSequence: 23
}
const result = await api.prepareOrder(
address,
request,
localInstructions
)
const result = await api.prepareOrder(address, request, localInstructions)
assertResultMatch(result, responses.prepareOrder.ticket, 'prepare')
},
}
}

View File

@@ -74,5 +74,5 @@ export default <TestSuite>{
responses.prepareOrderCancellation.ticket,
'prepare'
)
},
}
}

View File

@@ -293,7 +293,10 @@ export default <TestSuite>{
assertResultMatch(response, RESPONSE_FIXTURES.noCounterparty, 'prepare')
},
'preparePayment with source.amount/destination.minAmount can be signed': async (api, address) => {
'preparePayment with source.amount/destination.minAmount can be signed': async (
api,
address
) => {
// See also: 'sign succeeds with source.amount/destination.minAmount'
const localInstructions = {
@@ -303,20 +306,20 @@ export default <TestSuite>{
const response = await api.preparePayment(
address,
{
"source": {
source: {
address,
"amount": {
"currency": "GBP",
"value": "0.1",
"counterparty": "rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro"
amount: {
currency: 'GBP',
value: '0.1',
counterparty: 'rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro'
}
},
"destination": {
"address": "rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq",
"minAmount": {
"currency": "USD",
"value": "0.1248548562296331",
"counterparty": "rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH"
destination: {
address: 'rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq',
minAmount: {
currency: 'USD',
value: '0.1248548562296331',
counterparty: 'rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH'
}
}
},
@@ -527,6 +530,5 @@ export default <TestSuite>{
ValidationError,
'instance.instructions is of prohibited type [object Object]'
)
},
}
}

View File

@@ -264,5 +264,5 @@ export default <TestSuite>{
instructions
)
assertResultMatch(response, responses.prepareSettings.ticket, 'prepare')
},
}
}

View File

@@ -18,7 +18,10 @@ import {assertResultMatch, TestSuite} from '../../utils'
* - Check out "test/api/index.ts" for more information about the test runner.
*/
export default <TestSuite>{
'creates a ticket successfully with a sequence number': async (api, address) => {
'creates a ticket successfully with a sequence number': async (
api,
address
) => {
const expected = {
txJSON:
'{"TransactionType":"TicketCreate", "TicketCount": 2, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence":23,"Fee":"12"}',

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 = {
...instructionsWithMaxLedgerVersionOffset,
maxFee: '0.000012'
@@ -1263,10 +1265,7 @@ export default <TestSuite>{
)
},
'sets sequence to 0 if a ticketSequence is passed': async (
api,
address
) => {
'sets sequence to 0 if a ticketSequence is passed': async (api, address) => {
const localInstructions = {
...instructionsWithMaxLedgerVersionOffset,
maxFee: '0.000012',
@@ -1291,10 +1290,40 @@ export default <TestSuite>{
}
const response = await api.prepareTransaction(txJSON, localInstructions)
assertResultMatch(
response,
responses.preparePayment.ticket,
'prepare'
assertResultMatch(response, responses.preparePayment.ticket, 'prepare')
},
'rejects Promise if a sequence with value 0 is passed': async (
api,
address
) => {
const localInstructions = {
...instructionsWithMaxLedgerVersionOffset,
maxFee: '0.000012',
sequence: 0
}
const txJSON = {
TransactionType: 'Payment',
Account: address,
Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo',
Amount: {
currency: 'USD',
issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM',
value: '0.01'
},
SendMax: {
currency: 'USD',
issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM',
value: '0.01'
},
Flags: 0
}
await assertRejects(
api.prepareTransaction(txJSON, localInstructions),
ValidationError,
'`sequence` cannot be 0'
)
}
}

View File

@@ -9,7 +9,7 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100}
* - Check out "test/api/index.ts" for more information about the test runner.
*/
export default <TestSuite>{
simple: async (api, address) => {
'simple': async (api, address) => {
const result = await api.prepareTrustline(
address,
requests.prepareTrustline.simple,
@@ -18,7 +18,7 @@ export default <TestSuite>{
assertResultMatch(result, responses.prepareTrustline.simple, 'prepare')
},
frozen: async (api, address) => {
'frozen': async (api, address) => {
const result = await api.prepareTrustline(
address,
requests.prepareTrustline.frozen
@@ -26,7 +26,7 @@ export default <TestSuite>{
assertResultMatch(result, responses.prepareTrustline.frozen, 'prepare')
},
complex: async (api, address) => {
'complex': async (api, address) => {
const result = await api.prepareTrustline(
address,
requests.prepareTrustline.complex,
@@ -35,7 +35,7 @@ export default <TestSuite>{
assertResultMatch(result, responses.prepareTrustline.complex, 'prepare')
},
invalid: async (api, address) => {
'invalid': async (api, address) => {
const trustline = Object.assign({}, requests.prepareTrustline.complex)
delete trustline.limit // Make invalid
@@ -62,5 +62,5 @@ export default <TestSuite>{
localInstructions
)
assertResultMatch(result, responses.prepareTrustline.ticket, 'prepare')
},
}
}

View File

@@ -146,7 +146,10 @@ export default <TestSuite>{
schemaValidator.schemaValidate('sign', result)
},
'sign succeeds with source.amount/destination.minAmount': async (api, address) => {
'sign succeeds with source.amount/destination.minAmount': async (
api,
address
) => {
// See also: 'preparePayment with source.amount/destination.minAmount'
const txJSON =
@@ -337,5 +340,5 @@ export default <TestSuite>{
const result = api.sign(REQUEST_FIXTURES.ticket.txJSON, secret)
assert.deepEqual(result, RESPONSE_FIXTURES.ticket)
schemaValidator.schemaValidate('sign', result)
},
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -14,7 +14,7 @@ function setup(this: any, port_ = port) {
data: {openOnOtherPort: true}
})
})
.then(got => {
.then((got) => {
return new Promise((resolve, reject) => {
this.api = new RippleAPI({server: baseUrl + got.port})
this.api
@@ -35,7 +35,7 @@ function setup(this: any, port_ = port) {
}
function setupBroadcast(this: any) {
const servers = [port, port + 1].map(port_ => baseUrl + port_)
const servers = [port, port + 1].map((port_) => baseUrl + port_)
this.api = new RippleAPIBroadcast(servers)
return new Promise((resolve, reject) => {
this.api

View File

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

View File

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