From 2145c104fdce83416b8377f6219c240d567c377d Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Tue, 17 Dec 2019 10:35:59 -0800 Subject: [PATCH] run prettier format --- .prettierrc | 3 +- package.json | 2 + src/api.ts | 156 +-- src/broadcast.ts | 24 +- src/common/browser-hacks.ts | 13 +- src/common/connection.ts | 271 +++-- src/common/constants.ts | 16 +- src/common/errors.ts | 9 +- src/common/hashes/hash-prefix.ts | 14 +- src/common/hashes/index.ts | 82 +- src/common/hashes/ledgerspaces.ts | 29 +- src/common/hashes/sha512Half.ts | 6 +- src/common/hashes/shamap.ts | 37 +- src/common/index.ts | 16 +- src/common/rangeset.ts | 6 +- src/common/schema-validator.ts | 6 +- src/common/serverinfo.ts | 61 +- src/common/txflags.ts | 5 +- src/common/types/commands/account_info.ts | 20 +- src/common/types/commands/account_lines.ts | 24 +- src/common/types/commands/account_objects.ts | 87 +- src/common/types/commands/account_offers.ts | 32 +- src/common/types/commands/book_offers.ts | 30 +- src/common/types/commands/gateway_balances.ts | 20 +- src/common/types/commands/ledger_data.ts | 4 +- src/common/types/commands/ledger_entry.ts | 43 +- src/common/types/commands/server_info.ts | 68 +- src/common/types/objects/adjustments.ts | 12 +- src/common/types/objects/amounts.ts | 1 - src/common/types/objects/ledger.ts | 34 +- src/common/types/objects/ledger_data.ts | 4 +- src/common/types/objects/ledger_entries.ts | 255 ++--- src/common/types/objects/memos.ts | 5 +- src/common/types/objects/orders.ts | 16 +- src/common/types/objects/queue_data.ts | 18 +- src/common/types/objects/settings.ts | 40 +- src/common/types/objects/signers.ts | 2 +- src/common/types/objects/transactions.ts | 34 +- src/common/types/objects/trustlines.ts | 52 +- src/common/utils.ts | 105 +- src/common/validate.ts | 184 ++-- src/common/wswrapper.ts | 3 - src/index.ts | 4 +- src/ledger/accountinfo.ts | 21 +- src/ledger/accountobjects.ts | 19 +- src/ledger/balance-sheet.ts | 16 +- src/ledger/balances.ts | 31 +- src/ledger/ledger.ts | 11 +- src/ledger/orderbook.ts | 46 +- src/ledger/orders.ts | 11 +- src/ledger/parse/account-order.ts | 28 +- src/ledger/parse/amendment.ts | 2 - src/ledger/parse/amount.ts | 1 - src/ledger/parse/check-cancel.ts | 1 - src/ledger/parse/check-cash.ts | 5 +- src/ledger/parse/check-create.ts | 9 +- src/ledger/parse/deposit-preauth.ts | 2 +- src/ledger/parse/fee-update.ts | 3 +- src/ledger/parse/fields.ts | 8 +- src/ledger/parse/flags.ts | 7 +- src/ledger/parse/ledger.ts | 66 +- src/ledger/parse/order.ts | 11 +- src/ledger/parse/orderbook-order.ts | 39 +- src/ledger/parse/pathfind.ts | 46 +- src/ledger/parse/payment-channel.ts | 22 +- src/ledger/parse/payment.ts | 11 +- src/ledger/parse/settings.ts | 12 +- src/ledger/parse/transaction.ts | 45 +- src/ledger/parse/trustline.ts | 5 +- src/ledger/parse/utils.ts | 35 +- src/ledger/pathfind-types.ts | 70 +- src/ledger/pathfind.ts | 145 ++- src/ledger/payment-channel.ts | 9 +- src/ledger/settings.ts | 9 +- src/ledger/transaction.ts | 109 +- src/ledger/transactions.ts | 121 ++- src/ledger/trustlines.ts | 10 +- src/ledger/utils.ts | 65 +- src/offline/derive.ts | 12 +- src/offline/generate-address.ts | 22 +- src/offline/ledgerhash.ts | 72 +- src/offline/sign-payment-channel-claim.ts | 4 +- src/offline/verify-payment-channel-claim.ts | 7 +- src/server/server.ts | 8 +- src/transaction/check-cancel.ts | 13 +- src/transaction/check-cash.ts | 23 +- src/transaction/check-create.ts | 21 +- src/transaction/combine.ts | 17 +- src/transaction/escrow-cancellation.ts | 22 +- src/transaction/escrow-creation.ts | 40 +- src/transaction/escrow-execution.ts | 27 +- src/transaction/order.ts | 18 +- src/transaction/ordercancellation.ts | 19 +- src/transaction/payment-channel-claim.ts | 42 +- src/transaction/payment-channel-create.ts | 30 +- src/transaction/payment-channel-fund.ts | 22 +- src/transaction/payment.ts | 116 +- src/transaction/settings.ts | 52 +- src/transaction/sign.ts | 27 +- src/transaction/submit.ts | 5 +- src/transaction/trustline.ts | 29 +- src/transaction/types.ts | 161 ++- src/transaction/utils.ts | 162 ++- test/api/combine/index.ts | 6 +- test/api/computeLedgerHash/index.ts | 10 +- test/api/constructor/index.ts | 12 +- test/api/deriveAddress/index.ts | 2 +- test/api/deriveKeypair/index.ts | 2 +- test/api/deriveXAddress/index.ts | 4 +- test/api/dropsToXrp/index.ts | 2 +- test/api/errors/index.ts | 2 +- test/api/formatBidsAndAsks/index.ts | 8 +- test/api/generateAddress/index.ts | 8 +- test/api/generateXAddress/index.ts | 6 +- test/api/getAccountInfo/index.ts | 4 +- test/api/getAccountObjects/index.ts | 6 +- test/api/getBalanceSheet/index.ts | 6 +- test/api/getBalances/index.ts | 6 +- test/api/getFee/index.ts | 6 +- test/api/getFeeBase/index.ts | 2 +- test/api/getFeeRef/index.ts | 2 +- test/api/getLedger/index.ts | 8 +- test/api/getLedgerVersion/index.ts | 2 +- test/api/getOrderbook/index.ts | 8 +- test/api/getOrders/index.ts | 6 +- test/api/getPaths/index.ts | 8 +- test/api/getPaymentChannel/index.ts | 4 +- test/api/getServerInfo/index.ts | 6 +- test/api/getSettings/index.ts | 6 +- test/api/getTransaction/index.ts | 6 +- test/api/getTransactions/index.ts | 12 +- test/api/getTrustlines/index.ts | 8 +- test/api/hasNextPage/index.ts | 2 +- test/api/isConnected/index.ts | 2 +- test/api/isValidAddress/index.ts | 2 +- test/api/isValidSecret/index.ts | 2 +- test/api/prepareCheckCancel/index.ts | 2 +- test/api/prepareCheckCash/index.ts | 2 +- test/api/prepareCheckCreate/index.ts | 4 +- test/api/prepareEscrowCancellation/index.ts | 4 +- test/api/prepareEscrowCreation/index.ts | 5 +- test/api/prepareEscrowExecution/index.ts | 4 +- test/api/prepareOrder/index.ts | 4 +- test/api/prepareOrderCancellation/index.ts | 4 +- test/api/preparePayment/index.ts | 42 +- test/api/preparePaymentChannelClaim/index.ts | 8 +- test/api/preparePaymentChannelCreate/index.ts | 4 +- test/api/preparePaymentChannelFund/index.ts | 4 +- test/api/prepareSettings/index.ts | 20 +- test/api/prepareTransaction/index.ts | 8 +- test/api/prepareTrustline/index.ts | 4 +- test/api/request/index.ts | 2 +- test/api/requestNextPage/index.ts | 4 +- test/api/sign/index.ts | 12 +- test/api/signPaymentChannelClaim/index.ts | 2 +- test/api/submit/index.ts | 2 +- test/api/verifyPaymentChannelClaim/index.ts | 2 +- test/api/xrpToDrops/index.ts | 2 +- test/broadcast-api-test.ts | 98 +- test/connection-test.ts | 748 +++++++------ test/hashes-test.ts | 175 ++-- test/integration/broadcast-test.ts | 18 +- test/integration/connection-test.ts | 51 +- test/integration/integration-test.ts | 693 ++++++------ test/mock-rippled.ts | 991 ++++++++++-------- test/mocked-server.ts | 16 +- test/rangeset-test.ts | 118 +-- test/ripple-api-test-private.ts | 44 +- test/ripple-api-test.ts | 18 +- test/setup-api-web.ts | 79 +- test/setup-api.ts | 78 +- test/shamap-test.ts | 44 +- test/utils.ts | 8 +- yarn.lock | 5 + 174 files changed, 4152 insertions(+), 3228 deletions(-) diff --git a/.prettierrc b/.prettierrc index efcc93aa..66e6e819 100644 --- a/.prettierrc +++ b/.prettierrc @@ -5,5 +5,6 @@ "semi": false, "singleQuote": true, "trailingComma": "none", - "quoteProps": "consistent" + "quoteProps": "consistent", + "bracketSpacing": false } \ No newline at end of file diff --git a/package.json b/package.json index 61cb9a16..aa20b88a 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "mocha": "6.2.0", "mocha-junit-reporter": "^1.9.1", "nyc": "^14.1.1", + "prettier": "^1.19.1", "ts-node": "^8.4.1", "typescript": "^3.6.4", "webpack": "^4.41.2", @@ -63,6 +64,7 @@ "prepublish": "yarn clean && yarn build", "test": "TS_NODE_PROJECT=src/tsconfig.json nyc mocha --exit", "test:watch": "TS_NODE_PROJECT=src/tsconfig.json mocha --watch --reporter dot", + "format": "prettier --write '{src,test}/**/*.ts'", "lint": "eslint src/**/*.ts 'test/*-test.{ts,js}'", "perf": "./scripts/perf_test.sh", "start": "node scripts/http.js" diff --git a/src/api.ts b/src/api.ts index ee617111..c9a12cdc 100644 --- a/src/api.ts +++ b/src/api.ts @@ -24,8 +24,7 @@ import getBalances from './ledger/balances' import getBalanceSheet from './ledger/balance-sheet' import getPaths from './ledger/pathfind' import getOrders from './ledger/orders' -import {getOrderbook, - formatBidsAndAsks} from './ledger/orderbook' +import {getOrderbook, formatBidsAndAsks} from './ledger/orderbook' import {getSettings, parseAccountFlags} from './ledger/settings' import getAccountInfo from './ledger/accountinfo' import getAccountObjects from './ledger/accountobjects' @@ -47,7 +46,11 @@ import prepareSettings from './transaction/settings' import sign from './transaction/sign' import combine from './transaction/combine' import submit from './transaction/submit' -import {generateAddressAPI, GenerateAddressOptions, GeneratedAddress} from './offline/generate-address' +import { + generateAddressAPI, + GenerateAddressOptions, + GeneratedAddress +} from './offline/generate-address' import {deriveKeypair, deriveAddress, deriveXAddress} from './offline/derive' import computeLedgerHash from './offline/ledgerhash' import signPaymentChannelClaim from './offline/sign-payment-channel-claim' @@ -55,19 +58,28 @@ import verifyPaymentChannelClaim from './offline/verify-payment-channel-claim' import getLedger from './ledger/ledger' import { - AccountObjectsRequest, AccountObjectsResponse, - AccountOffersRequest, AccountOffersResponse, - AccountInfoRequest, AccountInfoResponse, - AccountLinesRequest, AccountLinesResponse, - BookOffersRequest, BookOffersResponse, - GatewayBalancesRequest, GatewayBalancesResponse, - LedgerRequest, LedgerResponse, - LedgerDataRequest, LedgerDataResponse, - LedgerEntryRequest, LedgerEntryResponse, - ServerInfoRequest, ServerInfoResponse, + AccountObjectsRequest, + AccountObjectsResponse, + AccountOffersRequest, + AccountOffersResponse, + AccountInfoRequest, + AccountInfoResponse, + AccountLinesRequest, + AccountLinesResponse, + BookOffersRequest, + BookOffersResponse, + GatewayBalancesRequest, + GatewayBalancesResponse, + LedgerRequest, + LedgerResponse, + LedgerDataRequest, + LedgerDataResponse, + LedgerEntryRequest, + LedgerEntryResponse, + ServerInfoRequest, + ServerInfoResponse } from './common/types/commands' - import RangeSet from './common/rangeset' import * as ledgerUtils from './ledger/utils' import * as transactionUtils from './transaction/utils' @@ -79,10 +91,10 @@ import {ConnectionUserOptions} from './common/connection' import {isValidXAddress, isValidClassicAddress} from 'ripple-address-codec' export interface APIOptions extends ConnectionUserOptions { - server?: string, - feeCushion?: number, - maxFeeXRP?: string, - proxy?: string, + server?: string + feeCushion?: number + maxFeeXRP?: string + proxy?: string timeout?: number } @@ -91,7 +103,7 @@ export interface APIOptions extends ConnectionUserOptions { * command. This varies from command to command, but we need to know it to * properly count across many requests. */ -function getCollectKeyFromCommand(command: string): string|undefined { +function getCollectKeyFromCommand(command: string): string | undefined { switch (command) { case 'account_offers': case 'book_offers': @@ -140,12 +152,12 @@ class RippleAPI extends EventEmitter { this.emit('connected') }) this.connection.on('disconnected', code => { - let finalCode = code; - // This is a backwards-compatible fix for this change in the ws library: + let finalCode = code + // This is a backwards-compatible fix for this change in the ws library: // https://github.com/websockets/ws/issues/1257 // TODO: Remove in next major, breaking version if (finalCode === 1005) { - finalCode = 1000; + finalCode = 1000 } this.emit('disconnected', finalCode) }) @@ -156,33 +168,51 @@ class RippleAPI extends EventEmitter { } } - /** * Makes a request to the API with the given command and * additional request body parameters. */ - async request(command: 'account_info', params: AccountInfoRequest): - Promise - async request(command: 'account_lines', params: AccountLinesRequest): - Promise - async request(command: 'account_objects', params: AccountObjectsRequest): - Promise - async request(command: 'account_offers', params: AccountOffersRequest): - Promise - async request(command: 'book_offers', params: BookOffersRequest): - Promise - async request(command: 'gateway_balances', params: GatewayBalancesRequest): - Promise - async request(command: 'ledger', params: LedgerRequest): - Promise - async request(command: 'ledger_data', params?: LedgerDataRequest): - Promise - async request(command: 'ledger_entry', params: LedgerEntryRequest): - Promise - async request(command: 'server_info', params?: ServerInfoRequest): - Promise - async request(command: string, params: any): - Promise + async request( + command: 'account_info', + params: AccountInfoRequest + ): Promise + async request( + command: 'account_lines', + params: AccountLinesRequest + ): Promise + async request( + command: 'account_objects', + params: AccountObjectsRequest + ): Promise + async request( + command: 'account_offers', + params: AccountOffersRequest + ): Promise + async request( + command: 'book_offers', + params: BookOffersRequest + ): Promise + async request( + command: 'gateway_balances', + params: GatewayBalancesRequest + ): Promise + async request( + command: 'ledger', + params: LedgerRequest + ): Promise + async request( + command: 'ledger_data', + params?: LedgerDataRequest + ): Promise + async request( + command: 'ledger_entry', + params: LedgerEntryRequest + ): Promise + async request( + command: 'server_info', + params?: ServerInfoRequest + ): Promise + async request(command: string, params: any): Promise async request(command: string, params: any = {}): Promise { return this.connection.request({ ...params, @@ -224,8 +254,10 @@ class RippleAPI extends EventEmitter { * * You can later submit the transaction with `submit()`. */ - async prepareTransaction(txJSON: TransactionJSON, instructions: Instructions = {}): - Promise { + async prepareTransaction( + txJSON: TransactionJSON, + instructions: Instructions = {} + ): Promise { return transactionUtils.prepareTransaction(txJSON, this, instructions) } @@ -253,16 +285,23 @@ class RippleAPI extends EventEmitter { * general use. Instead, use rippled's built-in pagination and make multiple * requests as needed. */ - async _requestAll(command: 'account_offers', params: AccountOffersRequest): - Promise - async _requestAll(command: 'book_offers', params: BookOffersRequest): - Promise - async _requestAll(command: 'account_lines', params: AccountLinesRequest): - Promise + async _requestAll( + command: 'account_offers', + params: AccountOffersRequest + ): Promise + async _requestAll( + command: 'book_offers', + params: BookOffersRequest + ): Promise + async _requestAll( + command: 'account_lines', + params: AccountLinesRequest + ): Promise async _requestAll( command: string, params: any = {}, - options: {collect?: string} = {}): Promise { + options: {collect?: string} = {} + ): Promise { // The data under collection is keyed based on the command. Fail if command // not recognized and collection key not provided. const collectKey = options.collect || getCollectKeyFromCommand(command) @@ -271,8 +310,7 @@ class RippleAPI extends EventEmitter { } // If limit is not provided, fetches all data over multiple requests. // NOTE: This may return much more than needed. Set limit when possible. - const countTo: number = - (params.limit !== undefined) ? params.limit : Infinity + const countTo: number = params.limit !== undefined ? params.limit : Infinity let count: number = 0 let marker: string = params.marker let lastBatchLength: number @@ -296,7 +334,7 @@ class RippleAPI extends EventEmitter { } else { lastBatchLength = 0 } - } while(!!marker && count < countTo && lastBatchLength !== 0) + } while (!!marker && count < countTo && lastBatchLength !== 0) return results } @@ -374,6 +412,4 @@ class RippleAPI extends EventEmitter { isValidSecret = schemaValidator.isValidSecret } -export { - RippleAPI -} +export {RippleAPI} diff --git a/src/broadcast.ts b/src/broadcast.ts index 23872cc2..8e1e8e24 100644 --- a/src/broadcast.ts +++ b/src/broadcast.ts @@ -1,24 +1,23 @@ - import * as _ from 'lodash' import {RippleAPI, APIOptions} from './api' class RippleAPIBroadcast extends RippleAPI { - ledgerVersion: number | undefined = undefined private _apis: RippleAPI[] constructor(servers, options: APIOptions = {}) { super(options) - const apis: RippleAPI[] = servers.map(server => new RippleAPI( - _.assign({}, options, {server}) - )) + const apis: RippleAPI[] = servers.map( + server => new RippleAPI(_.assign({}, options, {server})) + ) // exposed for testing this._apis = apis this.getMethodNames().forEach(name => { - this[name] = function() { // eslint-disable-line no-loop-func + this[name] = function() { + // eslint-disable-line no-loop-func return Promise.race(apis.map(api => api[name](...arguments))) } }) @@ -44,13 +43,16 @@ class RippleAPIBroadcast extends RippleAPI { apis.forEach(api => { api.on('ledger', this.onLedgerEvent.bind(this)) api.on('error', (errorCode, errorMessage, data) => - this.emit('error', errorCode, errorMessage, data)) + this.emit('error', errorCode, errorMessage, data) + ) }) } onLedgerEvent(ledger) { - if (ledger.ledgerVersion > this.ledgerVersion || - this.ledgerVersion === undefined) { + if ( + ledger.ledgerVersion > this.ledgerVersion || + this.ledgerVersion === undefined + ) { this.ledgerVersion = ledger.ledgerVersion this.emit('ledger', ledger) } @@ -68,6 +70,4 @@ class RippleAPIBroadcast extends RippleAPI { } } -export { - RippleAPIBroadcast -} +export {RippleAPIBroadcast} diff --git a/src/common/browser-hacks.ts b/src/common/browser-hacks.ts index 0da96fe4..2e4dc004 100644 --- a/src/common/browser-hacks.ts +++ b/src/common/browser-hacks.ts @@ -1,9 +1,9 @@ - function setPrototypeOf(object, prototype) { // Object.setPrototypeOf not supported on Internet Explorer 9 - Object.setPrototypeOf ? Object.setPrototypeOf(object, prototype) : - // @ts-ignore: Specifically a fallback for IE9 - object.__proto__ = prototype + Object.setPrototypeOf + ? Object.setPrototypeOf(object, prototype) + : // @ts-ignore: Specifically a fallback for IE9 + (object.__proto__ = prototype) } function getConstructorName(object: object): string { @@ -17,7 +17,4 @@ function getConstructorName(object: object): string { return functionConstructor ? functionConstructor[1] : classConstructor[1] } -export { - getConstructorName, - setPrototypeOf -} +export {getConstructorName, setPrototypeOf} diff --git a/src/common/connection.ts b/src/common/connection.ts index 8552f392..009ced86 100644 --- a/src/common/connection.ts +++ b/src/common/connection.ts @@ -3,9 +3,15 @@ import {EventEmitter} from 'events' import {parse as parseUrl} from 'url' import WebSocket from 'ws' import RangeSet from './rangeset' -import {RippledError, DisconnectedError, NotConnectedError, - TimeoutError, ResponseFormatError, ConnectionError, - RippledNotInitializedError} from './errors' +import { + RippledError, + DisconnectedError, + NotConnectedError, + TimeoutError, + ResponseFormatError, + ConnectionError, + RippledNotInitializedError +} from './errors' /** * ConnectionOptions is the configuration for the configuration object. @@ -19,7 +25,7 @@ export interface ConnectionOptions { key?: string passphrase?: string certificate?: string - timeout: number, + timeout: number connectionTimeout: number } @@ -31,21 +37,20 @@ export interface ConnectionOptions { export type ConnectionUserOptions = Partial class Connection extends EventEmitter { - private _url: string private _isReady: boolean = false - private _ws: null|WebSocket = null - protected _ledgerVersion: null|number = null + private _ws: null | WebSocket = null + protected _ledgerVersion: null | number = null private _availableLedgerVersions = new RangeSet() private _nextRequestID: number = 1 private _retry: number = 0 - private _connectTimer: null|NodeJS.Timeout = null - private _retryTimer: null|NodeJS.Timeout = null - private _heartbeatInterval: null|NodeJS.Timeout = null; - private _onOpenErrorBound: null| null|((...args: any[]) => void) = null - private _onUnexpectedCloseBound: null|((...args: any[]) => void) = null - private _fee_base: null|number = null - private _fee_ref: null|number = null + private _connectTimer: null | NodeJS.Timeout = null + private _retryTimer: null | NodeJS.Timeout = null + private _heartbeatInterval: null | NodeJS.Timeout = null + private _onOpenErrorBound: null | null | ((...args: any[]) => void) = null + private _onUnexpectedCloseBound: null | ((...args: any[]) => void) = null + private _fee_base: null | number = null + private _fee_ref: null | number = null private _trace: (id: string, message: string) => void = () => {} private _config: ConnectionOptions @@ -55,9 +60,9 @@ class Connection extends EventEmitter { this.setMaxListeners(Infinity) this._url = url this._config = { - timeout: (20 * 1000), - connectionTimeout: (2 * 1000), - ...options, + timeout: 20 * 1000, + connectionTimeout: 2 * 1000, + ...options } if (typeof options.trace === 'function') { this._trace = options.trace @@ -70,8 +75,7 @@ class Connection extends EventEmitter { this._ledgerVersion = Number(data.ledger_index) if (data.validated_ledgers) { this._availableLedgerVersions.reset() - this._availableLedgerVersions.parseAndAddRanges( - data.validated_ledgers) + this._availableLedgerVersions.parseAndAddRanges(data.validated_ledgers) } else { this._availableLedgerVersions.addValue(this._ledgerVersion) } @@ -151,17 +155,17 @@ class Connection extends EventEmitter { } _calculateTimeout(retriesCount) { - return (retriesCount < 40) - // First, for 2 seconds: 20 times per second - ? (1000 / 20) - : (retriesCount < 40 + 60) - // Then, for 1 minute: once per second - ? (1000) - : (retriesCount < 40 + 60 + 60) - // Then, for 10 minutes: once every 10 seconds - ? (10 * 1000) - // Then: once every 30 seconds - : (30 * 1000) + return retriesCount < 40 + ? // First, for 2 seconds: 20 times per second + 1000 / 20 + : retriesCount < 40 + 60 + ? // Then, for 1 minute: once per second + 1000 + : retriesCount < 40 + 60 + 60 + ? // Then, for 10 minutes: once every 10 seconds + 10 * 1000 + : // Then: once every 30 seconds + 30 * 1000 } _retryConnect() { @@ -228,8 +232,12 @@ class Connection extends EventEmitter { if (this._onUnexpectedCloseBound) { this._ws.removeListener('close', this._onUnexpectedCloseBound) } - this._onUnexpectedCloseBound = - this._onUnexpectedClose.bind(this, false, null, null) + this._onUnexpectedCloseBound = this._onUnexpectedClose.bind( + this, + false, + null, + null + ) this._ws.once('close', this._onUnexpectedCloseBound) } @@ -251,15 +259,18 @@ class Connection extends EventEmitter { if (this._config.proxy !== undefined) { const parsedURL = parseUrl(this._url) const parsedProxyURL = parseUrl(this._config.proxy) - const proxyOverrides = _.omitBy({ - secureEndpoint: (parsedURL.protocol === 'wss:'), - secureProxy: (parsedProxyURL.protocol === 'https:'), - auth: this._config.proxyAuthorization, - ca: this._config.trustedCertificates, - key: this._config.key, - passphrase: this._config.passphrase, - cert: this._config.certificate - }, _.isUndefined) + const proxyOverrides = _.omitBy( + { + secureEndpoint: parsedURL.protocol === 'wss:', + secureProxy: parsedProxyURL.protocol === 'https:', + auth: this._config.proxyAuthorization, + ca: this._config.trustedCertificates, + key: this._config.key, + passphrase: this._config.passphrase, + cert: this._config.certificate + }, + _.isUndefined + ) const proxyOptions = _.assign({}, parsedProxyURL, proxyOverrides) let HttpsProxyAgent try { @@ -273,12 +284,15 @@ class Connection extends EventEmitter { const base64 = Buffer.from(this._config.authorization).toString('base64') options.headers = {Authorization: `Basic ${base64}`} } - const optionsOverrides = _.omitBy({ - ca: this._config.trustedCertificates, - key: this._config.key, - passphrase: this._config.passphrase, - cert: this._config.certificate - }, _.isUndefined) + const optionsOverrides = _.omitBy( + { + ca: this._config.trustedCertificates, + key: this._config.key, + passphrase: this._config.passphrase, + cert: this._config.certificate + }, + _.isUndefined + ) const websocketOptions = _.assign({}, options, optionsOverrides) const websocket = new WebSocket(this._url, null, websocketOptions) // we will have a listener for each outstanding request, @@ -293,55 +307,69 @@ class Connection extends EventEmitter { this._clearConnectTimer() this._clearReconnectTimer() this._clearHeartbeatInterval() - return new Promise((_resolve, reject) => { - this._connectTimer = setTimeout(() => { - reject(new ConnectionError(`Error: connect() timed out after ${this._config.connectionTimeout} ms. ` + - `If your internet connection is working, the rippled server may be blocked or inaccessible.`)) - }, this._config.connectionTimeout) - if (!this._url) { - reject(new ConnectionError('Cannot connect because no server was specified')) - } - const resolve = () => { - this._startHeartbeatInterval(); - _resolve(); - } - if (this._state === WebSocket.OPEN) { - resolve() - } else if (this._state === WebSocket.CONNECTING) { - this._ws.once('open', () => resolve) - } else { - this._ws = this._createWebSocket() - // when an error causes the connection to close, the close event - // should still be emitted; the "ws" documentation says: "The close - // event is also emitted when then underlying net.Socket closes the - // connection (end or close)." - // In case if there is connection error (say, server is not responding) - // we must return this error to connection's caller. After successful - // opening, we will forward all errors to main api object. - this._onOpenErrorBound = this._onOpenError.bind(this, reject) - this._ws.once('error', this._onOpenErrorBound) - this._ws.on('message', this._onMessage.bind(this)) - // in browser close event can came before open event, so we must - // resolve connect's promise after reconnect in that case. - // after open event we will rebound _onUnexpectedCloseBound - // without resolve and reject functions - this._onUnexpectedCloseBound = this._onUnexpectedClose.bind(this, true, - resolve, reject) - this._ws.once('close', this._onUnexpectedCloseBound) - this._ws.once('open', () => { - return this._onOpen().then(resolve, reject) + return ( + new Promise((_resolve, reject) => { + this._connectTimer = setTimeout(() => { + reject( + new ConnectionError( + `Error: connect() timed out after ${this._config.connectionTimeout} ms. ` + + `If your internet connection is working, the rippled server may be blocked or inaccessible.` + ) + ) + }, this._config.connectionTimeout) + if (!this._url) { + reject( + new ConnectionError( + 'Cannot connect because no server was specified' + ) + ) + } + const resolve = () => { + this._startHeartbeatInterval() + _resolve() + } + if (this._state === WebSocket.OPEN) { + resolve() + } else if (this._state === WebSocket.CONNECTING) { + this._ws.once('open', () => resolve) + } else { + this._ws = this._createWebSocket() + // when an error causes the connection to close, the close event + // should still be emitted; the "ws" documentation says: "The close + // event is also emitted when then underlying net.Socket closes the + // connection (end or close)." + // In case if there is connection error (say, server is not responding) + // we must return this error to connection's caller. After successful + // opening, we will forward all errors to main api object. + this._onOpenErrorBound = this._onOpenError.bind(this, reject) + this._ws.once('error', this._onOpenErrorBound) + this._ws.on('message', this._onMessage.bind(this)) + // in browser close event can came before open event, so we must + // resolve connect's promise after reconnect in that case. + // after open event we will rebound _onUnexpectedCloseBound + // without resolve and reject functions + this._onUnexpectedCloseBound = this._onUnexpectedClose.bind( + this, + true, + resolve, + reject + ) + this._ws.once('close', this._onUnexpectedCloseBound) + this._ws.once('open', () => { + return this._onOpen().then(resolve, reject) + }) + } + }) + // Once we have a resolution or rejection, clear the timeout timer as no + // longer needed. + .then(() => { + this._clearConnectTimer() }) - } - }) - // Once we have a resolution or rejection, clear the timeout timer as no - // longer needed. - .then(() => { - this._clearConnectTimer() - }) - .catch((err) => { - this._clearConnectTimer() - throw err; - }) + .catch(err => { + this._clearConnectTimer() + throw err + }) + ) } disconnect(): Promise { @@ -380,20 +408,20 @@ class Connection extends EventEmitter { reconnect() { // NOTE: We currently have a "reconnecting" event, but that only triggers through - // _retryConnect, which was written in a way that is required to run as an internal + // _retryConnect, which was written in a way that is required to run as an internal // part of the post-disconnect connect() flow. // See: https://github.com/ripple/ripple-lib/pull/1101#issuecomment-565360423 - this.emit('reconnect'); + this.emit('reconnect') return this.disconnect().then(() => this.connect()) } private _clearHeartbeatInterval = () => { - clearInterval(this._heartbeatInterval); + clearInterval(this._heartbeatInterval) } private _startHeartbeatInterval = () => { this._clearHeartbeatInterval() - this._heartbeatInterval = setInterval(() => this._heartbeat(), 1000 * 60); + this._heartbeatInterval = setInterval(() => this._heartbeat(), 1000 * 60) } /** @@ -401,12 +429,12 @@ class Connection extends EventEmitter { * If this succeeds, we're good. If it fails, disconnect so that the consumer can reconnect, if desired. */ private _heartbeat = () => { - return this.request({command: "ping"}).catch(() => this.reconnect()); + return this.request({command: 'ping'}).catch(() => this.reconnect()) } _whenReady(promise: Promise): Promise { return new Promise((resolve, reject) => { - promise.catch(reject); + promise.catch(reject) if (!this._shouldBeConnected) { reject(new NotConnectedError()) } else if (this._state === WebSocket.OPEN && this._isReady) { @@ -422,9 +450,14 @@ class Connection extends EventEmitter { } hasLedgerVersions(lowLedgerVersion, highLedgerVersion): Promise { - return this._whenReady(Promise.resolve( - this._availableLedgerVersions.containsRange( - lowLedgerVersion, highLedgerVersion || this._ledgerVersion))) + return this._whenReady( + Promise.resolve( + this._availableLedgerVersions.containsRange( + lowLedgerVersion, + highLedgerVersion || this._ledgerVersion + ) + ) + ) } hasLedgerVersion(ledgerVersion): Promise { @@ -490,12 +523,18 @@ class Connection extends EventEmitter { this.once(eventName, response => { if (response.status === 'error') { - _reject(new RippledError(response.error_message || response.error, response)) + _reject( + new RippledError(response.error_message || response.error, response) + ) } else if (response.status === 'success') { _resolve(response.result) } else { - _reject(new ResponseFormatError( - 'unrecognized status: ' + response.status, response)) + _reject( + new ResponseFormatError( + 'unrecognized status: ' + response.status, + response + ) + ) } }) @@ -504,14 +543,16 @@ class Connection extends EventEmitter { // JSON.stringify automatically removes keys with value of 'undefined' const message = JSON.stringify(Object.assign({}, request, {id})) - this._whenReady(this._send(message)).then(() => { - const delay = timeout || this._config.timeout - timer = setTimeout(() => _reject(new TimeoutError()), delay) - // Node.js won't exit if a timer is still running, so we tell Node to ignore (Node will still wait for the request to complete) - if (timer.unref) { - timer.unref() - } - }).catch(_reject) + this._whenReady(this._send(message)) + .then(() => { + const delay = timeout || this._config.timeout + timer = setTimeout(() => _reject(new TimeoutError()), delay) + // Node.js won't exit if a timer is still running, so we tell Node to ignore (Node will still wait for the request to complete) + if (timer.unref) { + timer.unref() + } + }) + .catch(_reject) }) } } diff --git a/src/common/constants.ts b/src/common/constants.ts index 8d38a824..f30ecfc2 100644 --- a/src/common/constants.ts +++ b/src/common/constants.ts @@ -1,9 +1,7 @@ - import {txFlagIndices} from './txflags' // Ordering from https://developers.ripple.com/accountroot.html const accountRootFlags = { - // lsfDefaultRipple: // Enable rippling on trust lines by default. // Required for issuing addresses; discouraged for others. @@ -73,8 +71,12 @@ const AccountFlagIndices = { } const AccountFields = { - EmailHash: {name: 'emailHash', encoding: 'hex', - length: 32, defaults: '00000000000000000000000000000000'}, + EmailHash: { + name: 'emailHash', + encoding: 'hex', + length: 32, + defaults: '00000000000000000000000000000000' + }, WalletLocator: {name: 'walletLocator'}, MessageKey: {name: 'messageKey'}, Domain: {name: 'domain', encoding: 'hex'}, @@ -82,8 +84,4 @@ const AccountFields = { TickSize: {name: 'tickSize', defaults: 0} } -export { - AccountFields, - AccountFlagIndices, - AccountFlags -} +export {AccountFields, AccountFlagIndices, AccountFlags} diff --git a/src/common/errors.ts b/src/common/errors.ts index 4e4ccd3d..ce26878c 100644 --- a/src/common/errors.ts +++ b/src/common/errors.ts @@ -1,9 +1,7 @@ - import {inspect} from 'util' import * as browserHacks from './browser-hacks' class RippleError extends Error { - name: string message: string data?: any @@ -70,8 +68,11 @@ class MissingLedgerHistoryError extends RippleError { class PendingLedgerVersionError extends RippleError { constructor(message?: string) { - super(message || 'maxLedgerVersion is greater than server\'s most recent' + - ' validated ledger') + super( + message || + "maxLedgerVersion is greater than server's most recent" + + ' validated ledger' + ) } } diff --git a/src/common/hashes/hash-prefix.ts b/src/common/hashes/hash-prefix.ts index 54b07a4e..efdb0324 100644 --- a/src/common/hashes/hash-prefix.ts +++ b/src/common/hashes/hash-prefix.ts @@ -11,18 +11,18 @@ * some arbitrary string. For example "TXN". */ - enum HashPrefix { +enum HashPrefix { // transaction plus signature to give transaction ID - TRANSACTION_ID = 0x54584E00, // 'TXN' + TRANSACTION_ID = 0x54584e00, // 'TXN' // transaction plus metadata - TRANSACTION_NODE = 0x534E4400, // 'TND' + TRANSACTION_NODE = 0x534e4400, // 'TND' // inner node in tree - INNER_NODE = 0x4D494E00, // 'MIN' + INNER_NODE = 0x4d494e00, // 'MIN' // leaf node in tree - LEAF_NODE = 0x4D4C4E00, // 'MLN' + LEAF_NODE = 0x4d4c4e00, // 'MLN' // inner transaction to sign TRANSACTION_SIGN = 0x53545800, // 'STX' @@ -31,10 +31,10 @@ TRANSACTION_SIGN_TESTNET = 0x73747800, // 'stx' // inner transaction to multisign - TRANSACTION_MULTISIGN = 0x534D5400, // 'SMT' + TRANSACTION_MULTISIGN = 0x534d5400, // 'SMT' // ledger - LEDGER = 0x4C575200 // 'LWR' + LEDGER = 0x4c575200 // 'LWR' } export default HashPrefix diff --git a/src/common/hashes/index.ts b/src/common/hashes/index.ts index 8ad11fba..b18a7000 100644 --- a/src/common/hashes/index.ts +++ b/src/common/hashes/index.ts @@ -18,8 +18,11 @@ const bytesToHex = (bytes: number[]): string => { return Buffer.from(bytes).toString('hex') } -const bigintToHex = (integerString: string | number | BigNumber, byteLength: number): string => { - const hex = (new BigNumber(integerString)).toString(16) +const bigintToHex = ( + integerString: string | number | BigNumber, + byteLength: number +): string => { + const hex = new BigNumber(integerString).toString(16) return padLeftZero(hex, byteLength * 2) } @@ -28,12 +31,15 @@ const ledgerSpaceHex = (name: string): string => { } const addressToHex = (address: string): string => { - return (Buffer.from(decodeAccountID(address))).toString('hex') + return Buffer.from(decodeAccountID(address)).toString('hex') } 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 @@ -51,7 +57,7 @@ const addLengthPrefix = (hex: string): string => { return bytesToHex([193 + (x >>> 8), x & 0xff]) + hex } else if (length <= 918744) { const x = length - 12481 - return bytesToHex([241 + (x >>> 16), x >>> 8 & 0xff, x & 0xff]) + hex + return bytesToHex([241 + (x >>> 16), (x >>> 8) & 0xff, x & 0xff]) + hex } throw new Error('Variable integer overflow.') } @@ -65,7 +71,9 @@ export const computeTransactionHash = (txJSON: any): string => { return computeBinaryTransactionHash(encode(txJSON)) } -export const computeBinaryTransactionSigningHash = (txBlobHex: string): string => { +export const computeBinaryTransactionSigningHash = ( + txBlobHex: string +): string => { const prefix = HashPrefix.TRANSACTION_SIGN.toString(16).toUpperCase() return sha512Half(prefix + txBlobHex) } @@ -79,9 +87,9 @@ export const computeAccountHash = (address: string): string => { } export const computeSignerListHash = (address: string): string => { - return sha512Half(ledgerSpaceHex('signerList') + - addressToHex(address) + - '00000000') // uint32(0) signer list index + return sha512Half( + ledgerSpaceHex('signerList') + addressToHex(address) + '00000000' + ) // uint32(0) signer list index } export const computeOrderHash = (address: string, sequence: number): string => { @@ -89,18 +97,24 @@ export const computeOrderHash = (address: string, sequence: number): string => { return sha512Half(prefix + addressToHex(address) + intToHex(sequence, 4)) } -export const computeTrustlineHash = (address1: string, address2: string, currency: string): string => { +export const computeTrustlineHash = ( + address1: string, + address2: string, + currency: string +): string => { const address1Hex = addressToHex(address1) const address2Hex = addressToHex(address2) - const swap = (new BigNumber(address1Hex, 16)).isGreaterThan( - new BigNumber(address2Hex, 16)) + const swap = new BigNumber(address1Hex, 16).isGreaterThan( + new BigNumber(address2Hex, 16) + ) const lowAddressHex = swap ? address2Hex : address1Hex const highAddressHex = swap ? address1Hex : address2Hex const prefix = ledgerSpaceHex('rippleState') - return sha512Half(prefix + lowAddressHex + highAddressHex + - currencyToHex(currency)) + return sha512Half( + prefix + lowAddressHex + highAddressHex + currencyToHex(currency) + ) } export const computeTransactionTreeHash = (transactions: any[]): string => { @@ -131,25 +145,35 @@ export const computeStateTreeHash = (entries: any[]): string => { // see rippled Ledger::updateHash() export const computeLedgerHash = (ledgerHeader): string => { const prefix = HashPrefix.LEDGER.toString(16).toUpperCase() - return sha512Half(prefix + - intToHex(ledgerHeader.ledger_index, 4) + - bigintToHex(ledgerHeader.total_coins, 8) + - ledgerHeader.parent_hash + - ledgerHeader.transaction_hash + - ledgerHeader.account_hash + - intToHex(ledgerHeader.parent_close_time, 4) + - intToHex(ledgerHeader.close_time, 4) + - intToHex(ledgerHeader.close_time_resolution, 1) + - intToHex(ledgerHeader.close_flags, 1) + return sha512Half( + prefix + + intToHex(ledgerHeader.ledger_index, 4) + + bigintToHex(ledgerHeader.total_coins, 8) + + ledgerHeader.parent_hash + + ledgerHeader.transaction_hash + + ledgerHeader.account_hash + + intToHex(ledgerHeader.parent_close_time, 4) + + intToHex(ledgerHeader.close_time, 4) + + intToHex(ledgerHeader.close_time_resolution, 1) + + intToHex(ledgerHeader.close_flags, 1) ) } export const computeEscrowHash = (address, sequence): string => { - return sha512Half(ledgerSpaceHex('escrow') + addressToHex(address) + - intToHex(sequence, 4)) + return sha512Half( + ledgerSpaceHex('escrow') + addressToHex(address) + intToHex(sequence, 4) + ) } -export const computePaymentChannelHash = (address, dstAddress, sequence): string => { - return sha512Half(ledgerSpaceHex('paychan') + addressToHex(address) + - addressToHex(dstAddress) + intToHex(sequence, 4)) +export const computePaymentChannelHash = ( + address, + dstAddress, + sequence +): string => { + return sha512Half( + ledgerSpaceHex('paychan') + + addressToHex(address) + + addressToHex(dstAddress) + + intToHex(sequence, 4) + ) } diff --git a/src/common/hashes/ledgerspaces.ts b/src/common/hashes/ledgerspaces.ts index 1bd6dc71..0959b3ae 100644 --- a/src/common/hashes/ledgerspaces.ts +++ b/src/common/hashes/ledgerspaces.ts @@ -1,4 +1,3 @@ - /** * Ripple ledger namespace prefixes. * @@ -8,18 +7,18 @@ * Each namespace is just a single character prefix. */ export default { - account : 'a', - dirNode : 'd', - generatorMap : 'g', - rippleState : 'r', - offer : 'o', // Entry for an offer. - ownerDir : 'O', // Directory of things owned by an account. - bookDir : 'B', // Directory of order books. - contract : 'c', - skipList : 's', - amendment : 'f', - feeSettings : 'e', - signerList : 'S', - escrow : 'u', - paychan : 'x' + account: 'a', + dirNode: 'd', + generatorMap: 'g', + rippleState: 'r', + offer: 'o', // Entry for an offer. + ownerDir: 'O', // Directory of things owned by an account. + bookDir: 'B', // Directory of order books. + contract: 'c', + skipList: 's', + amendment: 'f', + feeSettings: 'e', + signerList: 'S', + escrow: 'u', + paychan: 'x' } diff --git a/src/common/hashes/sha512Half.ts b/src/common/hashes/sha512Half.ts index f830417d..114ed821 100644 --- a/src/common/hashes/sha512Half.ts +++ b/src/common/hashes/sha512Half.ts @@ -1,7 +1,11 @@ import {createHash} from 'crypto' const sha512Half = (hex: string): string => { - return createHash('sha512').update(Buffer.from(hex, 'hex')).digest('hex').toUpperCase().slice(0, 64) + return createHash('sha512') + .update(Buffer.from(hex, 'hex')) + .digest('hex') + .toUpperCase() + .slice(0, 64) } export default sha512Half diff --git a/src/common/hashes/shamap.ts b/src/common/hashes/shamap.ts index 9e10b2c4..21acb419 100644 --- a/src/common/hashes/shamap.ts +++ b/src/common/hashes/shamap.ts @@ -1,6 +1,7 @@ import hashPrefix from './hash-prefix' import sha512Half from './sha512Half' -const HEX_ZERO = '0000000000000000000000000000000000000000000000000000000000000000' +const HEX_ZERO = + '0000000000000000000000000000000000000000000000000000000000000000' export enum NodeType { INNER = 1, @@ -18,15 +19,17 @@ export abstract class Node { public constructor() {} public addItem(_tag: string, _node: Node): void { - throw new Error('Called unimplemented virtual method SHAMapTreeNode#addItem.') + throw new Error( + 'Called unimplemented virtual method SHAMapTreeNode#addItem.' + ) } - public get hash(): string|void { - throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.'); + public get hash(): string | void { + throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.') } } export class InnerNode extends Node { - public leaves: { [slot: number]: Node } + public leaves: {[slot: number]: Node} public type: NodeType public depth: number public empty: boolean @@ -48,9 +51,10 @@ export class InnerNode extends Node { * @param {string} tag equates to a ledger entry `index` * @param {Node} node to add * @return {void} - */ + */ + public addItem(tag: string, node: Node): void { - const existingNode = this.getNode(parseInt(tag[this.depth],16)) + const existingNode = this.getNode(parseInt(tag[this.depth], 16)) if (existingNode) { // A node already exists in this slot if (existingNode instanceof InnerNode) { @@ -60,15 +64,16 @@ export class InnerNode extends Node { if (existingNode.tag === tag) { // Collision throw new Error( - 'Tried to add a node to a SHAMap that was already in there.') + 'Tried to add a node to a SHAMap that was already in there.' + ) } else { // Turn it into an inner node const newInnerNode = new InnerNode(this.depth + 1) - + // Parent new and existing node newInnerNode.addItem(existingNode.tag, existingNode) newInnerNode.addItem(tag, node) - + // And place the newly created inner node in the slot this.setNode(parseInt(tag[this.depth], 16), newInnerNode) } @@ -87,7 +92,7 @@ export class InnerNode extends Node { */ public setNode(slot: number, node: Node): void { if (slot < 0 || slot > 15) { - throw new Error ('Invalid slot: slot must be between 0-15.') + throw new Error('Invalid slot: slot must be between 0-15.') } this.leaves[slot] = node this.empty = false @@ -100,8 +105,8 @@ export class InnerNode extends Node { */ public getNode(slot: number): Node { if (slot < 0 || slot > 15) { - throw new Error ('Invalid slot: slot must be between 0-15.') - } + throw new Error('Invalid slot: slot must be between 0-15.') + } return this.leaves[slot] } @@ -113,7 +118,7 @@ export class InnerNode extends Node { } const prefix = hashPrefix.INNER_NODE.toString(16) return sha512Half(prefix + hex) - } + } } export class Leaf extends Node { @@ -135,7 +140,7 @@ export class Leaf extends Node { this.data = data } - public get hash(): string|void { + public get hash(): string | void { switch (this.type) { case NodeType.ACCOUNT_STATE: const leafPrefix = hashPrefix.LEAF_NODE.toString(16) @@ -149,7 +154,7 @@ export class Leaf extends Node { default: throw new Error('Tried to hash a SHAMap node of unknown type.') } - } + } } export class SHAMap { diff --git a/src/common/index.ts b/src/common/index.ts index a0ad99b1..42cf93b6 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -6,16 +6,15 @@ import {xAddressToClassicAddress, isValidXAddress} from 'ripple-address-codec' export function ensureClassicAddress(account: string): string { if (isValidXAddress(account)) { - const { - classicAddress, - tag - } = xAddressToClassicAddress(account) + const {classicAddress, tag} = xAddressToClassicAddress(account) // Except for special cases, X-addresses used for requests // must not have an embedded tag. In other words, // `tag` should be `false`. if (tag !== false) { - throw new Error('This command does not support the use of a tag. Use an address without a tag.') + throw new Error( + 'This command does not support the use of a tag. Use an address without a tag.' + ) } // For rippled requests that use an account, always use a classic address. @@ -25,12 +24,7 @@ export function ensureClassicAddress(account: string): string { } } -export { - constants, - errors, - validate, - serverInfo -} +export {constants, errors, validate, serverInfo} export { dropsToXrp, xrpToDrops, diff --git a/src/common/rangeset.ts b/src/common/rangeset.ts index 82e0780e..d4ec2334 100644 --- a/src/common/rangeset.ts +++ b/src/common/rangeset.ts @@ -18,7 +18,6 @@ function mergeIntervals(intervals: Interval[]): Interval[] { } class RangeSet { - ranges: Array<[number, number]> constructor() { @@ -30,8 +29,9 @@ class RangeSet { } serialize() { - return this.ranges.map(range => - range[0].toString() + '-' + range[1].toString()).join(',') + return this.ranges + .map(range => range[0].toString() + '-' + range[1].toString()) + .join(',') } addRange(start: number, end: number) { diff --git a/src/common/schema-validator.ts b/src/common/schema-validator.ts index 7d74da60..a1340c3a 100644 --- a/src/common/schema-validator.ts +++ b/src/common/schema-validator.ts @@ -175,8 +175,4 @@ function isValidAddress(address: string): boolean { return isValidXAddress(address) || isValidClassicAddress(address) } -export { - schemaValidate, - isValidSecret, - isValidAddress -} +export {schemaValidate, isValidSecret, isValidAddress} diff --git a/src/common/serverinfo.ts b/src/common/serverinfo.ts index f1e50ad5..fde114ec 100644 --- a/src/common/serverinfo.ts +++ b/src/common/serverinfo.ts @@ -4,32 +4,32 @@ import BigNumber from 'bignumber.js' import {RippleAPI} from '..' export type GetServerInfoResponse = { - buildVersion: string, - completeLedgers: string, - hostID: string, - ioLatencyMs: number, + buildVersion: string + completeLedgers: string + hostID: string + ioLatencyMs: number load?: { - jobTypes: Array, + jobTypes: Array threads: number - }, + } lastClose: { - convergeTimeS: number, + convergeTimeS: number proposers: number - }, - loadFactor: number, - peers: number, - pubkeyNode: string, - pubkeyValidator?: string, - serverState: string, + } + loadFactor: number + peers: number + pubkeyNode: string + pubkeyValidator?: string + serverState: string validatedLedger: { - age: number, - baseFeeXRP: string, - hash: string, - reserveBaseXRP: string, - reserveIncrementXRP: string, + age: number + baseFeeXRP: string + hash: string + reserveBaseXRP: string + reserveIncrementXRP: string ledgerVersion: number - }, - validationQuorum: number, + } + validationQuorum: number networkLedger?: string } @@ -51,12 +51,9 @@ function getServerInfo(this: RippleAPI): Promise { reserveIncXrp: 'reserveIncrementXRP', seq: 'ledgerVersion' }) - info.validatedLedger.baseFeeXRP = - info.validatedLedger.baseFeeXRP.toString() - info.validatedLedger.reserveBaseXRP = - info.validatedLedger.reserveBaseXRP.toString() - info.validatedLedger.reserveIncrementXRP = - info.validatedLedger.reserveIncrementXRP.toString() + info.validatedLedger.baseFeeXRP = info.validatedLedger.baseFeeXRP.toString() + info.validatedLedger.reserveBaseXRP = info.validatedLedger.reserveBaseXRP.toString() + info.validatedLedger.reserveIncrementXRP = info.validatedLedger.reserveIncrementXRP.toString() } return info }) @@ -64,10 +61,7 @@ function getServerInfo(this: RippleAPI): Promise { // This is a public API that can be called directly. // This is not used by the `prepare*` methods. See `src/transaction/utils.ts` -async function getFee( - this: RippleAPI, - cushion?: number -): Promise { +async function getFee(this: RippleAPI, cushion?: number): Promise { if (cushion === undefined) { cushion = this._feeCushion } @@ -82,10 +76,7 @@ async function getFee( // Cap fee to `this._maxFeeXRP` fee = BigNumber.min(fee, this._maxFeeXRP) // Round fee to 6 decimal places - return (new BigNumber(fee.toFixed(6))).toString(10) + return new BigNumber(fee.toFixed(6)).toString(10) } -export { - getServerInfo, - getFee -} +export {getServerInfo, getFee} diff --git a/src/common/txflags.ts b/src/common/txflags.ts index b9f7a451..9991153d 100644 --- a/src/common/txflags.ts +++ b/src/common/txflags.ts @@ -58,7 +58,4 @@ const txFlagIndices = { } } -export { - txFlags, - txFlagIndices -} +export {txFlags, txFlagIndices} diff --git a/src/common/types/commands/account_info.ts b/src/common/types/commands/account_info.ts index 78bf6a69..13b74037 100644 --- a/src/common/types/commands/account_info.ts +++ b/src/common/types/commands/account_info.ts @@ -5,19 +5,19 @@ import { } from '../objects' export interface AccountInfoRequest { - account: string, - strict?: boolean, - queue?: boolean, - ledger_hash?: string, - ledger_index?: number | ('validated' | 'closed' | 'current'), + account: string + strict?: boolean + queue?: boolean + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') signer_lists?: boolean } export interface AccountInfoResponse { - account_data: AccountRootLedgerEntry, - signer_lists?: SignerListLedgerEntry[], - ledger_current_index?: number, - ledger_index?: number, - queue_data?: QueueData, + account_data: AccountRootLedgerEntry + signer_lists?: SignerListLedgerEntry[] + ledger_current_index?: number + ledger_index?: number + queue_data?: QueueData validated?: boolean } diff --git a/src/common/types/commands/account_lines.ts b/src/common/types/commands/account_lines.ts index e380d151..352597ef 100644 --- a/src/common/types/commands/account_lines.ts +++ b/src/common/types/commands/account_lines.ts @@ -1,19 +1,19 @@ import {Trustline} from '../objects' export interface AccountLinesRequest { - account: string, - ledger_hash?: string, - ledger_index?: number | ('validated' | 'closed' | 'current'), - peer?: string, - limit?: number, - marker?: any, + account: string + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + peer?: string + limit?: number + marker?: any } export interface AccountLinesResponse { - account: string, - lines: Trustline[], - ledger_current_index?: number, - ledger_index?: number, - ledger_hash?: string, - marker?: any, + account: string + lines: Trustline[] + ledger_current_index?: number + ledger_index?: number + ledger_hash?: string + marker?: any } diff --git a/src/common/types/commands/account_objects.ts b/src/common/types/commands/account_objects.ts index ffa0a019..f19f713a 100644 --- a/src/common/types/commands/account_objects.ts +++ b/src/common/types/commands/account_objects.ts @@ -1,84 +1,91 @@ import { - CheckLedgerEntry, RippleStateLedgerEntry, - OfferLedgerEntry, SignerListLedgerEntry, - EscrowLedgerEntry, PayChannelLedgerEntry, + CheckLedgerEntry, + RippleStateLedgerEntry, + OfferLedgerEntry, + SignerListLedgerEntry, + EscrowLedgerEntry, + PayChannelLedgerEntry, DepositPreauthLedgerEntry } from '../objects' export interface GetAccountObjectsOptions { - type?: string | ( - 'check' | - 'escrow' | - 'offer' | - 'payment_channel' | - 'signer_list' | - 'state' - ), - ledgerHash?: string, - ledgerIndex?: number | ('validated' | 'closed' | 'current'), - limit?: number, + type?: + | string + | ( + | 'check' + | 'escrow' + | 'offer' + | 'payment_channel' + | 'signer_list' + | 'state' + ) + ledgerHash?: string + ledgerIndex?: number | ('validated' | 'closed' | 'current') + limit?: number marker?: string } export interface AccountObjectsRequest { - account: string, + account: string // (Optional) Filter results to include only this type of ledger object. - type?: string | ( - 'check' | - 'escrow' | - 'offer' | - 'payment_channel' | - 'signer_list' | - 'state' - ), + type?: + | string + | ( + | 'check' + | 'escrow' + | 'offer' + | 'payment_channel' + | 'signer_list' + | 'state' + ) // (Optional) A 20-byte hex string for the ledger version to use. - ledger_hash?: string, + ledger_hash?: string // (Optional) The sequence number of the ledger to use, // or a shortcut string to choose a ledger automatically. - ledger_index?: number | ('validated' | 'closed' | 'current'), + ledger_index?: number | ('validated' | 'closed' | 'current') - limit?: number, + limit?: number marker?: string } export interface AccountObjectsResponse { - account: string, + account: string // Array of objects owned by this account. // from the getAccountObjects section of the dev center account_objects: Array< - CheckLedgerEntry | - RippleStateLedgerEntry | - OfferLedgerEntry | - SignerListLedgerEntry | - EscrowLedgerEntry | - PayChannelLedgerEntry | - DepositPreauthLedgerEntry - >, + | CheckLedgerEntry + | RippleStateLedgerEntry + | OfferLedgerEntry + | SignerListLedgerEntry + | EscrowLedgerEntry + | PayChannelLedgerEntry + | DepositPreauthLedgerEntry + > // (May be omitted) The identifying hash of the ledger // that was used to generate this response. - ledger_hash?: string, + ledger_hash?: string // (May be omitted) The sequence number of the ledger version // that was used to generate this response. - ledger_index?: number, + ledger_index?: number // (May be omitted) The sequence number of the current in-progress ledger // version that was used to generate this response. - ledger_current_index?: number, + ledger_current_index?: number // The limit that was used in this request, if any. - limit?: number, + limit?: number // Server-defined value indicating the response is paginated. Pass this // to the next call to resume where this call left off. Omitted when there // are no additional pages after this one. - marker?: string, + marker?: string // If true, this information comes from a ledger version // that has been validated by consensus. diff --git a/src/common/types/commands/account_offers.ts b/src/common/types/commands/account_offers.ts index dc9f8af3..db148a9d 100644 --- a/src/common/types/commands/account_offers.ts +++ b/src/common/types/commands/account_offers.ts @@ -1,27 +1,27 @@ import {RippledAmount} from '../objects' export interface AccountOffersRequest { - account: string, - ledger_hash?: string, - ledger_index?: number | ('validated' | 'closed' | 'current'), - limit?: number, - marker?: any, + account: string + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + limit?: number + marker?: any } export interface AccountOffersResponse { - account: string, - ledger_hash?: string, - ledger_current_index?: number, - ledger_index?: number, - marker?: any, - offers?: AccountOffer[], + account: string + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number + marker?: any + offers?: AccountOffer[] } export interface AccountOffer { - seq: number, - flags: number, - taker_gets: RippledAmount, - taker_pays: RippledAmount, - quality: string, + seq: number + flags: number + taker_gets: RippledAmount + taker_pays: RippledAmount + quality: string expiration?: number } diff --git a/src/common/types/commands/book_offers.ts b/src/common/types/commands/book_offers.ts index 66dc9609..7e34fae7 100644 --- a/src/common/types/commands/book_offers.ts +++ b/src/common/types/commands/book_offers.ts @@ -1,30 +1,26 @@ -import { - TakerRequestAmount, - RippledAmount, - OfferLedgerEntry -} from '../objects' +import {TakerRequestAmount, RippledAmount, OfferLedgerEntry} from '../objects' export interface BookOffersRequest { - taker?: string, - taker_gets: TakerRequestAmount, - taker_pays: TakerRequestAmount, - ledger_hash?: string, - ledger_index?: number | ('validated' | 'closed' | 'current'), - limit?: number, + taker?: string + taker_gets: TakerRequestAmount + taker_pays: TakerRequestAmount + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + limit?: number marker?: any } export interface BookOffersResponse { - offers: BookOffer[], - ledger_hash?: string, - ledger_current_index?: number, - ledger_index?: number, + offers: BookOffer[] + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number marker?: any } export interface BookOffer extends OfferLedgerEntry { quality?: string - owner_funds?: string, - taker_gets_funded?: RippledAmount, + owner_funds?: string + taker_gets_funded?: RippledAmount taker_pays_funded?: RippledAmount } diff --git a/src/common/types/commands/gateway_balances.ts b/src/common/types/commands/gateway_balances.ts index 09171d6f..b200b2fb 100644 --- a/src/common/types/commands/gateway_balances.ts +++ b/src/common/types/commands/gateway_balances.ts @@ -1,19 +1,19 @@ import {Amount} from '../objects' export interface GatewayBalancesRequest { - account: string, - strict?: boolean, - hotwallet: string|Array, - ledger_hash?: string, + account: string + strict?: boolean + hotwallet: string | Array + ledger_hash?: string ledger_index?: number | ('validated' | 'closed' | 'current') } export interface GatewayBalancesResponse { - account: string, - obligations?: {[currency: string]: string}, - balances?: {[address: string]: Amount[]}, - assets?: {[address: string]: Amount[]}, - ledger_hash?: string, - ledger_current_index?: number, + account: string + obligations?: {[currency: string]: string} + balances?: {[address: string]: Amount[]} + assets?: {[address: string]: Amount[]} + ledger_hash?: string + ledger_current_index?: number ledger_index?: number } diff --git a/src/common/types/commands/ledger_data.ts b/src/common/types/commands/ledger_data.ts index 668607a4..cca3f782 100644 --- a/src/common/types/commands/ledger_data.ts +++ b/src/common/types/commands/ledger_data.ts @@ -1,4 +1,4 @@ -import { LedgerData } from '../objects' +import {LedgerData} from '../objects' export interface LedgerDataRequest { id?: any @@ -9,4 +9,4 @@ export interface LedgerDataRequest { marker?: string } -export type LedgerDataResponse = LedgerData; \ No newline at end of file +export type LedgerDataResponse = LedgerData diff --git a/src/common/types/commands/ledger_entry.ts b/src/common/types/commands/ledger_entry.ts index 088fb0aa..a3f55339 100644 --- a/src/common/types/commands/ledger_entry.ts +++ b/src/common/types/commands/ledger_entry.ts @@ -3,29 +3,34 @@ import {LedgerEntry} from '../objects' export interface LedgerEntryRequest { ledger_hash?: string ledger_index?: number | ('validated' | 'closed' | 'current') - index?: string, - account_root?: string, - directory?: string | { - sub_index?: number, - dir_root: string - } | { - sub_index?: number, - owner: string - }, - offer?: string | { - account: string, - seq: number - }, + index?: string + account_root?: string + directory?: + | string + | { + sub_index?: number + dir_root: string + } + | { + sub_index?: number + owner: string + } + offer?: + | string + | { + account: string + seq: number + } ripple_state?: { - accounts: [string, string], + accounts: [string, string] currency: string - }, + } binary?: boolean } export interface LedgerEntryResponse { - index: string, - ledger_index: number, - node_binary?: string, - node?: LedgerEntry, + index: string + ledger_index: number + node_binary?: string + node?: LedgerEntry } diff --git a/src/common/types/commands/server_info.ts b/src/common/types/commands/server_info.ts index 7de6a588..ebf01e4f 100644 --- a/src/common/types/commands/server_info.ts +++ b/src/common/types/commands/server_info.ts @@ -4,48 +4,48 @@ export interface ServerInfoRequest { export interface ServerInfoResponse { info: { - amendment_blocked?: boolean, - build_version: string, - closed_ledger?: LedgerInfo, - complete_ledgers: string, - hostid: string, - io_latency_ms: number, + amendment_blocked?: boolean + build_version: string + closed_ledger?: LedgerInfo + complete_ledgers: string + hostid: string + io_latency_ms: number last_close: { - converge_time_s: number, + converge_time_s: number proposers: number - }, + } load?: { job_types: { - job_type: string, - per_second: number, + job_type: string + per_second: number in_progress: number - }[], + }[] threads: number - }, - load_factor: number, - load_factor_local?: number, - load_factor_net?: number, - load_factor_cluster?: number, - load_factor_fee_escalation?: number, - load_factor_fee_queue?: number, - load_factor_server?: number, - peers: number, - pubkey_node: string, - pubkey_validator: string, - server_state: string, - state_accounting: any, - uptime: number, - validated_ledger?: LedgerInfo, - validation_quorum: number, + } + load_factor: number + load_factor_local?: number + load_factor_net?: number + load_factor_cluster?: number + load_factor_fee_escalation?: number + load_factor_fee_queue?: number + load_factor_server?: number + peers: number + pubkey_node: string + pubkey_validator: string + server_state: string + state_accounting: any + uptime: number + validated_ledger?: LedgerInfo + validation_quorum: number validator_list_expires: string - }, + } } export interface LedgerInfo { - age: number, - base_fee_xrp: number, - hash: string, - reserve_base_xrp: number, - reserve_inc_xrp: number, - seq: number, + age: number + base_fee_xrp: number + hash: string + reserve_base_xrp: number + reserve_inc_xrp: number + seq: number } diff --git a/src/common/types/objects/adjustments.ts b/src/common/types/objects/adjustments.ts index 42a17d7d..ea9e2fb2 100644 --- a/src/common/types/objects/adjustments.ts +++ b/src/common/types/objects/adjustments.ts @@ -1,19 +1,19 @@ import {Amount} from './amounts' export type Adjustment = { - address: string, - amount: Amount, + address: string + amount: Amount tag?: number } export type MaxAdjustment = { - address: string, - maxAmount: Amount, + address: string + maxAmount: Amount tag?: number } export type MinAdjustment = { - address: string, - minAmount: Amount, + address: string + minAmount: Amount tag?: number } diff --git a/src/common/types/objects/amounts.ts b/src/common/types/objects/amounts.ts index 0ba909b4..c7c45481 100644 --- a/src/common/types/objects/amounts.ts +++ b/src/common/types/objects/amounts.ts @@ -2,7 +2,6 @@ export interface Amount extends Issue { value: string } - export type RippledAmount = string | Amount /** diff --git a/src/common/types/objects/ledger.ts b/src/common/types/objects/ledger.ts index 13ff5153..4c7a939c 100644 --- a/src/common/types/objects/ledger.ts +++ b/src/common/types/objects/ledger.ts @@ -1,23 +1,23 @@ export interface Ledger { - account_hash: string, - close_time: number, - close_time_human: string, - close_time_resolution: number, - closed: boolean, - ledger_hash: string, - ledger_index: string, - parent_hash: string, - total_coins: string, - transaction_hash: string, - transactions: string[] | object[], + account_hash: string + close_time: number + close_time_human: string + close_time_resolution: number + closed: boolean + ledger_hash: string + ledger_index: string + parent_hash: string + total_coins: string + transaction_hash: string + transactions: string[] | object[] // @deprecated - seqNum?: string, + seqNum?: string // @deprecated - totalCoins?: string, + totalCoins?: string // @deprecated - hash?: string, - close_flags?: number, - parent_close_time?: number, - accountState?: any[], + hash?: string + close_flags?: number + parent_close_time?: number + accountState?: any[] validated?: boolean } diff --git a/src/common/types/objects/ledger_data.ts b/src/common/types/objects/ledger_data.ts index 03fc8b9e..7ad27e72 100644 --- a/src/common/types/objects/ledger_data.ts +++ b/src/common/types/objects/ledger_data.ts @@ -2,5 +2,5 @@ export interface LedgerData { ledger_index: string ledger_hash: string marker: string - state: ({ data?: string; LedgerEntryType?: string; index: string } & any)[] -} \ No newline at end of file + state: ({data?: string; LedgerEntryType?: string; index: string} & any)[] +} diff --git a/src/common/types/objects/ledger_entries.ts b/src/common/types/objects/ledger_entries.ts index 0d0aed8b..beefd558 100644 --- a/src/common/types/objects/ledger_entries.ts +++ b/src/common/types/objects/ledger_entries.ts @@ -2,188 +2,189 @@ import {SignerEntry} from './index' import {Amount, RippledAmount} from './amounts' export interface AccountRootLedgerEntry { - LedgerEntryType: 'AccountRoot', - Account: string, - Balance: string, - Flags: number, - OwnerCount: number, - PreviousTxnID: string, - PreviousTxnLgrSeq: number, - Sequence: number, - AccountTxnID?: string, - Domain?: string, - EmailHash?: string, + LedgerEntryType: 'AccountRoot' + Account: string + Balance: string + Flags: number + OwnerCount: number + PreviousTxnID: string + PreviousTxnLgrSeq: number + Sequence: number + AccountTxnID?: string + Domain?: string + EmailHash?: string MessageKey?: string - RegularKey?: string, - TickSize?: number, - TransferRate?: number, - WalletLocator?: string, + RegularKey?: string + TickSize?: number + TransferRate?: number + WalletLocator?: string WalletSize?: number // DEPRECATED } export interface AmendmentsLedgerEntry { - LedgerEntryType: 'Amendments', - Amendments?: string[], - Majorities?: any[], + LedgerEntryType: 'Amendments' + Amendments?: string[] + Majorities?: any[] Flags: 0 } export interface CheckLedgerEntry { - LedgerEntryType: 'Check', - Account: string, - Destination, string, - Flags: 0, - OwnerNode: string, - PreviousTxnID: string, - PreviousTxnLgrSeq: number, - SendMax: string | object, - Sequence: number, - DestinationNode: string, - DestinationTag: number, - Expiration: number, - InvoiceID: string, + LedgerEntryType: 'Check' + Account: string + Destination + string + Flags: 0 + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + SendMax: string | object + Sequence: number + DestinationNode: string + DestinationTag: number + Expiration: number + InvoiceID: string SourceTag: number } export interface DepositPreauthLedgerEntry { - LedgerEntryType: 'DepositPreauth', - Account: string, - Authorize: string, - OwnerNode: string, - PreviousTxnID: string, + LedgerEntryType: 'DepositPreauth' + Account: string + Authorize: string + OwnerNode: string + PreviousTxnID: string PreviousTxnLgrSeq: number } export interface DirectoryNodeLedgerEntry { - LedgerEntryType: 'DirectoryNode', - Flags: number, - RootIndex: string, - Indexes: string[], - IndexNext?: number, + LedgerEntryType: 'DirectoryNode' + Flags: number + RootIndex: string + Indexes: string[] + IndexNext?: number IndexPrevious?: number } export interface OfferDirectoryNodeLedgerEntry - extends DirectoryNodeLedgerEntry { - TakerPaysCurrency: string, - TakerPaysIssuer: string, - TakerGetsCurrency: string, - TakerGetsIssuer: string, + extends DirectoryNodeLedgerEntry { + TakerPaysCurrency: string + TakerPaysIssuer: string + TakerGetsCurrency: string + TakerGetsIssuer: string ExchangeRate?: number // DEPRECATED } export interface OwnerDirectoryNodeLedgerEntry extends DirectoryNodeLedgerEntry { - Owner: string, + Owner: string } export interface EscrowLedgerEntry { - LedgerEntryType: 'Escrow', - Account: string, - Destination: string, - Amount: string, - Condition?: string, - CancelAfter?: number, - FinishAfter?: number, - Flags: number, - SourceTag?: number, - DestinationTag?: number, - OwnerNode: string, - DestinationNode?: string, - PreviousTxnID: string, + LedgerEntryType: 'Escrow' + Account: string + Destination: string + Amount: string + Condition?: string + CancelAfter?: number + FinishAfter?: number + Flags: number + SourceTag?: number + DestinationTag?: number + OwnerNode: string + DestinationNode?: string + PreviousTxnID: string PreviousTxnLgrSeq: number } export interface FeeSettingsLedgerEntry { - LedgerEntryType: 'FeeSettings', - BaseFee: string, - ReferenceFeeUnits: number, - ReserveBase: number, - ReserveIncrement: number, + LedgerEntryType: 'FeeSettings' + BaseFee: string + ReferenceFeeUnits: number + ReserveBase: number + ReserveIncrement: number Flags: number } export interface LedgerHashesLedgerEntry { - LedgerEntryType: 'LedgerHashes', - Hashes: string[], - Flags: number, - FirstLedgerSequence?: number, // DEPRECATED + LedgerEntryType: 'LedgerHashes' + Hashes: string[] + Flags: number + FirstLedgerSequence?: number // DEPRECATED LastLedgerSequence?: number } export interface OfferLedgerEntry { - LedgerEntryType: 'Offer', - Flags: number, - Account: string, - Sequence: number, - TakerPays: RippledAmount, - TakerGets: RippledAmount, - BookDirectory: string, - BookNode: string, - OwnerNode: string, - PreviousTxnID: string, - PreviousTxnLgrSeq: number, + LedgerEntryType: 'Offer' + Flags: number + Account: string + Sequence: number + TakerPays: RippledAmount + TakerGets: RippledAmount + BookDirectory: string + BookNode: string + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number Expiration?: number } export interface PayChannelLedgerEntry { - LedgerEntryType: 'PayChannel', - Sequence: number, - Account: string, - Amount: string, - Balance: string, - PublicKey: string, - Destination: string, - SettleDelay: number, - Expiration?: number, - CancelAfter?: number, - SourceTag?: number, - DestinationTag?: number, - OwnerNode: string, - PreviousTxnID: string, - PreviousTxnLgrSeq: number, + LedgerEntryType: 'PayChannel' + Sequence: number + Account: string + Amount: string + Balance: string + PublicKey: string + Destination: string + SettleDelay: number + Expiration?: number + CancelAfter?: number + SourceTag?: number + DestinationTag?: number + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number index: string } export interface RippleStateLedgerEntry { - LedgerEntryType: 'RippleState', - Flags: number, - Balance: Amount, - LowLimit: Amount, - HighLimit: Amount, - PreviousTxnID: string, - PreviousTxnLgrSeq: number, - LowNode?: string, - HighNode?: string, - LowQualityIn?: number, - LowQualityOut?: number, - HighQualityIn?: number, + LedgerEntryType: 'RippleState' + Flags: number + Balance: Amount + LowLimit: Amount + HighLimit: Amount + PreviousTxnID: string + PreviousTxnLgrSeq: number + LowNode?: string + HighNode?: string + LowQualityIn?: number + LowQualityOut?: number + HighQualityIn?: number HighQualityOut?: number } export interface SignerListLedgerEntry { - LedgerEntryType: 'SignerList', - OwnerNode: string, - SignerQuorum: number, - SignerEntries: SignerEntry[], - SignerListID: number, - PreviousTxnID: string, + LedgerEntryType: 'SignerList' + OwnerNode: string + SignerQuorum: number + SignerEntries: SignerEntry[] + SignerListID: number + PreviousTxnID: string PreviousTxnLgrSeq: number } // see https://ripple.com/build/ledger-format/#ledger-object-types export type LedgerEntry = - AccountRootLedgerEntry | - AmendmentsLedgerEntry | - CheckLedgerEntry | - DepositPreauthLedgerEntry | - DirectoryNodeLedgerEntry | - OfferDirectoryNodeLedgerEntry | - OwnerDirectoryNodeLedgerEntry | - EscrowLedgerEntry | - FeeSettingsLedgerEntry | - LedgerHashesLedgerEntry | - OfferLedgerEntry | - PayChannelLedgerEntry | - RippleStateLedgerEntry | - SignerListLedgerEntry + | AccountRootLedgerEntry + | AmendmentsLedgerEntry + | CheckLedgerEntry + | DepositPreauthLedgerEntry + | DirectoryNodeLedgerEntry + | OfferDirectoryNodeLedgerEntry + | OwnerDirectoryNodeLedgerEntry + | EscrowLedgerEntry + | FeeSettingsLedgerEntry + | LedgerHashesLedgerEntry + | OfferLedgerEntry + | PayChannelLedgerEntry + | RippleStateLedgerEntry + | SignerListLedgerEntry diff --git a/src/common/types/objects/memos.ts b/src/common/types/objects/memos.ts index 4464fa89..e5692e9b 100644 --- a/src/common/types/objects/memos.ts +++ b/src/common/types/objects/memos.ts @@ -1,6 +1,5 @@ - export type Memo = { - type?: string, - format?: string, + type?: string + format?: string data?: string } diff --git a/src/common/types/objects/orders.ts b/src/common/types/objects/orders.ts index 11985d79..05552293 100644 --- a/src/common/types/objects/orders.ts +++ b/src/common/types/objects/orders.ts @@ -2,14 +2,14 @@ import {Amount} from './amounts' import {Memo} from './memos' export type FormattedOrderSpecification = { - direction: string, - quantity: Amount, - totalPrice: Amount, - immediateOrCancel?: boolean, - fillOrKill?: boolean, - expirationTime?: string, - orderToReplace?: number, - memos?: Memo[], + direction: string + quantity: Amount + totalPrice: Amount + immediateOrCancel?: boolean + fillOrKill?: boolean + expirationTime?: string + orderToReplace?: number + memos?: Memo[] // If enabled, the offer will not consume offers that exactly match it, and // instead becomes an Offer node in the ledger. It will still consume offers // that cross it. diff --git a/src/common/types/objects/queue_data.ts b/src/common/types/objects/queue_data.ts index 6aeccb7c..918f05a3 100644 --- a/src/common/types/objects/queue_data.ts +++ b/src/common/types/objects/queue_data.ts @@ -1,16 +1,16 @@ export interface QueueTransaction { - auth_change: boolean, - fee: string, - fee_level: string, - max_spend_drops: string, + auth_change: boolean + fee: string + fee_level: string + max_spend_drops: string seq: number } export interface QueueData { - txn_count: number, - auth_change_queued?: boolean, - lowest_sequence?: number, - highest_sequence?: number, - max_spend_drops_total?: string, + txn_count: number + auth_change_queued?: boolean + lowest_sequence?: number + highest_sequence?: number + max_spend_drops_total?: string transactions?: QueueTransaction[] } diff --git a/src/common/types/objects/settings.ts b/src/common/types/objects/settings.ts index 85dc1a89..69285898 100644 --- a/src/common/types/objects/settings.ts +++ b/src/common/types/objects/settings.ts @@ -1,33 +1,33 @@ import {Memo} from './memos' export type WeightedSigner = { - address: string, + address: string weight: number } export type Signers = { - threshold?: number, + threshold?: number weights: WeightedSigner[] } export type FormattedSettings = { - defaultRipple?: boolean, - depositAuth?: boolean, - disableMasterKey?: boolean, - disallowIncomingXRP?: boolean, - domain?: string, - emailHash?: string|null, - walletLocator?: string|null, - enableTransactionIDTracking?: boolean, - globalFreeze?: boolean, - memos?: Memo[], - messageKey?: string, - noFreeze?: boolean, - passwordSpent?: boolean, - regularKey?: string, - requireAuthorization?: boolean, - requireDestinationTag?: boolean, - signers?: Signers, - transferRate?: number|null, + defaultRipple?: boolean + depositAuth?: boolean + disableMasterKey?: boolean + disallowIncomingXRP?: boolean + domain?: string + emailHash?: string | null + walletLocator?: string | null + enableTransactionIDTracking?: boolean + globalFreeze?: boolean + memos?: Memo[] + messageKey?: string + noFreeze?: boolean + passwordSpent?: boolean + regularKey?: string + requireAuthorization?: boolean + requireDestinationTag?: boolean + signers?: Signers + transferRate?: number | null tickSize?: number } diff --git a/src/common/types/objects/signers.ts b/src/common/types/objects/signers.ts index 9df63fd8..df02c135 100644 --- a/src/common/types/objects/signers.ts +++ b/src/common/types/objects/signers.ts @@ -1,4 +1,4 @@ export interface SignerEntry { - Account: string, + Account: string SignerWeight: number } diff --git a/src/common/types/objects/transactions.ts b/src/common/types/objects/transactions.ts index 40c54117..1e8d1cdc 100644 --- a/src/common/types/objects/transactions.ts +++ b/src/common/types/objects/transactions.ts @@ -2,21 +2,21 @@ import {RippledAmount} from './amounts' import {Memo} from './memos' export interface OfferCreateTransaction { - TransactionType: 'OfferCreate', - Account: string, - AccountTxnID?: string, - Fee: string, - Field: any, - Flags: number, - LastLedgerSequence?: number, - Sequence: number, - Signers: any[], - SigningPubKey: string, - SourceTag?: number, - TakerGets: RippledAmount, - TakerPays: RippledAmount, - TxnSignature: string, - Expiration?: number, - Memos?: Memo[], - OfferSequence?: number, + TransactionType: 'OfferCreate' + Account: string + AccountTxnID?: string + Fee: string + Field: any + Flags: number + LastLedgerSequence?: number + Sequence: number + Signers: any[] + SigningPubKey: string + SourceTag?: number + TakerGets: RippledAmount + TakerPays: RippledAmount + TxnSignature: string + Expiration?: number + Memos?: Memo[] + OfferSequence?: number } diff --git a/src/common/types/objects/trustlines.ts b/src/common/types/objects/trustlines.ts index f7f62228..75be5ff4 100644 --- a/src/common/types/objects/trustlines.ts +++ b/src/common/types/objects/trustlines.ts @@ -1,41 +1,41 @@ import {Memo} from './memos' export interface Trustline { - account: string, - balance: string, - currency: string, - limit: string, - limit_peer: string, - quality_in: number, - quality_out: number, - no_ripple?: boolean, - no_ripple_peer?: boolean, - freeze?: boolean, - freeze_peer?: boolean, - authorized?: boolean, - peer_authorized?: boolean, + account: string + balance: string + currency: string + limit: string + limit_peer: string + quality_in: number + quality_out: number + no_ripple?: boolean + no_ripple_peer?: boolean + freeze?: boolean + freeze_peer?: boolean + authorized?: boolean + peer_authorized?: boolean } export type FormattedTrustlineSpecification = { - currency: string, - counterparty: string, - limit: string, - qualityIn?: number, - qualityOut?: number, - ripplingDisabled?: boolean, - authorized?: boolean, - frozen?: boolean, + currency: string + counterparty: string + limit: string + qualityIn?: number + qualityOut?: number + ripplingDisabled?: boolean + authorized?: boolean + frozen?: boolean memos?: Memo[] } export type FormattedTrustline = { - specification: FormattedTrustlineSpecification, + specification: FormattedTrustlineSpecification counterparty: { - limit: string, - ripplingDisabled?: boolean, - frozen?: boolean, + limit: string + ripplingDisabled?: boolean + frozen?: boolean authorized?: boolean - }, + } state: { balance: string } diff --git a/src/common/utils.ts b/src/common/utils.ts index 37168de9..c565416e 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -16,74 +16,93 @@ function isValidSecret(secret: string): boolean { function dropsToXrp(drops: BigNumber.Value): string { if (typeof drops === 'string') { if (!drops.match(/^-?[0-9]*\.?[0-9]*$/)) { - throw new ValidationError(`dropsToXrp: invalid value '${drops}',` + - ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`) + throw new ValidationError( + `dropsToXrp: invalid value '${drops}',` + + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).` + ) } else if (drops === '.') { - throw new ValidationError(`dropsToXrp: invalid value '${drops}',` + - ` should be a BigNumber or string-encoded number.`) + throw new ValidationError( + `dropsToXrp: invalid value '${drops}',` + + ` should be a BigNumber or string-encoded number.` + ) } } // Converting to BigNumber and then back to string should remove any // decimal point followed by zeros, e.g. '1.00'. // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. - drops = (new BigNumber(drops)).toString(10) + drops = new BigNumber(drops).toString(10) // drops are only whole units if (drops.includes('.')) { - throw new ValidationError(`dropsToXrp: value '${drops}' has` + - ` too many decimal places.`) + throw new ValidationError( + `dropsToXrp: value '${drops}' has` + ` too many decimal places.` + ) } // This should never happen; the value has already been // validated above. This just ensures BigNumber did not do // something unexpected. if (!drops.match(/^-?[0-9]+$/)) { - throw new ValidationError(`dropsToXrp: failed sanity check -` + - ` value '${drops}',` + - ` does not match (^-?[0-9]+$).`) + throw new ValidationError( + `dropsToXrp: failed sanity check -` + + ` value '${drops}',` + + ` does not match (^-?[0-9]+$).` + ) } - return (new BigNumber(drops)).dividedBy(1000000.0).toString(10) + return new BigNumber(drops).dividedBy(1000000.0).toString(10) } function xrpToDrops(xrp: BigNumber.Value): string { if (typeof xrp === 'string') { if (!xrp.match(/^-?[0-9]*\.?[0-9]*$/)) { - throw new ValidationError(`xrpToDrops: invalid value '${xrp}',` + - ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`) + throw new ValidationError( + `xrpToDrops: invalid value '${xrp}',` + + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).` + ) } else if (xrp === '.') { - throw new ValidationError(`xrpToDrops: invalid value '${xrp}',` + - ` should be a BigNumber or string-encoded number.`) + throw new ValidationError( + `xrpToDrops: invalid value '${xrp}',` + + ` should be a BigNumber or string-encoded number.` + ) } } // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. - xrp = (new BigNumber(xrp)).toString(10) + xrp = new BigNumber(xrp).toString(10) // This should never happen; the value has already been // validated above. This just ensures BigNumber did not do // something unexpected. if (!xrp.match(/^-?[0-9.]+$/)) { - throw new ValidationError(`xrpToDrops: failed sanity check -` + - ` value '${xrp}',` + - ` does not match (^-?[0-9.]+$).`) + throw new ValidationError( + `xrpToDrops: failed sanity check -` + + ` value '${xrp}',` + + ` does not match (^-?[0-9.]+$).` + ) } const components = xrp.split('.') if (components.length > 2) { - throw new ValidationError(`xrpToDrops: failed sanity check -` + - ` value '${xrp}' has` + - ` too many decimal points.`) + throw new ValidationError( + `xrpToDrops: failed sanity check -` + + ` value '${xrp}' has` + + ` too many decimal points.` + ) } const fraction = components[1] || '0' if (fraction.length > 6) { - throw new ValidationError(`xrpToDrops: value '${xrp}' has` + - ` too many decimal places.`) + throw new ValidationError( + `xrpToDrops: value '${xrp}' has` + ` too many decimal places.` + ) } - return (new BigNumber(xrp)).times(1000000.0).integerValue(BigNumber.ROUND_FLOOR).toString(10) + return new BigNumber(xrp) + .times(1000000.0) + .integerValue(BigNumber.ROUND_FLOOR) + .toString(10) } function toRippledAmount(amount: Amount): RippledAmount { @@ -95,8 +114,11 @@ function toRippledAmount(amount: Amount): RippledAmount { } return { currency: amount.currency, - issuer: amount.counterparty ? amount.counterparty : - (amount.issuer ? amount.issuer : undefined), + issuer: amount.counterparty + ? amount.counterparty + : amount.issuer + ? amount.issuer + : undefined, value: amount.value } } @@ -105,16 +127,20 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any { if (typeof obj === 'object') { const accumulator = Array.isArray(obj) ? [] : {} let newKey - return _.reduce(obj, (result, value, key) => { - newKey = key - // 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()) - } - result[newKey] = convertKeysFromSnakeCaseToCamelCase(value) - return result - }, accumulator) + return _.reduce( + obj, + (result, value, key) => { + newKey = key + // 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()) + } + result[newKey] = convertKeysFromSnakeCaseToCamelCase(value) + return result + }, + accumulator + ) } return obj } @@ -128,7 +154,7 @@ function removeUndefined(obj: T): T { * @return {Number} ms since unix epoch */ function rippleToUnixTimestamp(rpepoch: number): number { - return (rpepoch + 0x386D4380) * 1000 + return (rpepoch + 0x386d4380) * 1000 } /** @@ -136,7 +162,7 @@ function rippleToUnixTimestamp(rpepoch: number): number { * @return {Number} seconds since ripple epoch (1/1/2000 GMT) */ function unixToRippleTimestamp(timestamp: number): number { - return Math.round(timestamp / 1000) - 0x386D4380 + return Math.round(timestamp / 1000) - 0x386d4380 } function rippleTimeToISO8601(rippleTime: number): string { @@ -161,4 +187,3 @@ export { iso8601ToRippleTime, isValidSecret } - diff --git a/src/common/validate.ts b/src/common/validate.ts index 97f2f0ac..de3b0b8f 100644 --- a/src/common/validate.ts +++ b/src/common/validate.ts @@ -7,8 +7,11 @@ function error(text) { } function validateLedgerRange(options) { - if (!_.isUndefined(options) && !_.isUndefined(options.minLedgerVersion) - && !_.isUndefined(options.maxLedgerVersion)) { + if ( + !_.isUndefined(options) && + !_.isUndefined(options.minLedgerVersion) && + !_.isUndefined(options.maxLedgerVersion) + ) { if (Number(options.minLedgerVersion) > Number(options.maxLedgerVersion)) { throw error('minLedgerVersion must not be greater than maxLedgerVersion') } @@ -20,110 +23,143 @@ function validateOptions(schema, instance) { validateLedgerRange(instance.options) } -export const getPaths = - _.partial(schemaValidate, 'getPathsParameters') +export const getPaths = _.partial(schemaValidate, 'getPathsParameters') -export const getTransactions = -_.partial(validateOptions, 'getTransactionsParameters') +export const getTransactions = _.partial( + validateOptions, + 'getTransactionsParameters' +) -export const getSettings = -_.partial(validateOptions, 'getSettingsParameters') +export const getSettings = _.partial(validateOptions, 'getSettingsParameters') -export const getAccountInfo = -_.partial(validateOptions, 'getAccountInfoParameters') +export const getAccountInfo = _.partial( + validateOptions, + 'getAccountInfoParameters' +) -export const getTrustlines = -_.partial(validateOptions, 'getTrustlinesParameters') +export const getTrustlines = _.partial( + validateOptions, + 'getTrustlinesParameters' +) -export const getBalances = -_.partial(validateOptions, 'getBalancesParameters') +export const getBalances = _.partial(validateOptions, 'getBalancesParameters') -export const getBalanceSheet = -_.partial(validateOptions, 'getBalanceSheetParameters') +export const getBalanceSheet = _.partial( + validateOptions, + 'getBalanceSheetParameters' +) -export const getOrders = -_.partial(validateOptions, 'getOrdersParameters') +export const getOrders = _.partial(validateOptions, 'getOrdersParameters') -export const getOrderbook = -_.partial(validateOptions, 'getOrderbookParameters') +export const getOrderbook = _.partial(validateOptions, 'getOrderbookParameters') -export const getTransaction = -_.partial(validateOptions, 'getTransactionParameters') +export const getTransaction = _.partial( + validateOptions, + 'getTransactionParameters' +) -export const getPaymentChannel = -_.partial(validateOptions, 'getPaymentChannelParameters') +export const getPaymentChannel = _.partial( + validateOptions, + 'getPaymentChannelParameters' +) -export const getLedger = -_.partial(validateOptions, 'getLedgerParameters') +export const getLedger = _.partial(validateOptions, 'getLedgerParameters') -export const preparePayment = -_.partial(schemaValidate, 'preparePaymentParameters') +export const preparePayment = _.partial( + schemaValidate, + 'preparePaymentParameters' +) -export const prepareOrder = -_.partial(schemaValidate, 'prepareOrderParameters') +export const prepareOrder = _.partial(schemaValidate, 'prepareOrderParameters') -export const prepareOrderCancellation = -_.partial(schemaValidate, 'prepareOrderCancellationParameters') +export const prepareOrderCancellation = _.partial( + schemaValidate, + 'prepareOrderCancellationParameters' +) -export const prepareTrustline = -_.partial(schemaValidate, 'prepareTrustlineParameters') +export const prepareTrustline = _.partial( + schemaValidate, + 'prepareTrustlineParameters' +) -export const prepareSettings = -_.partial(schemaValidate, 'prepareSettingsParameters') +export const prepareSettings = _.partial( + schemaValidate, + 'prepareSettingsParameters' +) -export const prepareEscrowCreation = -_.partial(schemaValidate, 'prepareEscrowCreationParameters') +export const prepareEscrowCreation = _.partial( + schemaValidate, + 'prepareEscrowCreationParameters' +) -export const prepareEscrowCancellation = -_.partial(schemaValidate, 'prepareEscrowCancellationParameters') +export const prepareEscrowCancellation = _.partial( + schemaValidate, + 'prepareEscrowCancellationParameters' +) -export const prepareEscrowExecution = -_.partial(schemaValidate, 'prepareEscrowExecutionParameters') +export const prepareEscrowExecution = _.partial( + schemaValidate, + 'prepareEscrowExecutionParameters' +) -export const preparePaymentChannelCreate = -_.partial(schemaValidate, 'preparePaymentChannelCreateParameters') +export const preparePaymentChannelCreate = _.partial( + schemaValidate, + 'preparePaymentChannelCreateParameters' +) -export const preparePaymentChannelFund = -_.partial(schemaValidate, 'preparePaymentChannelFundParameters') +export const preparePaymentChannelFund = _.partial( + schemaValidate, + 'preparePaymentChannelFundParameters' +) -export const preparePaymentChannelClaim = -_.partial(schemaValidate, 'preparePaymentChannelClaimParameters') +export const preparePaymentChannelClaim = _.partial( + schemaValidate, + 'preparePaymentChannelClaimParameters' +) -export const prepareCheckCreate = -_.partial(schemaValidate, 'prepareCheckCreateParameters') +export const prepareCheckCreate = _.partial( + schemaValidate, + 'prepareCheckCreateParameters' +) -export const prepareCheckCash = -_.partial(schemaValidate, 'prepareCheckCashParameters') +export const prepareCheckCash = _.partial( + schemaValidate, + 'prepareCheckCashParameters' +) -export const prepareCheckCancel = -_.partial(schemaValidate, 'prepareCheckCancelParameters') +export const prepareCheckCancel = _.partial( + schemaValidate, + 'prepareCheckCancelParameters' +) -export const sign = -_.partial(schemaValidate, 'signParameters') +export const sign = _.partial(schemaValidate, 'signParameters') -export const combine = -_.partial(schemaValidate, 'combineParameters') +export const combine = _.partial(schemaValidate, 'combineParameters') -export const submit = -_.partial(schemaValidate, 'submitParameters') +export const submit = _.partial(schemaValidate, 'submitParameters') -export const computeLedgerHash = -_.partial(schemaValidate, 'computeLedgerHashParameters') +export const computeLedgerHash = _.partial( + schemaValidate, + 'computeLedgerHashParameters' +) -export const generateAddress = -_.partial(schemaValidate, 'generateAddressParameters') +export const generateAddress = _.partial( + schemaValidate, + 'generateAddressParameters' +) -export const signPaymentChannelClaim = -_.partial(schemaValidate, 'signPaymentChannelClaimParameters') +export const signPaymentChannelClaim = _.partial( + schemaValidate, + 'signPaymentChannelClaimParameters' +) -export const verifyPaymentChannelClaim = -_.partial(schemaValidate, 'verifyPaymentChannelClaimParameters') +export const verifyPaymentChannelClaim = _.partial( + schemaValidate, + 'verifyPaymentChannelClaimParameters' +) -export const apiOptions = -_.partial(schemaValidate, 'api-options') +export const apiOptions = _.partial(schemaValidate, 'api-options') -export const instructions = -_.partial(schemaValidate, 'instructions') +export const instructions = _.partial(schemaValidate, 'instructions') -export const tx_json = -_.partial(schemaValidate, 'tx-json') +export const tx_json = _.partial(schemaValidate, 'tx-json') diff --git a/src/common/wswrapper.ts b/src/common/wswrapper.ts index 1fb6d560..985a079e 100644 --- a/src/common/wswrapper.ts +++ b/src/common/wswrapper.ts @@ -17,7 +17,6 @@ declare class WebSocket { * same, as `ws` package provides. */ class WSWrapper extends EventEmitter { - private _ws: WebSocket static CONNECTING = 0 static OPEN = 1 @@ -60,8 +59,6 @@ class WSWrapper extends EventEmitter { get readyState() { return this._ws.readyState } - } export = WSWrapper - diff --git a/src/index.ts b/src/index.ts index f9409a53..93856cdb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,8 +1,6 @@ export {RippleAPI} from './api' -export { - FormattedTransactionType -} from './transaction/types' +export {FormattedTransactionType} from './transaction/types' // Broadcast api is experimental export {RippleAPIBroadcast} from './broadcast' diff --git a/src/ledger/accountinfo.ts b/src/ledger/accountinfo.ts index 81cea076..ca0ca686 100644 --- a/src/ledger/accountinfo.ts +++ b/src/ledger/accountinfo.ts @@ -1,4 +1,9 @@ -import {validate, removeUndefined, dropsToXrp, ensureClassicAddress} from '../common' +import { + validate, + removeUndefined, + dropsToXrp, + ensureClassicAddress +} from '../common' import {RippleAPI} from '..' import {AccountInfoResponse} from '../common/types/commands/account_info' @@ -7,11 +12,11 @@ export type GetAccountInfoOptions = { } export type FormattedGetAccountInfoResponse = { - sequence: number, - xrpBalance: string, - ownerCount: number, - previousInitiatedTransactionID: string, - previousAffectingTransactionID: string, + sequence: number + xrpBalance: string + ownerCount: number + previousInitiatedTransactionID: string + previousAffectingTransactionID: string previousAffectingTransactionLedgerVersion: number } @@ -30,7 +35,9 @@ function formatAccountInfo( } export default async function getAccountInfo( - this: RippleAPI, address: string, options: GetAccountInfoOptions = {} + this: RippleAPI, + address: string, + options: GetAccountInfoOptions = {} ): Promise { // 1. Validate validate.getAccountInfo({address, options}) diff --git a/src/ledger/accountobjects.ts b/src/ledger/accountobjects.ts index 9531beac..80fcc5fa 100644 --- a/src/ledger/accountobjects.ts +++ b/src/ledger/accountobjects.ts @@ -14,14 +14,17 @@ export default async function getAccountObjects( // through to rippled. rippled validates requests. // Make Request - const response = await this.request('account_objects', removeUndefined({ - account: address, - type: options.type, - ledger_hash: options.ledgerHash, - ledger_index: options.ledgerIndex, - limit: options.limit, - marker: options.marker - })) + const response = await this.request( + 'account_objects', + removeUndefined({ + account: address, + type: options.type, + ledger_hash: options.ledgerHash, + ledger_index: options.ledgerIndex, + limit: options.limit, + marker: options.marker + }) + ) // Return Response return response } diff --git a/src/ledger/balance-sheet.ts b/src/ledger/balance-sheet.ts index c714b03b..0462293a 100644 --- a/src/ledger/balance-sheet.ts +++ b/src/ledger/balance-sheet.ts @@ -5,17 +5,17 @@ import {ensureLedgerVersion} from './utils' import {RippleAPI} from '..' export type BalanceSheetOptions = { - excludeAddresses?: Array, + excludeAddresses?: Array ledgerVersion?: number } export type GetBalanceSheet = { - balances?: Array, - assets?: Array, + balances?: Array + assets?: Array obligations?: Array<{ - currency: string, - value: string - }> + currency: string + value: string + }> } function formatBalanceSheet(balanceSheet): GetBalanceSheet { @@ -48,7 +48,9 @@ function formatBalanceSheet(balanceSheet): GetBalanceSheet { } async function getBalanceSheet( - this: RippleAPI, address: string, options: BalanceSheetOptions = {} + this: RippleAPI, + address: string, + options: BalanceSheetOptions = {} ): Promise { // 1. Validate validate.getBalanceSheet({address, options}) diff --git a/src/ledger/balances.ts b/src/ledger/balances.ts index 82075fd6..a70ec151 100644 --- a/src/ledger/balances.ts +++ b/src/ledger/balances.ts @@ -6,8 +6,8 @@ import {FormattedTrustline} from '../common/types/objects/trustlines' import {RippleAPI} from '..' export type Balance = { - value: string, - currency: string, + value: string + currency: string counterparty?: string } @@ -23,9 +23,9 @@ function getTrustlineBalanceAmount(trustline: FormattedTrustline) { function formatBalances(options, balances) { const result = balances.trustlines.map(getTrustlineBalanceAmount) - if (!(options.counterparty || - (options.currency && options.currency !== 'XRP') - )) { + if ( + !(options.counterparty || (options.currency && options.currency !== 'XRP')) + ) { const xrpBalance = { currency: 'XRP', value: balances.xrp @@ -39,7 +39,9 @@ function formatBalances(options, balances) { return result } -function getLedgerVersionHelper(connection: Connection, optionValue?: number +function getLedgerVersionHelper( + connection: Connection, + optionValue?: number ): Promise { if (optionValue !== undefined && optionValue !== null) { return Promise.resolve(optionValue) @@ -47,7 +49,10 @@ function getLedgerVersionHelper(connection: Connection, optionValue?: number return connection.getLedgerVersion() } -function getBalances(this: RippleAPI, address: string, options: GetTrustlinesOptions = {} +function getBalances( + this: RippleAPI, + address: string, + options: GetTrustlinesOptions = {} ): Promise { validate.getTrustlines({address, options}) @@ -59,12 +64,16 @@ function getBalances(this: RippleAPI, address: string, options: GetTrustlinesOpt address = ensureClassicAddress(address) return Promise.all([ - getLedgerVersionHelper(this.connection, options.ledgerVersion).then( - ledgerVersion => - utils.getXRPBalance(this.connection, address, ledgerVersion)), + getLedgerVersionHelper( + this.connection, + options.ledgerVersion + ).then(ledgerVersion => + utils.getXRPBalance(this.connection, address, ledgerVersion) + ), this.getTrustlines(address, options) ]).then(results => - formatBalances(options, {xrp: results[0], trustlines: results[1]})) + formatBalances(options, {xrp: results[0], trustlines: results[1]}) + ) } export default getBalances diff --git a/src/ledger/ledger.ts b/src/ledger/ledger.ts index 766af22e..2ee25613 100644 --- a/src/ledger/ledger.ts +++ b/src/ledger/ledger.ts @@ -3,15 +3,16 @@ import {FormattedLedger, parseLedger} from './parse/ledger' import {RippleAPI} from '..' export type GetLedgerOptions = { - ledgerHash?: string, - ledgerVersion?: number, - includeAllData?: boolean, - includeTransactions?: boolean, + ledgerHash?: string + ledgerVersion?: number + includeAllData?: boolean + includeTransactions?: boolean includeState?: boolean } async function getLedger( - this: RippleAPI, options: GetLedgerOptions = {} + this: RippleAPI, + options: GetLedgerOptions = {} ): Promise { // 1. Validate validate.getLedger({options}) diff --git a/src/ledger/orderbook.ts b/src/ledger/orderbook.ts index 4172c70c..98648bda 100644 --- a/src/ledger/orderbook.ts +++ b/src/ledger/orderbook.ts @@ -11,7 +11,7 @@ import {RippleAPI} from '..' import BigNumber from 'bignumber.js' export type FormattedOrderbook = { - bids: FormattedOrderbookOrder[], + bids: FormattedOrderbookOrder[] asks: FormattedOrderbookOrder[] } @@ -34,13 +34,18 @@ function flipOrder(order: FormattedOrderbookOrder) { return _.merge({}, order, {specification: newSpecification}) } -function alignOrder(base: Issue, order: FormattedOrderbookOrder): FormattedOrderbookOrder { +function alignOrder( + base: Issue, + order: FormattedOrderbookOrder +): FormattedOrderbookOrder { const quantity = order.specification.quantity return isSameIssue(quantity, base) ? order : flipOrder(order) } export function formatBidsAndAsks( - orderbook: OrderbookInfo, offers: BookOffer[]) { + orderbook: OrderbookInfo, + offers: BookOffer[] +) { // the "base" currency is the currency that you are buying or selling // the "counter" is the currency that the "base" is priced in // a "bid"/"ask" is an order to buy/sell the base, respectively @@ -51,9 +56,11 @@ export function formatBidsAndAsks( // for asks: lowest quality => lowest totalPrice/quantity => lowest price // for both bids and asks, lowest quality is closest to mid-market // we sort the orders so that earlier orders are closer to mid-market - const orders = offers.sort((a, b) => { - return (new BigNumber(a.quality)).comparedTo(b.quality) - }).map(parseOrderbookOrder) + const orders = offers + .sort((a, b) => { + return new BigNumber(a.quality).comparedTo(b.quality) + }) + .map(parseOrderbookOrder) const alignedOrders = orders.map(_.partial(alignOrder, orderbook.base)) const bids = alignedOrders.filter(_.partial(directionFilter, 'buy')) @@ -64,8 +71,11 @@ export function formatBidsAndAsks( // account is to specify a "perspective", which affects which unfunded offers // are returned async function makeRequest( - api: RippleAPI, taker: string, options: GetOrderbookOptions, - takerGets: Issue, takerPays: Issue + api: RippleAPI, + taker: string, + options: GetOrderbookOptions, + takerGets: Issue, + takerPays: Issue ) { const orderData = utils.renameCounterpartyToIssuerInOrder({ taker_gets: takerGets, @@ -80,14 +90,13 @@ async function makeRequest( }) } - export type GetOrderbookOptions = { - limit?: number, + limit?: number ledgerVersion?: number } export type OrderbookInfo = { - base: Issue, + base: Issue counter: Issue } @@ -105,10 +114,13 @@ export async function getOrderbook( makeRequest(this, address, options, orderbook.counter, orderbook.base) ]) // 3. Return Formatted Response - const directOffers = _.flatMap(directOfferResults, - directOfferResult => directOfferResult.offers) - const reverseOffers = _.flatMap(reverseOfferResults, - reverseOfferResult => reverseOfferResult.offers) - return formatBidsAndAsks(orderbook, - [...directOffers, ...reverseOffers]) + const directOffers = _.flatMap( + directOfferResults, + directOfferResult => directOfferResult.offers + ) + const reverseOffers = _.flatMap( + reverseOfferResults, + reverseOfferResult => reverseOfferResult.offers + ) + return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers]) } diff --git a/src/ledger/orders.ts b/src/ledger/orders.ts index 6e26e87a..b849b1ea 100644 --- a/src/ledger/orders.ts +++ b/src/ledger/orders.ts @@ -5,12 +5,13 @@ import {RippleAPI} from '..' import {AccountOffersResponse} from '../common/types/commands' export type GetOrdersOptions = { - limit?: number, + limit?: number ledgerVersion?: number } function formatResponse( - address: string, responses: AccountOffersResponse[] + address: string, + responses: AccountOffersResponse[] ): FormattedAccountOrder[] { let orders: FormattedAccountOrder[] = [] for (const response of responses) { @@ -23,14 +24,16 @@ function formatResponse( } export default async function getOrders( - this: RippleAPI, address: string, options: GetOrdersOptions = {} + this: RippleAPI, + address: string, + options: GetOrdersOptions = {} ): Promise { // 1. Validate validate.getOrders({address, options}) // 2. Make Request const responses = await this._requestAll('account_offers', { account: address, - ledger_index: options.ledgerVersion || await this.getLedgerVersion(), + ledger_index: options.ledgerVersion || (await this.getLedgerVersion()), limit: options.limit }) // 3. Return Formatted Response, from the perspective of `address` diff --git a/src/ledger/parse/account-order.ts b/src/ledger/parse/account-order.ts index 3b4e8d1f..354deeb2 100644 --- a/src/ledger/parse/account-order.ts +++ b/src/ledger/parse/account-order.ts @@ -6,10 +6,10 @@ import {orderFlags} from './flags' import {FormattedOrderSpecification} from '../../common/types/objects' export type FormattedAccountOrder = { - specification: FormattedOrderSpecification, - properties: { - maker: string, - sequence: number, + specification: FormattedOrderSpecification + properties: { + maker: string + sequence: number makerExchangeRate: string } } @@ -23,13 +23,14 @@ function computeQuality(takerGets, takerPays) { // rippled 'account_offers' returns a different format for orders than 'tx' // the flags are also different export function parseAccountOrder( - address: string, order: any + address: string, + order: any ): FormattedAccountOrder { const direction = (order.flags & orderFlags.Sell) === 0 ? 'buy' : 'sell' const takerGetsAmount = parseAmount(order.taker_gets) const takerPaysAmount = parseAmount(order.taker_pays) - const quantity = (direction === 'buy') ? takerPaysAmount : takerGetsAmount - const totalPrice = (direction === 'buy') ? takerGetsAmount : takerPaysAmount + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount // note: immediateOrCancel and fillOrKill orders cannot enter the order book // so we can omit those flags here @@ -37,15 +38,18 @@ export function parseAccountOrder( direction: direction, quantity: quantity, totalPrice: totalPrice, - passive: ((order.flags & orderFlags.Passive) !== 0) || undefined, + passive: (order.flags & orderFlags.Passive) !== 0 || undefined, // rippled currently does not provide "expiration" in account_offers expirationTime: parseTimestamp(order.expiration) }) - const makerExchangeRate = order.quality ? - adjustQualityForXRP(order.quality.toString(), - takerGetsAmount.currency, takerPaysAmount.currency) : - computeQuality(takerGetsAmount, takerPaysAmount) + const makerExchangeRate = order.quality + ? adjustQualityForXRP( + order.quality.toString(), + takerGetsAmount.currency, + takerPaysAmount.currency + ) + : computeQuality(takerGetsAmount, takerPaysAmount) const properties = { maker: address, sequence: order.seq, diff --git a/src/ledger/parse/amendment.ts b/src/ledger/parse/amendment.ts index b6cac001..7c25cf75 100644 --- a/src/ledger/parse/amendment.ts +++ b/src/ledger/parse/amendment.ts @@ -1,5 +1,3 @@ - - function parseAmendment(tx: any) { return { amendment: tx.Amendment diff --git a/src/ledger/parse/amount.ts b/src/ledger/parse/amount.ts index ca6883c8..578bbb73 100644 --- a/src/ledger/parse/amount.ts +++ b/src/ledger/parse/amount.ts @@ -1,7 +1,6 @@ import * as common from '../../common' import {Amount, RippledAmount} from '../../common/types/objects' - function parseAmount(amount: RippledAmount): Amount { if (typeof amount === 'string') { return { diff --git a/src/ledger/parse/check-cancel.ts b/src/ledger/parse/check-cancel.ts index edd8f5b0..97a1d058 100644 --- a/src/ledger/parse/check-cancel.ts +++ b/src/ledger/parse/check-cancel.ts @@ -2,7 +2,6 @@ import * as assert from 'assert' import {removeUndefined} from '../../common' export type FormattedCheckCancel = { - // ID of the Check ledger object to cancel. checkID: string } diff --git a/src/ledger/parse/check-cash.ts b/src/ledger/parse/check-cash.ts index b2a7db46..9dc31e74 100644 --- a/src/ledger/parse/check-cash.ts +++ b/src/ledger/parse/check-cash.ts @@ -4,14 +4,13 @@ import parseAmount from './amount' import {Amount} from '../../common/types/objects' export type FormattedCheckCash = { - // ID of the Check ledger object to cash. - checkID: string, + checkID: string // (Optional) redeem the Check for exactly this amount, if possible. // The currency must match that of the `SendMax` of the corresponding // `CheckCreate` transaction. - amount: Amount, + amount: Amount // (Optional) redeem the Check for at least this amount and // for as much as possible. diff --git a/src/ledger/parse/check-create.ts b/src/ledger/parse/check-create.ts index 6a08edee..8c502e90 100644 --- a/src/ledger/parse/check-create.ts +++ b/src/ledger/parse/check-create.ts @@ -5,19 +5,18 @@ import parseAmount from './amount' import {Amount} from '../../common/types/objects' export type FormattedCheckCreate = { - // account that can cash the check. - destination: string, + destination: string // amount the check is allowed to debit the sender, // including transfer fees on non-XRP currencies. - sendMax: Amount, + sendMax: Amount // (Optional) identifies the reason for the check, or a hosted recipient. - destinationTag?: string, + destinationTag?: string // (Optional) time in seconds since the Ripple Epoch. - expiration?: string, + expiration?: string // (Optional) 256-bit hash representing a specific reason or identifier. invoiceID?: string diff --git a/src/ledger/parse/deposit-preauth.ts b/src/ledger/parse/deposit-preauth.ts index eac29691..6517691d 100644 --- a/src/ledger/parse/deposit-preauth.ts +++ b/src/ledger/parse/deposit-preauth.ts @@ -3,7 +3,7 @@ import {removeUndefined} from '../../common' export type FormattedDepositPreauth = { // account (address) of the sender to preauthorize - authorize: string, + authorize: string // account (address) of the sender whose preauthorization should be revoked unauthorize: string diff --git a/src/ledger/parse/fee-update.ts b/src/ledger/parse/fee-update.ts index 7084302d..600b002b 100644 --- a/src/ledger/parse/fee-update.ts +++ b/src/ledger/parse/fee-update.ts @@ -1,9 +1,8 @@ - import BigNumber from 'bignumber.js' import {dropsToXrp} from '../../common' function parseFeeUpdate(tx: any) { - const baseFeeDrops = (new BigNumber(tx.BaseFee, 16)).toString() + const baseFeeDrops = new BigNumber(tx.BaseFee, 16).toString() return { baseFeeXRP: dropsToXrp(baseFeeDrops), referenceFeeUnits: tx.ReferenceFeeUnits, diff --git a/src/ledger/parse/fields.ts b/src/ledger/parse/fields.ts index 307d6fc2..8c2faf71 100644 --- a/src/ledger/parse/fields.ts +++ b/src/ledger/parse/fields.ts @@ -4,11 +4,12 @@ import {constants} from '../../common' const AccountFields = constants.AccountFields function parseField(info, value) { - if (info.encoding === 'hex' && !info.length) { // e.g. "domain" + if (info.encoding === 'hex' && !info.length) { + // e.g. "domain" return Buffer.from(value, 'hex').toString('ascii') } if (info.shift) { - return (new BigNumber(value)).shiftedBy(-info.shift).toNumber() + return new BigNumber(value).shiftedBy(-info.shift).toNumber() } return value } @@ -42,7 +43,8 @@ function parseFields(data: any): object { address: entry.SignerEntry.Account, weight: entry.SignerEntry.SignerWeight } - }) + } + ) } } return settings diff --git a/src/ledger/parse/flags.ts b/src/ledger/parse/flags.ts index 1937415f..b6bd69af 100644 --- a/src/ledger/parse/flags.ts +++ b/src/ledger/parse/flags.ts @@ -1,5 +1,3 @@ - - const orderFlags = { Passive: 0x00010000, Sell: 0x00020000 // offer was placed as a sell @@ -16,7 +14,4 @@ const trustlineFlags = { HighFreeze: 0x00800000 } -export { - orderFlags, - trustlineFlags -} +export {orderFlags, trustlineFlags} diff --git a/src/ledger/parse/ledger.ts b/src/ledger/parse/ledger.ts index b28db697..7f8cb258 100644 --- a/src/ledger/parse/ledger.ts +++ b/src/ledger/parse/ledger.ts @@ -7,19 +7,19 @@ export type FormattedLedger = { // TODO: properties in type don't match response object. Fix! // accepted: boolean, // closed: boolean, - stateHash: string, - closeTime: string, - closeTimeResolution: number, - closeFlags: number, - ledgerHash: string, - ledgerVersion: number, - parentLedgerHash: string, - parentCloseTime: string, - totalDrops: string, - transactionHash: string, - transactions?: Array, - transactionHashes?: Array, - rawState?: string, + stateHash: string + closeTime: string + closeTimeResolution: number + closeFlags: number + ledgerHash: string + ledgerVersion: number + parentLedgerHash: string + parentCloseTime: string + totalDrops: string + transactionHash: string + transactions?: Array + transactionHashes?: Array + rawState?: string stateHashes?: Array } @@ -44,8 +44,10 @@ function parseTransactions(transactions, ledgerVersion) { return {transactionHashes: transactions} } return { - transactions: _.map(transactions, - _.partial(parseTransactionWrapper, ledgerVersion)) + transactions: _.map( + transactions, + _.partial(parseTransactionWrapper, ledgerVersion) + ) } } @@ -66,20 +68,22 @@ function parseState(state) { */ export function parseLedger(ledger: Ledger): FormattedLedger { const ledgerVersion = parseInt(ledger.ledger_index || ledger.seqNum, 10) - return removeUndefined(Object.assign( - { - stateHash: ledger.account_hash, - closeTime: rippleTimeToISO8601(ledger.close_time), - closeTimeResolution: ledger.close_time_resolution, - closeFlags: ledger.close_flags, - ledgerHash: ledger.hash || ledger.ledger_hash, - ledgerVersion: ledgerVersion, - parentLedgerHash: ledger.parent_hash, - parentCloseTime: rippleTimeToISO8601(ledger.parent_close_time), - totalDrops: ledger.total_coins || ledger.totalCoins, - transactionHash: ledger.transaction_hash - }, - parseTransactions(ledger.transactions, ledgerVersion), - parseState(ledger.accountState) - )) + return removeUndefined( + Object.assign( + { + stateHash: ledger.account_hash, + closeTime: rippleTimeToISO8601(ledger.close_time), + closeTimeResolution: ledger.close_time_resolution, + closeFlags: ledger.close_flags, + ledgerHash: ledger.hash || ledger.ledger_hash, + ledgerVersion: ledgerVersion, + parentLedgerHash: ledger.parent_hash, + parentCloseTime: rippleTimeToISO8601(ledger.parent_close_time), + totalDrops: ledger.total_coins || ledger.totalCoins, + transactionHash: ledger.transaction_hash + }, + parseTransactions(ledger.transactions, ledgerVersion), + parseState(ledger.accountState) + ) + ) } diff --git a/src/ledger/parse/order.ts b/src/ledger/parse/order.ts index 8a16e8bf..527a3f53 100644 --- a/src/ledger/parse/order.ts +++ b/src/ledger/parse/order.ts @@ -15,17 +15,16 @@ function parseOrder(tx: OfferCreateTransaction): FormattedOrderSpecification { const direction = (tx.Flags & flags.Sell) === 0 ? 'buy' : 'sell' const takerGetsAmount = parseAmount(tx.TakerGets) const takerPaysAmount = parseAmount(tx.TakerPays) - const quantity = (direction === 'buy') ? takerPaysAmount : takerGetsAmount - const totalPrice = (direction === 'buy') ? takerGetsAmount : takerPaysAmount + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount return removeUndefined({ direction: direction, quantity: quantity, totalPrice: totalPrice, - passive: ((tx.Flags & flags.Passive) !== 0) || undefined, - immediateOrCancel: ((tx.Flags & flags.ImmediateOrCancel) !== 0) - || undefined, - fillOrKill: ((tx.Flags & flags.FillOrKill) !== 0) || undefined, + passive: (tx.Flags & flags.Passive) !== 0 || undefined, + immediateOrCancel: (tx.Flags & flags.ImmediateOrCancel) !== 0 || undefined, + fillOrKill: (tx.Flags & flags.FillOrKill) !== 0 || undefined, expirationTime: parseTimestamp(tx.Expiration) }) } diff --git a/src/ledger/parse/orderbook-order.ts b/src/ledger/parse/orderbook-order.ts index 1a623d6b..3eac581c 100644 --- a/src/ledger/parse/orderbook-order.ts +++ b/src/ledger/parse/orderbook-order.ts @@ -8,27 +8,25 @@ import {BookOffer} from '../../common/types/commands' import {Amount, FormattedOrderSpecification} from '../../common/types/objects' export type FormattedOrderbookOrder = { - specification: FormattedOrderSpecification, + specification: FormattedOrderSpecification properties: { - maker: string, - sequence: number, + maker: string + sequence: number makerExchangeRate: string - }, + } state?: { - fundedAmount: Amount, + fundedAmount: Amount priceOfFundedAmount: Amount - }, + } data: BookOffer } -export function parseOrderbookOrder( - data: BookOffer -): FormattedOrderbookOrder { +export function parseOrderbookOrder(data: BookOffer): FormattedOrderbookOrder { const direction = (data.Flags & orderFlags.Sell) === 0 ? 'buy' : 'sell' const takerGetsAmount = parseAmount(data.TakerGets) const takerPaysAmount = parseAmount(data.TakerPays) - const quantity = (direction === 'buy') ? takerPaysAmount : takerGetsAmount - const totalPrice = (direction === 'buy') ? takerGetsAmount : takerPaysAmount + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount // note: immediateOrCancel and fillOrKill orders cannot enter the order book // so we can omit those flags here @@ -36,21 +34,26 @@ export function parseOrderbookOrder( direction: direction, quantity: quantity, totalPrice: totalPrice, - passive: ((data.Flags & orderFlags.Passive) !== 0) || undefined, + passive: (data.Flags & orderFlags.Passive) !== 0 || undefined, expirationTime: parseTimestamp(data.Expiration) }) const properties = { maker: data.Account, sequence: data.Sequence, - makerExchangeRate: adjustQualityForXRP(data.quality, - takerGetsAmount.currency, takerPaysAmount.currency) + makerExchangeRate: adjustQualityForXRP( + data.quality, + takerGetsAmount.currency, + takerPaysAmount.currency + ) } - const takerGetsFunded = data.taker_gets_funded ? - parseAmount(data.taker_gets_funded) : undefined - const takerPaysFunded = data.taker_pays_funded ? - parseAmount(data.taker_pays_funded) : undefined + const takerGetsFunded = data.taker_gets_funded + ? parseAmount(data.taker_gets_funded) + : undefined + const takerPaysFunded = data.taker_pays_funded + ? parseAmount(data.taker_pays_funded) + : undefined const available = removeUndefined({ fundedAmount: takerGetsFunded, priceOfFundedAmount: takerPaysFunded diff --git a/src/ledger/parse/pathfind.ts b/src/ledger/parse/pathfind.ts index 37649ba8..88d08e6e 100644 --- a/src/ledger/parse/pathfind.ts +++ b/src/ledger/parse/pathfind.ts @@ -4,33 +4,48 @@ 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'])) + ) } function removeAnyCounterpartyEncoding(address: string, amount: Amount) { - return amount.counterparty === address ? - _.omit(amount, 'counterparty') : amount + return amount.counterparty === address + ? _.omit(amount, 'counterparty') + : amount } function createAdjustment( - address: string, adjustmentWithoutAddress: object): any { + address: string, + adjustmentWithoutAddress: object +): any { const amountKey = _.keys(adjustmentWithoutAddress)[0] const amount = adjustmentWithoutAddress[amountKey] - return _.set({address: address}, amountKey, - removeAnyCounterpartyEncoding(address, amount)) + return _.set( + {address: address}, + amountKey, + removeAnyCounterpartyEncoding(address, amount) + ) } -function parseAlternative(sourceAddress: string, destinationAddress: string, - destinationAmount: RippledAmount, alternative: any +function parseAlternative( + sourceAddress: string, + destinationAddress: string, + destinationAmount: RippledAmount, + alternative: any ): Path { // we use "maxAmount"/"minAmount" here so that the result can be passed // directly to preparePayment - const amounts = (alternative.destination_amount !== undefined) ? - {source: {amount: parseAmount(alternative.source_amount)}, - destination: {minAmount: parseAmount(alternative.destination_amount)}} : - {source: {maxAmount: parseAmount(alternative.source_amount)}, - destination: {amount: parseAmount(destinationAmount)}} + const amounts = + alternative.destination_amount !== undefined + ? { + source: {amount: parseAmount(alternative.source_amount)}, + destination: {minAmount: parseAmount(alternative.destination_amount)} + } + : { + source: {maxAmount: parseAmount(alternative.source_amount)}, + destination: {amount: parseAmount(destinationAmount)} + } return { source: createAdjustment(sourceAddress, amounts.source), @@ -44,7 +59,8 @@ function parsePathfind(pathfindResult: RippledPathsResponse): GetPaths { const destinationAddress = pathfindResult.destination_account const destinationAmount = pathfindResult.destination_amount return pathfindResult.alternatives.map(alt => - parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt)) + parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt) + ) } export default parsePathfind diff --git a/src/ledger/parse/payment-channel.ts b/src/ledger/parse/payment-channel.ts index d8517b59..3b83b784 100644 --- a/src/ledger/parse/payment-channel.ts +++ b/src/ledger/parse/payment-channel.ts @@ -3,17 +3,17 @@ import {removeUndefined, dropsToXrp} from '../../common' import {PayChannelLedgerEntry} from '../../common/types/objects' export type FormattedPaymentChannel = { - account: string, - amount: string, - balance: string, - publicKey: string, - destination: string, - settleDelay: number, - expiration?: string, - cancelAfter?: string, - sourceTag?: number, - destinationTag?: number, - previousAffectingTransactionID: string, + account: string + amount: string + balance: string + publicKey: string + destination: string + settleDelay: number + expiration?: string + cancelAfter?: string + sourceTag?: number + destinationTag?: number + previousAffectingTransactionID: string previousAffectingTransactionLedgerVersion: number } diff --git a/src/ledger/parse/payment.ts b/src/ledger/parse/payment.ts index 5089bf90..749d2480 100644 --- a/src/ledger/parse/payment.ts +++ b/src/ledger/parse/payment.ts @@ -13,8 +13,9 @@ function isQualityLimited(tx) { } function removeGenericCounterparty(amount, address) { - return amount.counterparty === address ? - _.omit(amount, 'counterparty') : amount + return amount.counterparty === address + ? _.omit(amount, 'counterparty') + : amount } // Payment specification @@ -24,12 +25,14 @@ function parsePayment(tx: any): object { const source = { address: tx.Account, maxAmount: removeGenericCounterparty( - parseAmount(tx.SendMax || tx.Amount), tx.Account), + parseAmount(tx.SendMax || tx.Amount), + tx.Account + ), tag: tx.SourceTag } const destination: { - address: string, + address: string tag: number | undefined } = { address: tx.Destination, diff --git a/src/ledger/parse/settings.ts b/src/ledger/parse/settings.ts index 44f3b100..b23eaf88 100644 --- a/src/ledger/parse/settings.ts +++ b/src/ledger/parse/settings.ts @@ -5,8 +5,9 @@ const AccountFlags = constants.AccountFlags import parseFields from './fields' function getAccountRootModifiedNode(tx: any) { - const modifiedNodes = tx.meta.AffectedNodes.filter(node => - node.ModifiedNode.LedgerEntryType === 'AccountRoot') + const modifiedNodes = tx.meta.AffectedNodes.filter( + node => node.ModifiedNode.LedgerEntryType === 'AccountRoot' + ) assert.ok(modifiedNodes.length === 1) return modifiedNodes[0].ModifiedNode } @@ -51,8 +52,11 @@ function parseFlags(tx: any): any { function parseSettings(tx: any) { const txType = tx.TransactionType - assert.ok(txType === 'AccountSet' || txType === 'SetRegularKey' || - txType === 'SignerListSet') + assert.ok( + txType === 'AccountSet' || + txType === 'SetRegularKey' || + txType === 'SignerListSet' + ) return _.assign({}, parseFlags(tx), parseFields(tx)) } diff --git a/src/ledger/parse/transaction.ts b/src/ledger/parse/transaction.ts index a4996f59..a6290faf 100644 --- a/src/ledger/parse/transaction.ts +++ b/src/ledger/parse/transaction.ts @@ -49,30 +49,33 @@ function parseTransactionType(type) { function parseTransaction(tx: any, includeRawTransaction: boolean): any { const type = parseTransactionType(tx.TransactionType) const mapping = { - 'payment': parsePayment, - 'trustline': parseTrustline, - 'order': parseOrder, - 'orderCancellation': parseOrderCancellation, - 'settings': parseSettings, - 'escrowCreation': parseEscrowCreation, - 'escrowExecution': parseEscrowExecution, - 'escrowCancellation': parseEscrowCancellation, - 'checkCreate': parseCheckCreate, - 'checkCash': parseCheckCash, - 'checkCancel': parseCheckCancel, - 'depositPreauth': parseDepositPreauth, - 'paymentChannelCreate': parsePaymentChannelCreate, - 'paymentChannelFund': parsePaymentChannelFund, - 'paymentChannelClaim': parsePaymentChannelClaim, - 'feeUpdate': parseFeeUpdate, - 'amendment': parseAmendment + payment: parsePayment, + trustline: parseTrustline, + order: parseOrder, + orderCancellation: parseOrderCancellation, + settings: parseSettings, + escrowCreation: parseEscrowCreation, + escrowExecution: parseEscrowExecution, + escrowCancellation: parseEscrowCancellation, + checkCreate: parseCheckCreate, + checkCash: parseCheckCash, + checkCancel: parseCheckCancel, + depositPreauth: parseDepositPreauth, + paymentChannelCreate: parsePaymentChannelCreate, + paymentChannelFund: parsePaymentChannelFund, + paymentChannelClaim: parsePaymentChannelClaim, + feeUpdate: parseFeeUpdate, + amendment: parseAmendment } const parser: Function = mapping[type] - const specification = parser ? parser(tx) : { - UNAVAILABLE: 'Unrecognized transaction type.', - SEE_RAW_TRANSACTION: 'Since this type is unrecognized, `rawTransaction` is included in this response.' - } + const specification = parser + ? parser(tx) + : { + UNAVAILABLE: 'Unrecognized transaction type.', + SEE_RAW_TRANSACTION: + 'Since this type is unrecognized, `rawTransaction` is included in this response.' + } if (!parser) { includeRawTransaction = true } diff --git a/src/ledger/parse/trustline.ts b/src/ledger/parse/trustline.ts index ee0982c1..f284e9cd 100644 --- a/src/ledger/parse/trustline.ts +++ b/src/ledger/parse/trustline.ts @@ -24,7 +24,10 @@ function parseTrustline(tx: any): object { qualityIn: parseQuality(tx.QualityIn), qualityOut: parseQuality(tx.QualityOut), ripplingDisabled: parseFlag( - tx.Flags, flags.SetNoRipple, flags.ClearNoRipple), + tx.Flags, + flags.SetNoRipple, + flags.ClearNoRipple + ), frozen: parseFlag(tx.Flags, flags.SetFreeze, flags.ClearFreeze), authorized: parseFlag(tx.Flags, flags.SetAuth, 0) }) diff --git a/src/ledger/parse/utils.ts b/src/ledger/parse/utils.ts index fe1cf83e..e450aa4b 100644 --- a/src/ledger/parse/utils.ts +++ b/src/ledger/parse/utils.ts @@ -7,25 +7,28 @@ import parseAmount from './amount' import {Amount, Memo} from '../../common/types/objects' function adjustQualityForXRP( - quality: string, takerGetsCurrency: string, takerPaysCurrency: string + quality: string, + takerGetsCurrency: string, + takerPaysCurrency: string ) { // quality = takerPays.value/takerGets.value // using drops (1e-6 XRP) for XRP values - const numeratorShift = (takerPaysCurrency === 'XRP' ? -6 : 0) - const denominatorShift = (takerGetsCurrency === 'XRP' ? -6 : 0) + const numeratorShift = takerPaysCurrency === 'XRP' ? -6 : 0 + const denominatorShift = takerGetsCurrency === 'XRP' ? -6 : 0 const shift = numeratorShift - denominatorShift - return shift === 0 ? quality : - (new BigNumber(quality)).shiftedBy(shift).toString() + return shift === 0 + ? quality + : new BigNumber(quality).shiftedBy(shift).toString() } -function parseQuality(quality?: number|null): number|undefined { +function parseQuality(quality?: number | null): number | undefined { if (typeof quality !== 'number') { return undefined } - return (new BigNumber(quality)).shiftedBy(-9).toNumber() + return new BigNumber(quality).shiftedBy(-9).toNumber() } -function parseTimestamp(rippleTime?: number|null): string|undefined { +function parseTimestamp(rippleTime?: number | null): string | undefined { if (typeof rippleTime !== 'number') { return undefined } @@ -57,14 +60,14 @@ function isPartialPayment(tx: any) { } function parseDeliveredAmount(tx: any): Amount | void { - - if (tx.TransactionType !== 'Payment' || - tx.meta.TransactionResult !== 'tesSUCCESS') { + if ( + tx.TransactionType !== 'Payment' || + tx.meta.TransactionResult !== 'tesSUCCESS' + ) { return undefined } - if (tx.meta.delivered_amount && - tx.meta.delivered_amount === 'unavailable') { + if (tx.meta.delivered_amount && tx.meta.delivered_amount === 'unavailable') { return undefined } @@ -96,7 +99,7 @@ function parseDeliveredAmount(tx: any): Amount | void { return undefined } -function parseOutcome(tx: any): any|undefined { +function parseOutcome(tx: any): any | undefined { const metadata = tx.meta || tx.metaData if (!metadata) { return undefined @@ -121,11 +124,11 @@ function parseOutcome(tx: any): any|undefined { }) } -function hexToString(hex: string): string|undefined { +function hexToString(hex: string): string | undefined { return hex ? Buffer.from(hex, 'hex').toString('utf-8') : undefined } -function parseMemos(tx: any): Array|undefined { +function parseMemos(tx: any): Array | undefined { if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) { return undefined } diff --git a/src/ledger/pathfind-types.ts b/src/ledger/pathfind-types.ts index 238029a2..76df0610 100644 --- a/src/ledger/pathfind-types.ts +++ b/src/ledger/pathfind-types.ts @@ -1,18 +1,22 @@ - -import {Amount, RippledAmount, Adjustment, MaxAdjustment, - MinAdjustment} from '../common/types/objects' +import { + Amount, + RippledAmount, + Adjustment, + MaxAdjustment, + MinAdjustment +} from '../common/types/objects' // Amount where counterparty and value are optional export type LaxLaxAmount = { - currency: string, - value?: string, - issuer?: string, + currency: string + value?: string + issuer?: string counterparty?: string } export type Path = { - source: Adjustment | MaxAdjustment, - destination: Adjustment | MinAdjustment, + source: Adjustment | MaxAdjustment + destination: Adjustment | MinAdjustment paths: string } @@ -20,41 +24,43 @@ export type GetPaths = Array export type PathFind = { source: { - address: string, - amount?: Amount, - currencies?: Array<{currency: string, counterparty?:string}> - }, + address: string + amount?: Amount + currencies?: Array<{currency: string; counterparty?: string}> + } destination: { - address: string, + address: string amount: LaxLaxAmount } } export type PathFindRequest = { - command: string, - source_account: string, - destination_amount: RippledAmount, - destination_account: string, - source_currencies?: {currency: string, issuer?: string}[], + command: string + source_account: string + destination_amount: RippledAmount + destination_account: string + source_currencies?: {currency: string; issuer?: string}[] send_max?: RippledAmount } export type RippledPathsResponse = { alternatives: Array<{ - paths_computed: Array>, + paths_computed: Array< + Array<{ + type: number + type_hex: string + account?: string + issuer?: string + currency?: string + }> + > source_amount: RippledAmount - }>, - type: string, - destination_account: string, - destination_amount: RippledAmount, - destination_currencies?: Array, - source_account: string, - source_currencies?: Array<{currency: string}>, + }> + type: string + destination_account: string + destination_amount: RippledAmount + destination_currencies?: Array + source_account: string + source_currencies?: Array<{currency: string}> full_reply?: boolean } diff --git a/src/ledger/pathfind.ts b/src/ledger/pathfind.ts index 652d76d3..36ee558c 100644 --- a/src/ledger/pathfind.ts +++ b/src/ledger/pathfind.ts @@ -12,28 +12,37 @@ import {Connection} from '../common' import parsePathfind from './parse/pathfind' import {RippledAmount, Amount} from '../common/types/objects' import { - GetPaths, PathFind, RippledPathsResponse, PathFindRequest + GetPaths, + PathFind, + RippledPathsResponse, + PathFindRequest } from './pathfind-types' import {RippleAPI} from '..' const NotFoundError = errors.NotFoundError const ValidationError = errors.ValidationError - -function addParams(request: PathFindRequest, result: RippledPathsResponse +function addParams( + request: PathFindRequest, + result: RippledPathsResponse ): RippledPathsResponse { - return _.defaults(_.assign({}, result, { - source_account: request.source_account, - source_currencies: request.source_currencies - }), {destination_amount: request.destination_amount}) + return _.defaults( + _.assign({}, result, { + source_account: request.source_account, + source_currencies: request.source_currencies + }), + {destination_amount: request.destination_amount} + ) } -function requestPathFind(connection: Connection, pathfind: PathFind +function requestPathFind( + connection: Connection, + pathfind: PathFind ): Promise { const destinationAmount: Amount = _.assign( { // This is converted back to drops by toRippledAmount() - value: pathfind.destination.amount.currency === 'XRP' ? - dropsToXrp('-1') : '-1' + value: + pathfind.destination.amount.currency === 'XRP' ? dropsToXrp('-1') : '-1' }, pathfind.destination.amount ) @@ -43,21 +52,26 @@ function requestPathFind(connection: Connection, pathfind: PathFind destination_account: pathfind.destination.address, destination_amount: toRippledAmount(destinationAmount) } - if (typeof request.destination_amount === 'object' - && !request.destination_amount.issuer) { + if ( + typeof request.destination_amount === 'object' && + !request.destination_amount.issuer + ) { // Convert blank issuer to sender's address // (Ripple convention for 'any issuer') // https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount request.destination_amount.issuer = request.destination_account } if (pathfind.source.currencies && pathfind.source.currencies.length > 0) { - request.source_currencies = pathfind.source.currencies.map( - amount => renameCounterpartyToIssuer(amount)) + request.source_currencies = pathfind.source.currencies.map(amount => + renameCounterpartyToIssuer(amount) + ) } if (pathfind.source.amount) { if (pathfind.destination.amount.value !== undefined) { - throw new ValidationError('Cannot specify both source.amount' - + ' and destination.amount.value in getPaths') + throw new ValidationError( + 'Cannot specify both source.amount' + + ' and destination.amount.value in getPaths' + ) } request.send_max = toRippledAmount(pathfind.source.amount) if (typeof request.send_max !== 'string' && !request.send_max.issuer) { @@ -68,12 +82,14 @@ function requestPathFind(connection: Connection, pathfind: PathFind return connection.request(request).then(paths => addParams(request, paths)) } -function addDirectXrpPath(paths: RippledPathsResponse, xrpBalance: string +function addDirectXrpPath( + paths: RippledPathsResponse, + xrpBalance: string ): RippledPathsResponse { // Add XRP "path" only if the source acct has enough XRP to make the payment const destinationAmount = paths.destination_amount // @ts-ignore: destinationAmount can be a currency amount object! Fix! - if ((new BigNumber(xrpBalance)).isGreaterThanOrEqualTo(destinationAmount)) { + if (new BigNumber(xrpBalance).isGreaterThanOrEqualTo(destinationAmount)) { paths.alternatives.unshift({ paths_computed: [], source_amount: paths.destination_amount @@ -84,38 +100,49 @@ function addDirectXrpPath(paths: RippledPathsResponse, xrpBalance: string function isRippledIOUAmount(amount: RippledAmount) { // rippled XRP amounts are specified as decimal strings - return (typeof amount === 'object') && - amount.currency && (amount.currency !== 'XRP') + return ( + typeof amount === 'object' && amount.currency && amount.currency !== 'XRP' + ) } -function conditionallyAddDirectXRPPath(connection: Connection, address: string, +function conditionallyAddDirectXRPPath( + connection: Connection, + address: string, paths: RippledPathsResponse ): Promise { - if (isRippledIOUAmount(paths.destination_amount) - || !_.includes(paths.destination_currencies, 'XRP')) { + if ( + isRippledIOUAmount(paths.destination_amount) || + !_.includes(paths.destination_currencies, 'XRP') + ) { return Promise.resolve(paths) } - return getXRPBalance(connection, address, undefined).then( - xrpBalance => addDirectXrpPath(paths, xrpBalance)) + return getXRPBalance(connection, address, undefined).then(xrpBalance => + addDirectXrpPath(paths, xrpBalance) + ) } -function filterSourceFundsLowPaths(pathfind: PathFind, +function filterSourceFundsLowPaths( + pathfind: PathFind, paths: RippledPathsResponse ): RippledPathsResponse { - if (pathfind.source.amount && - pathfind.destination.amount.value === undefined && paths.alternatives) { + if ( + pathfind.source.amount && + pathfind.destination.amount.value === undefined && + paths.alternatives + ) { paths.alternatives = _.filter(paths.alternatives, alt => { if (!alt.source_amount) { return false } const pathfindSourceAmountValue = new BigNumber( - pathfind.source.amount.currency === 'XRP' ? - xrpToDrops(pathfind.source.amount.value) : - pathfind.source.amount.value) + pathfind.source.amount.currency === 'XRP' + ? xrpToDrops(pathfind.source.amount.value) + : pathfind.source.amount.value + ) const altSourceAmountValue = new BigNumber( - typeof alt.source_amount === 'string' ? - alt.source_amount : - alt.source_amount.value + typeof alt.source_amount === 'string' + ? alt.source_amount + : alt.source_amount.value ) return altSourceAmountValue.eq(pathfindSourceAmountValue) }) @@ -127,24 +154,35 @@ function formatResponse(pathfind: PathFind, paths: RippledPathsResponse) { if (paths.alternatives && paths.alternatives.length > 0) { return parsePathfind(paths) } - if (paths.destination_currencies !== undefined && - !_.includes(paths.destination_currencies, - pathfind.destination.amount.currency)) { - throw new NotFoundError('No paths found. ' + - 'The destination_account does not accept ' + - pathfind.destination.amount.currency + ', they only accept: ' + - paths.destination_currencies.join(', ')) + if ( + paths.destination_currencies !== undefined && + !_.includes( + paths.destination_currencies, + pathfind.destination.amount.currency + ) + ) { + throw new NotFoundError( + 'No paths found. ' + + 'The destination_account does not accept ' + + pathfind.destination.amount.currency + + ', they only accept: ' + + paths.destination_currencies.join(', ') + ) } else if (paths.source_currencies && paths.source_currencies.length > 0) { - throw new NotFoundError('No paths found. Please ensure' + - ' that the source_account has sufficient funds to execute' + - ' the payment in one of the specified source_currencies. If it does' + - ' there may be insufficient liquidity in the network to execute' + - ' this payment right now') + throw new NotFoundError( + 'No paths found. Please ensure' + + ' that the source_account has sufficient funds to execute' + + ' the payment in one of the specified source_currencies. If it does' + + ' there may be insufficient liquidity in the network to execute' + + ' this payment right now' + ) } else { - throw new NotFoundError('No paths found.' + - ' Please ensure that the source_account has sufficient funds to' + - ' execute the payment. If it does there may be insufficient liquidity' + - ' in the network to execute this payment right now') + throw new NotFoundError( + 'No paths found.' + + ' Please ensure that the source_account has sufficient funds to' + + ' execute the payment. If it does there may be insufficient liquidity' + + ' in the network to execute this payment right now' + ) } } @@ -152,9 +190,10 @@ function getPaths(this: RippleAPI, pathfind: PathFind): Promise { validate.getPaths({pathfind}) const address = pathfind.source.address - return requestPathFind(this.connection, pathfind).then(paths => - conditionallyAddDirectXRPPath(this.connection, address, paths) - ) + return requestPathFind(this.connection, pathfind) + .then(paths => + conditionallyAddDirectXRPPath(this.connection, address, paths) + ) .then(paths => filterSourceFundsLowPaths(pathfind, paths)) .then(paths => formatResponse(pathfind, paths)) } diff --git a/src/ledger/payment-channel.ts b/src/ledger/payment-channel.ts index 2eba8c90..89562371 100644 --- a/src/ledger/payment-channel.ts +++ b/src/ledger/payment-channel.ts @@ -10,15 +10,18 @@ const NotFoundError = errors.NotFoundError function formatResponse( response: LedgerEntryResponse ): FormattedPaymentChannel { - if (response.node === undefined || - response.node.LedgerEntryType !== 'PayChannel') { + if ( + response.node === undefined || + response.node.LedgerEntryType !== 'PayChannel' + ) { throw new NotFoundError('Payment channel ledger entry not found') } return parsePaymentChannel(response.node) } async function getPaymentChannel( - this: RippleAPI, id: string + this: RippleAPI, + id: string ): Promise { // 1. Validate validate.getPaymentChannel({id}) diff --git a/src/ledger/settings.ts b/src/ledger/settings.ts index 51babebb..98aa7dd4 100644 --- a/src/ledger/settings.ts +++ b/src/ledger/settings.ts @@ -12,8 +12,9 @@ export type SettingsOptions = { } export function parseAccountFlags( - value: number, - options: {excludeFalse?: boolean} = {}) { + value: number, + options: {excludeFalse?: boolean} = {} +) { const settings = {} for (const flagName in AccountFlags) { if (value & AccountFlags[flagName]) { @@ -35,7 +36,9 @@ function formatSettings(response: AccountInfoResponse) { } export async function getSettings( - this: RippleAPI, address: string, options: SettingsOptions = {} + this: RippleAPI, + address: string, + options: SettingsOptions = {} ): Promise { // 1. Validate validate.getSettings({address, options}) diff --git a/src/ledger/transaction.ts b/src/ledger/transaction.ts index 227a59e9..46ae5133 100644 --- a/src/ledger/transaction.ts +++ b/src/ledger/transaction.ts @@ -8,19 +8,20 @@ import {RippledError} from '../common/errors' import {RippleAPI} from '..' export type TransactionOptions = { - minLedgerVersion?: number, - maxLedgerVersion?: number, + minLedgerVersion?: number + maxLedgerVersion?: number includeRawTransaction?: boolean } type TransactionResponse = FormattedTransactionType & { - hash: string, - ledger_index: number, - meta: any, - validated?: boolean + hash: string + ledger_index: number + meta: any + validated?: boolean } - -function attachTransactionDate(connection: Connection, tx: any +function attachTransactionDate( + connection: Connection, + tx: any ): Promise { if (tx.date) { return Promise.resolve(tx) @@ -31,7 +32,8 @@ function attachTransactionDate(connection: Connection, tx: any if (!ledgerVersion) { return new Promise(() => { const error = new errors.NotFoundError( - 'Transaction has not been validated yet; try again later') + 'Transaction has not been validated yet; try again later' + ) error.data = { details: '(ledger_index and LedgerSequence not found in tx)' } @@ -44,56 +46,74 @@ function attachTransactionDate(connection: Connection, tx: any ledger_index: ledgerVersion } - return connection.request(request).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 => { - if (error instanceof errors.UnexpectedError) { - throw error - } - throw new errors.NotFoundError('Transaction ledger not found') - }) + return connection + .request(request) + .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 => { + if (error instanceof errors.UnexpectedError) { + throw error + } + throw new errors.NotFoundError('Transaction ledger not found') + }) } function isTransactionInRange(tx: any, options: TransactionOptions) { - return (!options.minLedgerVersion - || tx.ledger_index >= options.minLedgerVersion) - && (!options.maxLedgerVersion - || tx.ledger_index <= options.maxLedgerVersion) + return ( + (!options.minLedgerVersion || + tx.ledger_index >= options.minLedgerVersion) && + (!options.maxLedgerVersion || tx.ledger_index <= options.maxLedgerVersion) + ) } -function convertError(connection: Connection, options: TransactionOptions, +function convertError( + connection: Connection, + options: TransactionOptions, error: RippledError ): Promise { let shouldUseNotFoundError = false - if ((error.data && error.data.error === 'txnNotFound') || error.message === 'txnNotFound') { + if ( + (error.data && error.data.error === 'txnNotFound') || + error.message === 'txnNotFound' + ) { shouldUseNotFoundError = true } // In the future, we should deprecate this error, instead passing through the one from rippled. - const _error = shouldUseNotFoundError ? new errors.NotFoundError('Transaction not found') : error + const _error = shouldUseNotFoundError + ? new errors.NotFoundError('Transaction not found') + : error if (_error instanceof errors.NotFoundError) { - return utils.hasCompleteLedgerRange(connection, options.minLedgerVersion, - options.maxLedgerVersion).then(hasCompleteLedgerRange => { - if (!hasCompleteLedgerRange) { - return utils.isPendingLedgerVersion( - connection, options.maxLedgerVersion) - .then(isPendingLedgerVersion => { - return isPendingLedgerVersion ? - new errors.PendingLedgerVersionError() : - new errors.MissingLedgerHistoryError() - }) - } - return _error - }) + return utils + .hasCompleteLedgerRange( + connection, + options.minLedgerVersion, + options.maxLedgerVersion + ) + .then(hasCompleteLedgerRange => { + if (!hasCompleteLedgerRange) { + return utils + .isPendingLedgerVersion(connection, options.maxLedgerVersion) + .then(isPendingLedgerVersion => { + return isPendingLedgerVersion + ? new errors.PendingLedgerVersionError() + : new errors.MissingLedgerHistoryError() + }) + } + return _error + }) } return Promise.resolve(_error) } -function formatResponse(options: TransactionOptions, tx: TransactionResponse +function formatResponse( + options: TransactionOptions, + tx: TransactionResponse ): FormattedTransactionType { if (tx.validated !== true || !isTransactionInRange(tx, options)) { throw new errors.NotFoundError('Transaction not found') @@ -101,7 +121,10 @@ function formatResponse(options: TransactionOptions, tx: TransactionResponse return parseTransaction(tx, options.includeRawTransaction) } -async function getTransaction(this: RippleAPI, id: string, options: TransactionOptions = {} +async function getTransaction( + this: RippleAPI, + id: string, + options: TransactionOptions = {} ): Promise { validate.getTransaction({id, options}) const _options = await utils.ensureLedgerVersion.call(this, options) @@ -113,7 +136,7 @@ async function getTransaction(this: RippleAPI, id: string, options: TransactionO const txWithDate = await attachTransactionDate(this.connection, tx) return formatResponse(_options, txWithDate) } catch (error) { - throw (await convertError(this.connection, _options, error)) + throw await convertError(this.connection, _options, error) } } diff --git a/src/ledger/transactions.ts b/src/ledger/transactions.ts index 68c6a3bb..f660f88d 100644 --- a/src/ledger/transactions.ts +++ b/src/ledger/transactions.ts @@ -1,5 +1,5 @@ import * as _ from 'lodash' -import binary from 'ripple-binary-codec'; +import binary from 'ripple-binary-codec' import {computeTransactionHash} from '../common/hashes' import * as utils from './utils' import parseTransaction from './parse/transaction' @@ -9,17 +9,17 @@ import {FormattedTransactionType} from '../transaction/types' import {RippleAPI} from '..' export type TransactionsOptions = { - start?: string, - limit?: number, - minLedgerVersion?: number, - maxLedgerVersion?: number, - earliestFirst?: boolean, - excludeFailures?: boolean, - initiated?: boolean, - counterparty?: string, - types?: Array, - includeRawTransactions?: boolean, - binary?: boolean, + start?: string + limit?: number + minLedgerVersion?: number + maxLedgerVersion?: number + earliestFirst?: boolean + excludeFailures?: boolean + initiated?: boolean + counterparty?: string + types?: Array + includeRawTransactions?: boolean + binary?: boolean startTx?: FormattedTransactionType } @@ -39,8 +39,10 @@ function parseBinaryTransaction(transaction) { function parseAccountTxTransaction(tx, includeRawTransaction: boolean) { const _tx = tx.tx_blob ? parseBinaryTransaction(tx) : tx // rippled uses a different response format for 'account_tx' than 'tx' - return parseTransaction(_.assign({}, _tx.tx, - {meta: _tx.meta, validated: _tx.validated}), includeRawTransaction) + return parseTransaction( + _.assign({}, _tx.tx, {meta: _tx.meta, validated: _tx.validated}), + includeRawTransaction + ) } function counterpartyFilter(filters, tx: FormattedTransactionType) { @@ -48,15 +50,20 @@ function counterpartyFilter(filters, tx: FormattedTransactionType) { return true } const specification: any = tx.specification - if (specification && ((specification.destination && - specification.destination.address === filters.counterparty) || - (specification.counterparty === filters.counterparty))) { - return true + if ( + specification && + ((specification.destination && + specification.destination.address === filters.counterparty) || + specification.counterparty === filters.counterparty) + ) { + return true } return false } -function transactionFilter(address: string, filters: TransactionsOptions, +function transactionFilter( + address: string, + filters: TransactionsOptions, tx: FormattedTransactionType ) { if (filters.excludeFailures && tx.outcome.result !== 'tesSUCCESS') { @@ -78,15 +85,21 @@ function transactionFilter(address: string, filters: TransactionsOptions, } function orderFilter( - options: TransactionsOptions, tx: FormattedTransactionType + options: TransactionsOptions, + tx: FormattedTransactionType ) { - return !options.startTx || (options.earliestFirst ? - utils.compareTransactions(tx, options.startTx) > 0 : - utils.compareTransactions(tx, options.startTx) < 0) + return ( + !options.startTx || + (options.earliestFirst + ? utils.compareTransactions(tx, options.startTx) > 0 + : utils.compareTransactions(tx, options.startTx) < 0) + ) } -function formatPartialResponse(address: string, - options: TransactionsOptions, data +function formatPartialResponse( + address: string, + options: TransactionsOptions, + data ) { const parse = tx => parseAccountTxTransaction(tx, options.includeRawTransactions) @@ -100,8 +113,12 @@ function formatPartialResponse(address: string, } } -function getAccountTx(connection: Connection, address: string, - options: TransactionsOptions, marker: string, limit: number +function getAccountTx( + connection: Connection, + address: string, + options: TransactionsOptions, + marker: string, + limit: number ) { const request = { command: 'account_tx', @@ -116,12 +133,15 @@ function getAccountTx(connection: Connection, address: string, marker: marker } - return connection.request(request).then(response => - formatPartialResponse(address, options, response)) + return connection + .request(request) + .then(response => formatPartialResponse(address, options, response)) } -function checkForLedgerGaps(connection: Connection, - options: TransactionsOptions, transactions: GetTransactionsResponse +function checkForLedgerGaps( + connection: Connection, + options: TransactionsOptions, + transactions: GetTransactionsResponse ) { let {minLedgerVersion, maxLedgerVersion} = options @@ -136,25 +156,32 @@ function checkForLedgerGaps(connection: Connection, } } - return utils.hasCompleteLedgerRange(connection, minLedgerVersion, - maxLedgerVersion).then(hasCompleteLedgerRange => { - if (!hasCompleteLedgerRange) { - throw new errors.MissingLedgerHistoryError() - } - }) + return utils + .hasCompleteLedgerRange(connection, minLedgerVersion, maxLedgerVersion) + .then(hasCompleteLedgerRange => { + if (!hasCompleteLedgerRange) { + throw new errors.MissingLedgerHistoryError() + } + }) } -function formatResponse(connection: Connection, options: TransactionsOptions, +function formatResponse( + connection: Connection, + options: TransactionsOptions, transactions: GetTransactionsResponse ) { - const compare = options.earliestFirst ? utils.compareTransactions : - _.rearg(utils.compareTransactions, 1, 0) + const compare = options.earliestFirst + ? utils.compareTransactions + : _.rearg(utils.compareTransactions, 1, 0) const sortedTransactions = transactions.sort(compare) return checkForLedgerGaps(connection, options, sortedTransactions).then( - () => sortedTransactions) + () => sortedTransactions + ) } -function getTransactionsInternal(connection: Connection, address: string, +function getTransactionsInternal( + connection: Connection, + address: string, options: TransactionsOptions ): Promise { const getter = _.partial(getAccountTx, connection, address, options) @@ -162,7 +189,10 @@ function getTransactionsInternal(connection: Connection, address: string, return utils.getRecursive(getter, options.limit).then(format) } -function getTransactions(this: RippleAPI, address: string, options: TransactionsOptions = {} +function getTransactions( + this: RippleAPI, + address: string, + options: TransactionsOptions = {} ): Promise { validate.getTransactions({address, options}) @@ -176,8 +206,9 @@ function getTransactions(this: RippleAPI, address: string, options: Transactions if (options.start) { return getTransaction.call(this, options.start).then(tx => { const ledgerVersion = tx.outcome.ledgerVersion - const bound = options.earliestFirst ? - {minLedgerVersion: ledgerVersion} : {maxLedgerVersion: ledgerVersion} + const bound = options.earliestFirst + ? {minLedgerVersion: ledgerVersion} + : {maxLedgerVersion: ledgerVersion} const startOptions = _.assign({}, defaults, options, {startTx: tx}, bound) return getTransactionsInternal(this.connection, address, startOptions) }) diff --git a/src/ledger/trustlines.ts b/src/ledger/trustlines.ts index 6146d842..3c39a42b 100644 --- a/src/ledger/trustlines.ts +++ b/src/ledger/trustlines.ts @@ -5,9 +5,9 @@ import {RippleAPI} from '..' import {FormattedTrustline} from '../common/types/objects/trustlines' export type GetTrustlinesOptions = { - counterparty?: string, - currency?: string, - limit?: number, + counterparty?: string + currency?: string + limit?: number ledgerVersion?: number } @@ -16,7 +16,9 @@ function currencyFilter(currency: string, trustline: FormattedTrustline) { } async function getTrustlines( - this: RippleAPI, address: string, options: GetTrustlinesOptions = {} + this: RippleAPI, + address: string, + options: GetTrustlinesOptions = {} ): Promise { // 1. Validate validate.getTrustlines({address, options}) diff --git a/src/ledger/utils.ts b/src/ledger/utils.ts index 430b85ee..204b2240 100644 --- a/src/ledger/utils.ts +++ b/src/ledger/utils.ts @@ -4,10 +4,10 @@ import * as common from '../common' import {Connection} from '../common' import {FormattedTransactionType} from '../transaction/types' import {Issue} from '../common/types/objects' -import {RippleAPI} from '..' +import {RippleAPI} from '..' export type RecursiveData = { - marker: string, + marker: string results: Array } @@ -18,7 +18,9 @@ function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max) } -function getXRPBalance(connection: Connection, address: string, +function getXRPBalance( + connection: Connection, + address: string, ledgerVersion?: number ): Promise { const request = { @@ -26,13 +28,16 @@ function getXRPBalance(connection: Connection, address: string, account: address, ledger_index: ledgerVersion } - return connection.request(request).then(data => - common.dropsToXrp(data.account_data.Balance)) + return connection + .request(request) + .then(data => common.dropsToXrp(data.account_data.Balance)) } // If the marker is omitted from a response, you have reached the end function getRecursiveRecur( - getter: Getter, marker: string | undefined, limit: number + getter: Getter, + marker: string | undefined, + limit: number ): Promise> { return getter(marker, limit).then(data => { const remaining = limit - data.results.length @@ -50,17 +55,20 @@ function getRecursive(getter: Getter, limit?: number): Promise> { } function renameCounterpartyToIssuer( - obj: T & {counterparty?: string, issuer?: string} - ): (T & {issuer?: string}) { - const issuer = (obj.counterparty !== undefined) ? - obj.counterparty : - ((obj.issuer !== undefined) ? obj.issuer : undefined) + obj: T & {counterparty?: string; issuer?: string} +): T & {issuer?: string} { + const issuer = + obj.counterparty !== undefined + ? obj.counterparty + : obj.issuer !== undefined + ? obj.issuer + : undefined const withIssuer = Object.assign({}, obj, {issuer}) delete withIssuer.counterparty return withIssuer } -export type RequestBookOffersArgs = {taker_gets: Issue, taker_pays: Issue} +export type RequestBookOffersArgs = {taker_gets: Issue; taker_pays: Issue} function renameCounterpartyToIssuerInOrder(order: RequestBookOffersArgs) { const taker_gets = renameCounterpartyToIssuer(order.taker_gets) @@ -70,7 +78,7 @@ function renameCounterpartyToIssuerInOrder(order: RequestBookOffersArgs) { } function signum(num) { - return (num === 0) ? 0 : (num > 0 ? 1 : -1) + return num === 0 ? 0 : num > 0 ? 1 : -1 } /** @@ -80,7 +88,8 @@ function signum(num) { * See: https://developers.ripple.com/transaction-metadata.html */ function compareTransactions( - first: FormattedTransactionType, second: FormattedTransactionType + first: FormattedTransactionType, + second: FormattedTransactionType ): number { if (!first.outcome || !second.outcome) { return 0 @@ -91,30 +100,38 @@ function compareTransactions( return first.outcome.ledgerVersion < second.outcome.ledgerVersion ? -1 : 1 } -function hasCompleteLedgerRange(connection: Connection, - minLedgerVersion?: number, maxLedgerVersion?: number +function hasCompleteLedgerRange( + connection: Connection, + minLedgerVersion?: number, + maxLedgerVersion?: number ): Promise { const firstLedgerVersion = 32570 // earlier versions have been lost return connection.hasLedgerVersions( - minLedgerVersion || firstLedgerVersion, maxLedgerVersion) + minLedgerVersion || firstLedgerVersion, + maxLedgerVersion + ) } -function isPendingLedgerVersion(connection: Connection, +function isPendingLedgerVersion( + connection: Connection, maxLedgerVersion?: number ): Promise { - return connection.getLedgerVersion().then(ledgerVersion => - ledgerVersion < (maxLedgerVersion || 0)) + return connection + .getLedgerVersion() + .then(ledgerVersion => ledgerVersion < (maxLedgerVersion || 0)) } -function ensureLedgerVersion(this: RippleAPI, options: any -): Promise { - if (Boolean(options) && options.ledgerVersion !== undefined && +function ensureLedgerVersion(this: RippleAPI, options: any): Promise { + if ( + Boolean(options) && + options.ledgerVersion !== undefined && options.ledgerVersion !== null ) { return Promise.resolve(options) } return this.getLedgerVersion().then(ledgerVersion => - _.assign({}, options, {ledgerVersion})) + _.assign({}, options, {ledgerVersion}) + ) } export { diff --git a/src/offline/derive.ts b/src/offline/derive.ts index 66e1bad7..bfd7cf69 100644 --- a/src/offline/derive.ts +++ b/src/offline/derive.ts @@ -1,13 +1,13 @@ import {deriveKeypair, deriveAddress} from 'ripple-keypairs' import {classicAddressToXAddress} from 'ripple-address-codec' -function deriveXAddress(options: {publicKey: string, tag: number | false, test: boolean}): string { +function deriveXAddress(options: { + publicKey: string + tag: number | false + test: boolean +}): string { const classicAddress = deriveAddress(options.publicKey) return classicAddressToXAddress(classicAddress, options.tag, options.test) } -export { - deriveKeypair, - deriveAddress, - deriveXAddress -} +export {deriveKeypair, deriveAddress, deriveXAddress} diff --git a/src/offline/generate-address.ts b/src/offline/generate-address.ts index af3b4866..7aef1684 100644 --- a/src/offline/generate-address.ts +++ b/src/offline/generate-address.ts @@ -3,23 +3,23 @@ import keypairs from 'ripple-keypairs' import {errors, validate} from '../common' export type GeneratedAddress = { - xAddress: string, - classicAddress?: string, - address?: string, // @deprecated Use `classicAddress` instead. + xAddress: string + classicAddress?: string + address?: string // @deprecated Use `classicAddress` instead. secret: string } export interface GenerateAddressOptions { // The entropy to use to generate the seed. - entropy?: Uint8Array | number[], + entropy?: Uint8Array | number[] // The digital signature algorithm to generate an address for. Can be `ecdsa-secp256k1` (default) or `ed25519`. - algorithm?: 'ecdsa-secp256k1' | 'ed25519', + algorithm?: 'ecdsa-secp256k1' | 'ed25519' // Specifies whether the address is intended for use on a test network such as Testnet or Devnet. // If `true`, the address should only be used for testing, and will start with `T`. // If `false` (default), the address should only be used on mainnet, and will start with `X`. - test?: boolean, + test?: boolean // If `true`, return the classic address, in addition to the X-address. includeClassicAddress?: boolean @@ -32,7 +32,11 @@ function generateAddressAPI(options: GenerateAddressOptions): GeneratedAddress { const keypair = keypairs.deriveKeypair(secret) const classicAddress = keypairs.deriveAddress(keypair.publicKey) const returnValue: any = { - xAddress: classicAddressToXAddress(classicAddress, false, options && options.test), + xAddress: classicAddressToXAddress( + classicAddress, + false, + options && options.test + ), secret } if (options.includeClassicAddress) { @@ -45,6 +49,4 @@ function generateAddressAPI(options: GenerateAddressOptions): GeneratedAddress { } } -export { - generateAddressAPI -} +export {generateAddressAPI} diff --git a/src/offline/ledgerhash.ts b/src/offline/ledgerhash.ts index addb0a8a..6bac60cb 100644 --- a/src/offline/ledgerhash.ts +++ b/src/offline/ledgerhash.ts @@ -1,5 +1,9 @@ import * as _ from 'lodash' -import {computeLedgerHash, computeTransactionTreeHash, computeStateTreeHash} from '../common/hashes' +import { + computeLedgerHash, + computeTransactionTreeHash, + computeStateTreeHash +} from '../common/hashes' import * as common from '../common' function convertLedgerHeader(header): any { @@ -25,63 +29,79 @@ function hashLedgerHeader(ledgerHeader) { return computeLedgerHash(header) } -function computeTransactionHash(ledger, - options: ComputeLedgerHeaderHashOptions) { +function computeTransactionHash( + ledger, + options: ComputeLedgerHeaderHashOptions +) { let transactions: any[] if (ledger.rawTransactions) { transactions = JSON.parse(ledger.rawTransactions) } else if (ledger.transactions) { try { transactions = ledger.transactions.map(tx => - JSON.parse(tx.rawTransaction)) + JSON.parse(tx.rawTransaction) + ) } catch (e) { - if (e.toString() === 'SyntaxError: Unexpected' + - ' token u in JSON at position 0') { + if ( + e.toString() === + 'SyntaxError: Unexpected' + ' token u in JSON at position 0' + ) { // one or more of the `tx.rawTransaction`s is undefined - throw new common.errors.ValidationError('ledger' - + ' is missing raw transactions') + throw new common.errors.ValidationError( + 'ledger' + ' is missing raw transactions' + ) } } } else { if (options.computeTreeHashes) { - throw new common.errors.ValidationError('transactions' - + ' property is missing from the ledger') + throw new common.errors.ValidationError( + 'transactions' + ' property is missing from the ledger' + ) } return ledger.transactionHash } const txs = _.map(transactions, tx => { const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {}) // rename `meta` back to `metaData` - const renameMeta = _.assign({}, _.omit(mergeTx, 'meta'), - tx.meta ? {metaData: tx.meta} : {}) + const renameMeta = _.assign( + {}, + _.omit(mergeTx, 'meta'), + tx.meta ? {metaData: tx.meta} : {} + ) return renameMeta }) const transactionHash = computeTransactionTreeHash(txs) - if (ledger.transactionHash !== undefined - && ledger.transactionHash !== transactionHash) { - throw new common.errors.ValidationError('transactionHash in header' - + ' does not match computed hash of transactions', { + if ( + ledger.transactionHash !== undefined && + ledger.transactionHash !== transactionHash + ) { + throw new common.errors.ValidationError( + 'transactionHash in header' + + ' does not match computed hash of transactions', + { transactionHashInHeader: ledger.transactionHash, computedHashOfTransactions: transactionHash - }) + } + ) } return transactionHash } -function computeStateHash(ledger, - options: ComputeLedgerHeaderHashOptions) { +function computeStateHash(ledger, options: ComputeLedgerHeaderHashOptions) { if (ledger.rawState === undefined) { if (options.computeTreeHashes) { - throw new common.errors.ValidationError('rawState' - + ' property is missing from the ledger') + throw new common.errors.ValidationError( + 'rawState' + ' property is missing from the ledger' + ) } return ledger.stateHash } const state = JSON.parse(ledger.rawState) const stateHash = computeStateTreeHash(state) if (ledger.stateHash !== undefined && ledger.stateHash !== stateHash) { - throw new common.errors.ValidationError('stateHash in header' - + ' does not match computed hash of state') + throw new common.errors.ValidationError( + 'stateHash in header' + ' does not match computed hash of state' + ) } return stateHash } @@ -90,8 +110,10 @@ export type ComputeLedgerHeaderHashOptions = { computeTreeHashes?: boolean } -function computeLedgerHeaderHash(ledger: any, - options: ComputeLedgerHeaderHashOptions = {}): string { +function computeLedgerHeaderHash( + ledger: any, + options: ComputeLedgerHeaderHashOptions = {} +): string { const subhashes = { transactionHash: computeTransactionHash(ledger, options), stateHash: computeStateHash(ledger, options) diff --git a/src/offline/sign-payment-channel-claim.ts b/src/offline/sign-payment-channel-claim.ts index 015396af..3a323a67 100644 --- a/src/offline/sign-payment-channel-claim.ts +++ b/src/offline/sign-payment-channel-claim.ts @@ -3,7 +3,9 @@ import keypairs from 'ripple-keypairs' import binary from 'ripple-binary-codec' const {validate, xrpToDrops} = common -function signPaymentChannelClaim(channel: string, amount: string, +function signPaymentChannelClaim( + channel: string, + amount: string, privateKey: string ): string { validate.signPaymentChannelClaim({channel, amount, privateKey}) diff --git a/src/offline/verify-payment-channel-claim.ts b/src/offline/verify-payment-channel-claim.ts index a34f215c..aeba50de 100644 --- a/src/offline/verify-payment-channel-claim.ts +++ b/src/offline/verify-payment-channel-claim.ts @@ -2,8 +2,11 @@ import keypairs from 'ripple-keypairs' import binary from 'ripple-binary-codec' import {validate, xrpToDrops} from '../common' -function verifyPaymentChannelClaim(channel: string, amount: string, - signature: string, publicKey: string +function verifyPaymentChannelClaim( + channel: string, + amount: string, + signature: string, + publicKey: string ): string { validate.verifyPaymentChannelClaim({channel, amount, signature, publicKey}) diff --git a/src/server/server.ts b/src/server/server.ts index 033f464d..0cfedd6a 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -30,10 +30,4 @@ function formatLedgerClose(ledgerClose: any): object { } } -export { - connect, - disconnect, - isConnected, - getLedgerVersion, - formatLedgerClose -} +export {connect, disconnect, isConnected, getLedgerVersion, formatLedgerClose} diff --git a/src/transaction/check-cancel.ts b/src/transaction/check-cancel.ts index fedd86f4..bde56a3d 100644 --- a/src/transaction/check-cancel.ts +++ b/src/transaction/check-cancel.ts @@ -7,7 +7,8 @@ export type CheckCancelParameters = { checkID: string } -function createCheckCancelTransaction(account: string, +function createCheckCancelTransaction( + account: string, cancel: CheckCancelParameters ): TransactionJSON { const txJSON = { @@ -19,15 +20,15 @@ function createCheckCancelTransaction(account: string, return txJSON } -function prepareCheckCancel(this: RippleAPI, address: string, +function prepareCheckCancel( + this: RippleAPI, + address: string, checkCancel: CheckCancelParameters, instructions: Instructions = {} ): Promise { try { - validate.prepareCheckCancel( - {address, checkCancel, instructions}) - const txJSON = createCheckCancelTransaction( - address, checkCancel) + validate.prepareCheckCancel({address, checkCancel, instructions}) + const txJSON = createCheckCancelTransaction(address, checkCancel) return prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/check-cash.ts b/src/transaction/check-cash.ts index d0fcca58..496dd314 100644 --- a/src/transaction/check-cash.ts +++ b/src/transaction/check-cash.ts @@ -7,17 +7,20 @@ import {Amount} from '../common/types/objects' import {RippleAPI} from '..' export type CheckCashParameters = { - checkID: string, - amount?: Amount, + checkID: string + amount?: Amount deliverMin?: Amount } -function createCheckCashTransaction(account: string, +function createCheckCashTransaction( + account: string, checkCash: CheckCashParameters ): TransactionJSON { if (checkCash.amount && checkCash.deliverMin) { - throw new ValidationError('"amount" and "deliverMin" properties on ' - + 'CheckCash are mutually exclusive') + throw new ValidationError( + '"amount" and "deliverMin" properties on ' + + 'CheckCash are mutually exclusive' + ) } const txJSON: any = { @@ -37,15 +40,15 @@ function createCheckCashTransaction(account: string, return txJSON } -function prepareCheckCash(this: RippleAPI, address: string, +function prepareCheckCash( + this: RippleAPI, + address: string, checkCash: CheckCashParameters, instructions: Instructions = {} ): Promise { try { - validate.prepareCheckCash( - {address, checkCash, instructions}) - const txJSON = createCheckCashTransaction( - address, checkCash) + validate.prepareCheckCash({address, checkCash, instructions}) + const txJSON = createCheckCashTransaction(address, checkCash) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/check-create.ts b/src/transaction/check-create.ts index 73245ab4..df5bf81f 100644 --- a/src/transaction/check-create.ts +++ b/src/transaction/check-create.ts @@ -6,14 +6,15 @@ import {Amount} from '../common/types/objects' import {RippleAPI} from '..' export type CheckCreateParameters = { - destination: string, - sendMax: Amount, - destinationTag?: number, - expiration?: string, + destination: string + sendMax: Amount + destinationTag?: number + expiration?: string invoiceID?: string } -function createCheckCreateTransaction(account: string, +function createCheckCreateTransaction( + account: string, check: CheckCreateParameters ): TransactionJSON { const txJSON: any = { @@ -38,15 +39,15 @@ function createCheckCreateTransaction(account: string, return txJSON } -function prepareCheckCreate(this: RippleAPI, address: string, +function prepareCheckCreate( + this: RippleAPI, + address: string, checkCreate: CheckCreateParameters, instructions: Instructions = {} ): Promise { try { - validate.prepareCheckCreate( - {address, checkCreate, instructions}) - const txJSON = createCheckCreateTransaction( - address, checkCreate) + validate.prepareCheckCreate({address, checkCreate, instructions}) + const txJSON = createCheckCreateTransaction(address, checkCreate) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/combine.ts b/src/transaction/combine.ts index c04e2167..db867b10 100644 --- a/src/transaction/combine.ts +++ b/src/transaction/combine.ts @@ -7,13 +7,14 @@ import {validate} from '../common' import {computeBinaryTransactionHash} from '../common/hashes' function addressToBigNumber(address) { - const hex = (Buffer.from(decodeAccountID(address))).toString('hex') + const hex = Buffer.from(decodeAccountID(address)).toString('hex') return new BigNumber(hex, 16) } function compareSigners(a, b) { - return addressToBigNumber(a.Signer.Account) - .comparedTo(addressToBigNumber(b.Signer.Account)) + return addressToBigNumber(a.Signer.Account).comparedTo( + addressToBigNumber(b.Signer.Account) + ) } function combine(signedTransactions: Array): object { @@ -25,10 +26,14 @@ function combine(signedTransactions: Array): object { const tx = _.omit(txs[0], 'Signers') if (!_.every(txs, _tx => _.isEqual(tx, _.omit(_tx, 'Signers')))) { throw new utils.common.errors.ValidationError( - 'txJSON is not the same for all signedTransactions') + 'txJSON is not the same for all signedTransactions' + ) } - const unsortedSigners = _.reduce(txs, (accumulator, _tx) => - accumulator.concat(_tx.Signers || []), []) + const unsortedSigners = _.reduce( + txs, + (accumulator, _tx) => accumulator.concat(_tx.Signers || []), + [] + ) const signers = unsortedSigners.sort(compareSigners) const signedTx = _.assign({}, tx, {Signers: signers}) const signedTransaction = binary.encode(signedTx) diff --git a/src/transaction/escrow-cancellation.ts b/src/transaction/escrow-cancellation.ts index 4fe4ede1..3fb709e6 100644 --- a/src/transaction/escrow-cancellation.ts +++ b/src/transaction/escrow-cancellation.ts @@ -5,15 +5,16 @@ import {Memo} from '../common/types/objects' import {RippleAPI} from '..' export type EscrowCancellation = { - owner: string, - escrowSequence: number, + owner: string + escrowSequence: number // TODO: This ripple-lib memo format should be deprecated in favor of rippled's format. // If necessary, expose a public method for converting between the two formats. memos?: Array } -function createEscrowCancellationTransaction(account: string, +function createEscrowCancellationTransaction( + account: string, payment: EscrowCancellation ): TransactionJSON { const txJSON: any = { @@ -28,14 +29,21 @@ function createEscrowCancellationTransaction(account: string, return txJSON } -function prepareEscrowCancellation(this: RippleAPI, address: string, +function prepareEscrowCancellation( + this: RippleAPI, + address: string, escrowCancellation: EscrowCancellation, instructions: Instructions = {} ): Promise { - validate.prepareEscrowCancellation( - {address, escrowCancellation, instructions}) + validate.prepareEscrowCancellation({ + address, + escrowCancellation, + instructions + }) const txJSON = createEscrowCancellationTransaction( - address, escrowCancellation) + address, + escrowCancellation + ) return utils.prepareTransaction(txJSON, this, instructions) } diff --git a/src/transaction/escrow-creation.ts b/src/transaction/escrow-creation.ts index b5d13c9c..731a6d22 100644 --- a/src/transaction/escrow-creation.ts +++ b/src/transaction/escrow-creation.ts @@ -6,17 +6,18 @@ import {Memo} from '../common/types/objects' import {RippleAPI} from '..' export type EscrowCreation = { - amount: string, - destination: string, - memos?: Array, - condition?: string, - allowCancelAfter?: string, - allowExecuteAfter?: string, - sourceTag?: number, + amount: string + destination: string + memos?: Array + condition?: string + allowCancelAfter?: string + allowExecuteAfter?: string + sourceTag?: number destinationTag?: number } -function createEscrowCreationTransaction(account: string, +function createEscrowCreationTransaction( + account: string, payment: EscrowCreation ): TransactionJSON { const txJSON: any = { @@ -44,23 +45,28 @@ function createEscrowCreationTransaction(account: string, if (payment.memos !== undefined) { txJSON.Memos = payment.memos.map(utils.convertMemo) } - if (Boolean(payment.allowCancelAfter) && Boolean(payment.allowExecuteAfter) && - txJSON.CancelAfter <= txJSON.FinishAfter) { - throw new ValidationError('prepareEscrowCreation: ' + - '"allowCancelAfter" must be after "allowExecuteAfter"') + if ( + Boolean(payment.allowCancelAfter) && + Boolean(payment.allowExecuteAfter) && + txJSON.CancelAfter <= txJSON.FinishAfter + ) { + throw new ValidationError( + 'prepareEscrowCreation: ' + + '"allowCancelAfter" must be after "allowExecuteAfter"' + ) } return txJSON } -function prepareEscrowCreation(this: RippleAPI, address: string, +function prepareEscrowCreation( + this: RippleAPI, + address: string, escrowCreation: EscrowCreation, instructions: Instructions = {} ): Promise { try { - validate.prepareEscrowCreation( - {address, escrowCreation, instructions}) - const txJSON = createEscrowCreationTransaction( - address, escrowCreation) + validate.prepareEscrowCreation({address, escrowCreation, instructions}) + const txJSON = createEscrowCreationTransaction(address, escrowCreation) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/escrow-execution.ts b/src/transaction/escrow-execution.ts index 0db0f3bd..cb6f6e1a 100644 --- a/src/transaction/escrow-execution.ts +++ b/src/transaction/escrow-execution.ts @@ -6,14 +6,15 @@ import {Memo} from '../common/types/objects' import {RippleAPI} from '..' export type EscrowExecution = { - owner: string, - escrowSequence: number, - memos?: Array, - condition?: string, + owner: string + escrowSequence: number + memos?: Array + condition?: string fulfillment?: string } -function createEscrowExecutionTransaction(account: string, +function createEscrowExecutionTransaction( + account: string, payment: EscrowExecution ): TransactionJSON { const txJSON: any = { @@ -24,8 +25,10 @@ function createEscrowExecutionTransaction(account: string, } if (Boolean(payment.condition) !== Boolean(payment.fulfillment)) { - throw new ValidationError('"condition" and "fulfillment" fields on' - + ' EscrowFinish must only be specified together.') + throw new ValidationError( + '"condition" and "fulfillment" fields on' + + ' EscrowFinish must only be specified together.' + ) } if (payment.condition !== undefined) { @@ -40,15 +43,15 @@ function createEscrowExecutionTransaction(account: string, return txJSON } -function prepareEscrowExecution(this: RippleAPI, address: string, +function prepareEscrowExecution( + this: RippleAPI, + address: string, escrowExecution: EscrowExecution, instructions: Instructions = {} ): Promise { try { - validate.prepareEscrowExecution( - {address, escrowExecution, instructions}) - const txJSON = createEscrowExecutionTransaction( - address, escrowExecution) + validate.prepareEscrowExecution({address, escrowExecution, instructions}) + const txJSON = createEscrowExecutionTransaction(address, escrowExecution) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/order.ts b/src/transaction/order.ts index d0612570..f4463bad 100644 --- a/src/transaction/order.ts +++ b/src/transaction/order.ts @@ -6,12 +6,15 @@ import {FormattedOrderSpecification} from '../common/types/objects/index' import {RippleAPI} from '..' function createOrderTransaction( - account: string, order: FormattedOrderSpecification + account: string, + order: FormattedOrderSpecification ): OfferCreateTransaction { - const takerPays = utils.common.toRippledAmount(order.direction === 'buy' ? - order.quantity : order.totalPrice) - const takerGets = utils.common.toRippledAmount(order.direction === 'buy' ? - order.totalPrice : order.quantity) + const takerPays = utils.common.toRippledAmount( + order.direction === 'buy' ? order.quantity : order.totalPrice + ) + const takerGets = utils.common.toRippledAmount( + order.direction === 'buy' ? order.totalPrice : order.quantity + ) const txJSON: Partial = { TransactionType: 'OfferCreate', @@ -44,7 +47,10 @@ function createOrderTransaction( return txJSON as OfferCreateTransaction } -function prepareOrder(this: RippleAPI, address: string, order: FormattedOrderSpecification, +function prepareOrder( + this: RippleAPI, + address: string, + order: FormattedOrderSpecification, instructions: Instructions = {} ): Promise { try { diff --git a/src/transaction/ordercancellation.ts b/src/transaction/ordercancellation.ts index 1517a7a6..c7d8bdbd 100644 --- a/src/transaction/ordercancellation.ts +++ b/src/transaction/ordercancellation.ts @@ -3,7 +3,8 @@ const validate = utils.common.validate import {Instructions, Prepare, TransactionJSON} from './types' import {RippleAPI} from '..' -function createOrderCancellationTransaction(account: string, +function createOrderCancellationTransaction( + account: string, orderCancellation: any ): TransactionJSON { const txJSON: any = { @@ -17,12 +18,22 @@ function createOrderCancellationTransaction(account: string, return txJSON } -function prepareOrderCancellation(this: RippleAPI, address: string, orderCancellation: object, +function prepareOrderCancellation( + this: RippleAPI, + address: string, + orderCancellation: object, instructions: Instructions = {} ): Promise { try { - validate.prepareOrderCancellation({address, orderCancellation, instructions}) - const txJSON = createOrderCancellationTransaction(address, orderCancellation) + validate.prepareOrderCancellation({ + address, + orderCancellation, + instructions + }) + const txJSON = createOrderCancellationTransaction( + address, + orderCancellation + ) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/payment-channel-claim.ts b/src/transaction/payment-channel-claim.ts index e19978ff..67461589 100644 --- a/src/transaction/payment-channel-claim.ts +++ b/src/transaction/payment-channel-claim.ts @@ -6,16 +6,17 @@ import {Instructions, Prepare, TransactionJSON} from './types' import {RippleAPI} from '..' export type PaymentChannelClaim = { - channel: string, - balance?: string, - amount?: string, - signature?: string, - publicKey?: string, - renew?: boolean, + channel: string + balance?: string + amount?: string + signature?: string + publicKey?: string + renew?: boolean close?: boolean } -function createPaymentChannelClaimTransaction(account: string, +function createPaymentChannelClaimTransaction( + account: string, claim: PaymentChannelClaim ): TransactionJSON { const txJSON: TransactionJSON = { @@ -33,8 +34,10 @@ function createPaymentChannelClaimTransaction(account: string, } if (Boolean(claim.signature) !== Boolean(claim.publicKey)) { - throw new ValidationError('"signature" and "publicKey" fields on' - + ' PaymentChannelClaim must only be specified together.') + throw new ValidationError( + '"signature" and "publicKey" fields on' + + ' PaymentChannelClaim must only be specified together.' + ) } if (claim.signature !== undefined) { @@ -45,8 +48,10 @@ function createPaymentChannelClaimTransaction(account: string, } if (claim.renew === true && claim.close === true) { - throw new ValidationError('"renew" and "close" flags on PaymentChannelClaim' - + ' are mutually exclusive') + throw new ValidationError( + '"renew" and "close" flags on PaymentChannelClaim' + + ' are mutually exclusive' + ) } if (claim.renew === true) { @@ -59,15 +64,22 @@ function createPaymentChannelClaimTransaction(account: string, return txJSON } -function preparePaymentChannelClaim(this: RippleAPI, address: string, +function preparePaymentChannelClaim( + this: RippleAPI, + address: string, paymentChannelClaim: PaymentChannelClaim, instructions: Instructions = {} ): Promise { try { - validate.preparePaymentChannelClaim( - {address, paymentChannelClaim, instructions}) + validate.preparePaymentChannelClaim({ + address, + paymentChannelClaim, + instructions + }) const txJSON = createPaymentChannelClaimTransaction( - address, paymentChannelClaim) + address, + paymentChannelClaim + ) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/payment-channel-create.ts b/src/transaction/payment-channel-create.ts index ae48f37e..a80acf5c 100644 --- a/src/transaction/payment-channel-create.ts +++ b/src/transaction/payment-channel-create.ts @@ -4,16 +4,17 @@ import {Instructions, Prepare, TransactionJSON} from './types' import {RippleAPI} from '..' export type PaymentChannelCreate = { - amount: string, - destination: string, - settleDelay: number, - publicKey: string, - cancelAfter?: string, - sourceTag?: number, + amount: string + destination: string + settleDelay: number + publicKey: string + cancelAfter?: string + sourceTag?: number destinationTag?: number } -function createPaymentChannelCreateTransaction(account: string, +function createPaymentChannelCreateTransaction( + account: string, paymentChannel: PaymentChannelCreate ): TransactionJSON { const txJSON: any = { @@ -38,15 +39,22 @@ function createPaymentChannelCreateTransaction(account: string, return txJSON } -function preparePaymentChannelCreate(this: RippleAPI, address: string, +function preparePaymentChannelCreate( + this: RippleAPI, + address: string, paymentChannelCreate: PaymentChannelCreate, instructions: Instructions = {} ): Promise { try { - validate.preparePaymentChannelCreate( - {address, paymentChannelCreate, instructions}) + validate.preparePaymentChannelCreate({ + address, + paymentChannelCreate, + instructions + }) const txJSON = createPaymentChannelCreateTransaction( - address, paymentChannelCreate) + address, + paymentChannelCreate + ) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/payment-channel-fund.ts b/src/transaction/payment-channel-fund.ts index 717b152c..1f47aabc 100644 --- a/src/transaction/payment-channel-fund.ts +++ b/src/transaction/payment-channel-fund.ts @@ -4,12 +4,13 @@ import {Instructions, Prepare, TransactionJSON} from './types' import {RippleAPI} from '..' export type PaymentChannelFund = { - channel: string, - amount: string, + channel: string + amount: string expiration?: string } -function createPaymentChannelFundTransaction(account: string, +function createPaymentChannelFundTransaction( + account: string, fund: PaymentChannelFund ): TransactionJSON { const txJSON: TransactionJSON = { @@ -26,15 +27,22 @@ function createPaymentChannelFundTransaction(account: string, return txJSON } -function preparePaymentChannelFund(this: RippleAPI, address: string, +function preparePaymentChannelFund( + this: RippleAPI, + address: string, paymentChannelFund: PaymentChannelFund, instructions: Instructions = {} ): Promise { try { - validate.preparePaymentChannelFund( - {address, paymentChannelFund, instructions}) + validate.preparePaymentChannelFund({ + address, + paymentChannelFund, + instructions + }) const txJSON = createPaymentChannelFundTransaction( - address, paymentChannelFund) + address, + paymentChannelFund + ) return utils.prepareTransaction(txJSON, this, instructions) } catch (e) { return Promise.reject(e) diff --git a/src/transaction/payment.ts b/src/transaction/payment.ts index 1e7e9036..617e18b0 100644 --- a/src/transaction/payment.ts +++ b/src/transaction/payment.ts @@ -5,57 +5,71 @@ const toRippledAmount = utils.common.toRippledAmount const paymentFlags = utils.common.txFlags.Payment const ValidationError = utils.common.errors.ValidationError import {Instructions, Prepare, TransactionJSON} from './types' -import {Amount, Adjustment, MaxAdjustment, - MinAdjustment, Memo} from '../common/types/objects' +import { + Amount, + Adjustment, + MaxAdjustment, + MinAdjustment, + Memo +} from '../common/types/objects' import {xrpToDrops} from '../common' import {RippleAPI} from '..' import {getClassicAccountAndTag, ClassicAccountAndTag} from './utils' - export interface Payment { - source: Adjustment | MaxAdjustment, - destination: Adjustment | MinAdjustment, - paths?: string, - memos?: Array, + source: Adjustment | MaxAdjustment + destination: Adjustment | MinAdjustment + paths?: string + memos?: Array // A 256-bit hash that can be used to identify a particular payment - invoiceID?: string, + invoiceID?: string // A boolean that, if set to true, indicates that this payment should go // through even if the whole amount cannot be delivered because of a lack of // liquidity or funds in the source_account account - allowPartialPayment?: boolean, + allowPartialPayment?: boolean // A boolean that can be set to true if paths are specified and the sender // would like the Ripple Network to disregard any direct paths from // the source_account to the destination_account. This may be used to take // advantage of an arbitrage opportunity or by gateways wishing to issue // balances from a hot wallet to a user who has mistakenly set a trustline // directly to the hot wallet - noDirectRipple?: boolean, + noDirectRipple?: boolean limitQuality?: boolean } function isMaxAdjustment( - source: Adjustment | MaxAdjustment): source is MaxAdjustment { - return (source as MaxAdjustment).maxAmount !== undefined + source: Adjustment | MaxAdjustment +): source is MaxAdjustment { + return (source as MaxAdjustment).maxAmount !== undefined } function isMinAdjustment( - destination: Adjustment | MinAdjustment): destination is MinAdjustment { - return (destination as MinAdjustment).minAmount !== undefined + destination: Adjustment | MinAdjustment +): destination is MinAdjustment { + return (destination as MinAdjustment).minAmount !== undefined } function isXRPToXRPPayment(payment: Payment): boolean { const {source, destination} = payment const sourceCurrency = isMaxAdjustment(source) - ? source.maxAmount.currency : source.amount.currency + ? source.maxAmount.currency + : source.amount.currency const destinationCurrency = isMinAdjustment(destination) - ? destination.minAmount.currency : destination.amount.currency - return (sourceCurrency === 'XRP' || sourceCurrency === 'drops') && - (destinationCurrency === 'XRP' || destinationCurrency === 'drops') + ? destination.minAmount.currency + : destination.amount.currency + return ( + (sourceCurrency === 'XRP' || sourceCurrency === 'drops') && + (destinationCurrency === 'XRP' || destinationCurrency === 'drops') + ) } function isIOUWithoutCounterparty(amount: Amount): boolean { - return amount && amount.currency !== 'XRP' && amount.currency !== 'drops' - && amount.counterparty === undefined + return ( + amount && + amount.currency !== 'XRP' && + amount.currency !== 'drops' && + amount.counterparty === undefined + ) } function applyAnyCounterpartyEncoding(payment: Payment): void { @@ -101,46 +115,66 @@ function createMaximalAmount(amount: Amount): Amount { * @returns {ClassicAccountAndTag} * The classic account and tag. */ -function validateAndNormalizeAddress(address: string, expectedTag: number | undefined): ClassicAccountAndTag { +function validateAndNormalizeAddress( + address: string, + expectedTag: number | undefined +): ClassicAccountAndTag { const classicAddress = getClassicAccountAndTag(address, expectedTag) - classicAddress.tag = classicAddress.tag === false ? undefined : classicAddress.tag + classicAddress.tag = + classicAddress.tag === false ? undefined : classicAddress.tag return classicAddress } -function createPaymentTransaction(address: string, paymentArgument: Payment +function createPaymentTransaction( + address: string, + paymentArgument: Payment ): TransactionJSON { const payment = _.cloneDeep(paymentArgument) applyAnyCounterpartyEncoding(payment) - const sourceAddressAndTag = validateAndNormalizeAddress(payment.source.address, payment.source.tag) + const sourceAddressAndTag = validateAndNormalizeAddress( + payment.source.address, + payment.source.tag + ) const addressToVerifyAgainst = validateAndNormalizeAddress(address, undefined) - if (addressToVerifyAgainst.classicAccount !== sourceAddressAndTag.classicAccount) { + if ( + addressToVerifyAgainst.classicAccount !== sourceAddressAndTag.classicAccount + ) { throw new ValidationError('address must match payment.source.address') } - if (addressToVerifyAgainst.tag !== undefined && - sourceAddressAndTag.tag !== undefined && - addressToVerifyAgainst.tag !== sourceAddressAndTag.tag) { + if ( + addressToVerifyAgainst.tag !== undefined && + sourceAddressAndTag.tag !== undefined && + addressToVerifyAgainst.tag !== sourceAddressAndTag.tag + ) { throw new ValidationError( - 'address includes a tag that does not match payment.source.tag') + 'address includes a tag that does not match payment.source.tag' + ) } - const destinationAddressAndTag = validateAndNormalizeAddress(payment.destination.address, payment.destination.tag) + const destinationAddressAndTag = validateAndNormalizeAddress( + payment.destination.address, + payment.destination.tag + ) if ( - (isMaxAdjustment(payment.source) && isMinAdjustment(payment.destination)) - || + (isMaxAdjustment(payment.source) && isMinAdjustment(payment.destination)) || (!isMaxAdjustment(payment.source) && !isMinAdjustment(payment.destination)) ) { - throw new ValidationError('payment must specify either (source.maxAmount ' - + 'and destination.amount) or (source.amount and destination.minAmount)') + throw new ValidationError( + 'payment must specify either (source.maxAmount ' + + 'and destination.amount) or (source.amount and destination.minAmount)' + ) } const destinationAmount = isMinAdjustment(payment.destination) - ? payment.destination.minAmount : payment.destination.amount + ? payment.destination.minAmount + : payment.destination.amount const sourceAmount = isMaxAdjustment(payment.source) - ? payment.source.maxAmount : payment.source.amount + ? payment.source.maxAmount + : payment.source.amount // when using destination.minAmount, rippled still requires that we set // a destination amount in addition to DeliverMin. the destination amount @@ -149,8 +183,9 @@ function createPaymentTransaction(address: string, paymentArgument: Payment // maximum possible amount. otherwise it's possible that the destination // cap could be hit before the source cap. const amount = - (isMinAdjustment(payment.destination) && !isXRPToXRPPayment(payment)) - ? createMaximalAmount(destinationAmount) : destinationAmount + isMinAdjustment(payment.destination) && !isXRPToXRPPayment(payment) + ? createMaximalAmount(destinationAmount) + : destinationAmount const txJSON: any = { TransactionType: 'Payment', @@ -203,7 +238,10 @@ function createPaymentTransaction(address: string, paymentArgument: Payment return txJSON } -function preparePayment(this: RippleAPI, address: string, payment: Payment, +function preparePayment( + this: RippleAPI, + address: string, + payment: Payment, instructions: Instructions = {} ): Promise { try { diff --git a/src/transaction/settings.ts b/src/transaction/settings.ts index c82d9155..c5e7f795 100644 --- a/src/transaction/settings.ts +++ b/src/transaction/settings.ts @@ -4,13 +4,24 @@ import * as utils from './utils' const validate = utils.common.validate const AccountFlagIndices = utils.common.constants.AccountFlagIndices const AccountFields = utils.common.constants.AccountFields -import {Instructions, Prepare, SettingsTransaction, TransactionJSON} from './types' +import { + Instructions, + Prepare, + SettingsTransaction, + TransactionJSON +} from './types' import {FormattedSettings, WeightedSigner} from '../common/types/objects' import {RippleAPI} from '..' -function setTransactionFlags(txJSON: TransactionJSON, values: FormattedSettings) { +function setTransactionFlags( + txJSON: TransactionJSON, + values: FormattedSettings +) { const keys = Object.keys(values) - assert.ok(keys.length === 1, 'ERROR: can only set one setting per transaction') + assert.ok( + keys.length === 1, + 'ERROR: can only set one setting per transaction' + ) const flagName = keys[0] const value = values[flagName] const index = AccountFlagIndices[flagName] @@ -24,7 +35,10 @@ function setTransactionFlags(txJSON: TransactionJSON, values: FormattedSettings) } // Sets `null` fields to their `default`. -function setTransactionFields(txJSON: TransactionJSON, input: FormattedSettings) { +function setTransactionFields( + txJSON: TransactionJSON, + input: FormattedSettings +) { const fieldSchema = AccountFields for (const fieldName in fieldSchema) { const field = fieldSchema[fieldName] @@ -41,7 +55,9 @@ function setTransactionFields(txJSON: TransactionJSON, input: FormattedSettings) 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 @@ -62,7 +78,7 @@ function setTransactionFields(txJSON: TransactionJSON, input: FormattedSettings) */ function convertTransferRate(transferRate: number): number { - return (new BigNumber(transferRate)).shiftedBy(9).toNumber() + return new BigNumber(transferRate).shiftedBy(9).toNumber() } function formatSignerEntry(signer: WeightedSigner): object { @@ -75,7 +91,8 @@ function formatSignerEntry(signer: WeightedSigner): object { } function createSettingsTransactionWithoutMemos( - account: string, settings: FormattedSettings + account: string, + settings: FormattedSettings ): SettingsTransaction { if (settings.regularKey !== undefined) { const removeRegularKey = { @@ -85,7 +102,9 @@ function createSettingsTransactionWithoutMemos( if (settings.regularKey === null) { return removeRegularKey } - return Object.assign({}, removeRegularKey, {RegularKey: settings.regularKey}) + return Object.assign({}, removeRegularKey, { + RegularKey: settings.regularKey + }) } if (settings.signers !== undefined) { @@ -94,12 +113,14 @@ function createSettingsTransactionWithoutMemos( Account: account, SignerEntries: [], SignerQuorum: settings.signers.threshold - }; + } if (settings.signers.weights !== undefined) { - setSignerList.SignerEntries = settings.signers.weights.map(formatSignerEntry); + setSignerList.SignerEntries = settings.signers.weights.map( + formatSignerEntry + ) } - return setSignerList; + return setSignerList } const txJSON: SettingsTransaction = { @@ -118,7 +139,9 @@ function createSettingsTransactionWithoutMemos( return txJSON } -function createSettingsTransaction(account: string, settings: FormattedSettings +function createSettingsTransaction( + account: string, + settings: FormattedSettings ): SettingsTransaction { const txJSON = createSettingsTransactionWithoutMemos(account, settings) if (settings.memos !== undefined) { @@ -127,7 +150,10 @@ function createSettingsTransaction(account: string, settings: FormattedSettings return txJSON } -function prepareSettings(this: RippleAPI, address: string, settings: FormattedSettings, +function prepareSettings( + this: RippleAPI, + address: string, + settings: FormattedSettings, instructions: Instructions = {} ): Promise { try { diff --git a/src/transaction/sign.ts b/src/transaction/sign.ts index 6a1ffce2..1ce5c7e5 100644 --- a/src/transaction/sign.ts +++ b/src/transaction/sign.ts @@ -7,7 +7,7 @@ import {SignOptions, KeyPair, TransactionJSON} from './types' import {BigNumber} from 'bignumber.js' import {xrpToDrops} from '../common' import {RippleAPI} from '..' -const validate = utils.common.validate +const validate = utils.common.validate function computeSignature(tx: object, privateKey: string, signAs?: string) { const signingData = signAs @@ -23,7 +23,7 @@ function signWithKeypair( options: SignOptions = { signAs: '' } -): { signedTransaction: string; id: string } { +): {signedTransaction: string; id: string} { validate.sign({txJSON, keypair}) const tx = JSON.parse(txJSON) @@ -43,11 +43,18 @@ function signWithKeypair( const signer = { Account: options.signAs, SigningPubKey: keypair.publicKey, - TxnSignature: computeSignature(txToSignAndEncode, keypair.privateKey, options.signAs) + TxnSignature: computeSignature( + txToSignAndEncode, + keypair.privateKey, + options.signAs + ) } txToSignAndEncode.Signers = [{Signer: signer}] } else { - txToSignAndEncode.TxnSignature = computeSignature(txToSignAndEncode, keypair.privateKey) + txToSignAndEncode.TxnSignature = computeSignature( + txToSignAndEncode, + keypair.privateKey + ) } const serialized = binaryCodec.encode(txToSignAndEncode) @@ -72,7 +79,7 @@ function objectDiff(a: object, b: object): object { const diffs = {} // Compare two items and push non-matches to object - const compare = function (i1: any, i2: any, k: string): void { + const compare = function(i1: any, i2: any, k: string): void { const type1 = Object.prototype.toString.call(i1) const type2 = Object.prototype.toString.call(i2) if (type2 === '[object Undefined]') { @@ -186,7 +193,7 @@ function checkFee(api: RippleAPI, txFee: string): void { if (fee.isGreaterThan(maxFeeDrops)) { throw new utils.common.errors.ValidationError( `"Fee" should not exceed "${maxFeeDrops}". ` + - 'To use a higher fee, set `maxFeeXRP` in the RippleAPI constructor.' + 'To use a higher fee, set `maxFeeXRP` in the RippleAPI constructor.' ) } } @@ -197,7 +204,7 @@ function sign( secret?: any, options?: SignOptions, keypair?: KeyPair -): { signedTransaction: string; id: string } { +): {signedTransaction: string; id: string} { if (typeof secret === 'string') { // we can't validate that the secret matches the account because // the secret could correspond to the regular key @@ -215,11 +222,7 @@ function sign( 'sign: Missing secret or keypair.' ) } - return signWithKeypair( - this, - txJSON, - keypair ? keypair : secret, - options) + return signWithKeypair(this, txJSON, keypair ? keypair : secret, options) } } diff --git a/src/transaction/submit.ts b/src/transaction/submit.ts index 1e39850a..8672fa9a 100644 --- a/src/transaction/submit.ts +++ b/src/transaction/submit.ts @@ -4,7 +4,7 @@ import {validate} from '../common' import {RippleAPI} from '..' export interface FormattedSubmitResponse { - resultCode: string, + resultCode: string resultMessage: string } @@ -37,7 +37,8 @@ function formatSubmitResponse(response): FormattedSubmitResponse { } async function submit( - this: RippleAPI, signedTransaction: string + this: RippleAPI, + signedTransaction: string ): Promise { // 1. Validate validate.submit({signedTransaction}) diff --git a/src/transaction/trustline.ts b/src/transaction/trustline.ts index 114d111c..3e27be5a 100644 --- a/src/transaction/trustline.ts +++ b/src/transaction/trustline.ts @@ -3,16 +3,18 @@ import * as utils from './utils' const validate = utils.common.validate const trustlineFlags = utils.common.txFlags.TrustSet import {Instructions, Prepare, TransactionJSON} from './types' -import { - FormattedTrustlineSpecification -} from '../common/types/objects/trustlines' +import {FormattedTrustlineSpecification} from '../common/types/objects/trustlines' import {RippleAPI} from '..' function convertQuality(quality) { - return (new BigNumber(quality)).shiftedBy(9).integerValue(BigNumber.ROUND_DOWN).toNumber() + return new BigNumber(quality) + .shiftedBy(9) + .integerValue(BigNumber.ROUND_DOWN) + .toNumber() } -function createTrustlineTransaction(account: string, +function createTrustlineTransaction( + account: string, trustline: FormattedTrustlineSpecification ): TransactionJSON { const limit = { @@ -37,12 +39,14 @@ function createTrustlineTransaction(account: string, txJSON.Flags |= trustlineFlags.SetAuth } if (trustline.ripplingDisabled !== undefined) { - txJSON.Flags |= trustline.ripplingDisabled ? - trustlineFlags.NoRipple : trustlineFlags.ClearNoRipple + txJSON.Flags |= trustline.ripplingDisabled + ? trustlineFlags.NoRipple + : trustlineFlags.ClearNoRipple } if (trustline.frozen !== undefined) { - txJSON.Flags |= trustline.frozen ? - trustlineFlags.SetFreeze : trustlineFlags.ClearFreeze + txJSON.Flags |= trustline.frozen + ? trustlineFlags.SetFreeze + : trustlineFlags.ClearFreeze } if (trustline.memos !== undefined) { txJSON.Memos = trustline.memos.map(utils.convertMemo) @@ -50,8 +54,11 @@ function createTrustlineTransaction(account: string, return txJSON } -function prepareTrustline(this: RippleAPI, address: string, - trustline: FormattedTrustlineSpecification, instructions: Instructions = {} +function prepareTrustline( + this: RippleAPI, + address: string, + trustline: FormattedTrustlineSpecification, + instructions: Instructions = {} ): Promise { try { validate.prepareTrustline({address, trustline, instructions}) diff --git a/src/transaction/types.ts b/src/transaction/types.ts index 6b5bcbb4..565e1268 100644 --- a/src/transaction/types.ts +++ b/src/transaction/types.ts @@ -1,4 +1,3 @@ - import { FormattedOrderSpecification, FormattedTrustline, @@ -7,58 +6,56 @@ import { Memo, FormattedSettings } from '../common/types/objects' -import { - ApiMemo, -} from './utils' +import {ApiMemo} from './utils' export type TransactionJSON = { - Account: string, - TransactionType: string, - Memos?: {Memo: ApiMemo}[], - Flags?: number, - Fulfillment?: string, + Account: string + TransactionType: string + Memos?: {Memo: ApiMemo}[] + Flags?: number + Fulfillment?: string [Field: string]: string | number | Array | RippledAmount | undefined } export type Instructions = { - sequence?: number, - fee?: string, + sequence?: number + fee?: string // @deprecated - maxFee?: string, - maxLedgerVersion?: number, - maxLedgerVersionOffset?: number, + maxFee?: string + maxLedgerVersion?: number + maxLedgerVersionOffset?: number signersCount?: number } export type Prepare = { - txJSON: string, + txJSON: string instructions: { - fee: string, - sequence: number, + fee: string + sequence: number maxLedgerVersion?: number } } export type Submit = { - success: boolean, - engineResult: string, - engineResultCode: number, - engineResultMessage?: string, - txBlob?: string, + success: boolean + engineResult: string + engineResultCode: number + engineResultMessage?: string + txBlob?: string txJson?: object } export interface OfferCreateTransaction extends TransactionJSON { - TransactionType: 'OfferCreate', - Account: string, - Fee: string, - Flags: number, - LastLedgerSequence: number, - Sequence: number, - TakerGets: RippledAmount, - TakerPays: RippledAmount, - Expiration?: number, - OfferSequence?: number, + TransactionType: 'OfferCreate' + Account: string + Fee: string + Flags: number + LastLedgerSequence: number + Sequence: number + TakerGets: RippledAmount + TakerPays: RippledAmount + Expiration?: number + OfferSequence?: number Memos?: {Memo: ApiMemo}[] } @@ -67,7 +64,7 @@ export interface SettingsTransaction extends TransactionJSON { } export type KeyPair = { - publicKey: string, + publicKey: string privateKey: string } @@ -76,23 +73,23 @@ export type SignOptions = { } export type Outcome = { - result: string, - ledgerVersion: number, - indexInLedger: number, - fee: string, + result: string + ledgerVersion: number + indexInLedger: number + fee: string balanceChanges: { [key: string]: { - currency: string, - counterparty?: string, - value: string + currency: string + counterparty?: string + value: string }[] - }, - orderbookChanges: object, + } + orderbookChanges: object deliveredAmount?: { - currency: string, - counterparty?: string, + currency: string + counterparty?: string value: string - }, + } timestamp?: string } @@ -101,64 +98,64 @@ export type FormattedOrderCancellation = { } export type FormattedPayment = { - source: Adjustment, - destination: Adjustment, - paths?: string, - memos?: Array, - invoiceID?: string, - allowPartialPayment?: boolean, - noDirectRipple?: boolean, + source: Adjustment + destination: Adjustment + paths?: string + memos?: Array + invoiceID?: string + allowPartialPayment?: boolean + noDirectRipple?: boolean limitQuality?: boolean } export type FormattedPaymentTransaction = { - type: string, - specification: FormattedPayment, - outcome: Outcome, - id: string, - address: string, + type: string + specification: FormattedPayment + outcome: Outcome + id: string + address: string sequence: number } export type FormattedOrderTransaction = { - type: string, - specification: FormattedOrderSpecification, - outcome: Outcome, - id: string, - address: string, + type: string + specification: FormattedOrderSpecification + outcome: Outcome + id: string + address: string sequence: number } export type FormattedOrderCancellationTransaction = { - type: string, - specification: FormattedOrderCancellation, - outcome: Outcome, - id: string, - address: string, + type: string + specification: FormattedOrderCancellation + outcome: Outcome + id: string + address: string sequence: number } export type FormattedTrustlineTransaction = { - type: string, - specification: FormattedTrustline, - outcome: Outcome, - id: string, - address: string, + type: string + specification: FormattedTrustline + outcome: Outcome + id: string + address: string sequence: number } export type FormattedSettingsTransaction = { - type: string, - specification: FormattedSettings, - outcome: Outcome, - id: string, - address: string, + type: string + specification: FormattedSettings + outcome: Outcome + id: string + address: string sequence: number } export type FormattedTransactionType = - FormattedPaymentTransaction | - FormattedOrderTransaction | - FormattedOrderCancellationTransaction | - FormattedTrustlineTransaction | - FormattedSettingsTransaction + | FormattedPaymentTransaction + | FormattedOrderTransaction + | FormattedOrderCancellationTransaction + | FormattedTrustlineTransaction + | FormattedSettingsTransaction diff --git a/src/transaction/utils.ts b/src/transaction/utils.ts index 07ea900b..ebee8ad8 100644 --- a/src/transaction/utils.ts +++ b/src/transaction/utils.ts @@ -7,11 +7,16 @@ import {ValidationError} from '../common/errors' import {xAddressToClassicAddress, isValidXAddress} from 'ripple-address-codec' const txFlags = common.txFlags -const TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD = ['Payment', 'CheckCreate', 'EscrowCreate', 'PaymentChannelCreate'] +const TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD = [ + 'Payment', + 'CheckCreate', + 'EscrowCreate', + 'PaymentChannelCreate' +] export type ApiMemo = { - MemoData?: string, - MemoType?: string, + MemoData?: string + MemoType?: string MemoFormat?: string } @@ -19,8 +24,8 @@ function formatPrepareResponse(txJSON: any): Prepare { const instructions = { fee: common.dropsToXrp(txJSON.Fee), sequence: txJSON.Sequence, - maxLedgerVersion: txJSON.LastLedgerSequence === undefined ? - null : txJSON.LastLedgerSequence + maxLedgerVersion: + txJSON.LastLedgerSequence === undefined ? null : txJSON.LastLedgerSequence } return { txJSON: JSON.stringify(txJSON), @@ -47,7 +52,10 @@ 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() } /** @@ -58,7 +66,7 @@ function scaleValue(value, multiplier, extra = 0) { * `undefined` if the input could not specify whether a tag should be used. */ export interface ClassicAccountAndTag { - classicAccount: string, + classicAccount: string tag: number | false | undefined } @@ -75,11 +83,16 @@ export interface ClassicAccountAndTag { * @returns {ClassicAccountAndTag} * The classic account and tag. */ -function getClassicAccountAndTag(Account: string, expectedTag?: number): ClassicAccountAndTag { +function getClassicAccountAndTag( + Account: string, + expectedTag?: number +): ClassicAccountAndTag { if (isValidXAddress(Account)) { const classic = xAddressToClassicAddress(Account) if (expectedTag !== undefined && classic.tag !== expectedTag) { - throw new ValidationError('address includes a tag that does not match the tag specified in the transaction') + throw new ValidationError( + 'address includes a tag that does not match the tag specified in the transaction' + ) } return { classicAccount: classic.classicAddress, @@ -93,16 +106,28 @@ function getClassicAccountAndTag(Account: string, expectedTag?: number): Classic } } -function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, +function prepareTransaction( + txJSON: TransactionJSON, + api: RippleAPI, instructions: Instructions ): Promise { common.validate.instructions(instructions) common.validate.tx_json(txJSON) - const disallowedFieldsInTxJSON = ['maxLedgerVersion', 'maxLedgerVersionOffset', 'fee', 'sequence'] + const disallowedFieldsInTxJSON = [ + 'maxLedgerVersion', + 'maxLedgerVersionOffset', + 'fee', + 'sequence' + ] const badFields = disallowedFieldsInTxJSON.filter(field => txJSON[field]) if (badFields.length) { - return Promise.reject(new ValidationError('txJSON additionalProperty "' + badFields[0] + - '" exists in instance when not allowed')) + return Promise.reject( + new ValidationError( + 'txJSON additionalProperty "' + + badFields[0] + + '" exists in instance when not allowed' + ) + ) } const newTxJSON = Object.assign({}, txJSON) @@ -113,12 +138,17 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, } // Sender: - const {classicAccount, tag: sourceTag} = getClassicAccountAndTag(txJSON.Account) + const {classicAccount, tag: sourceTag} = getClassicAccountAndTag( + txJSON.Account + ) newTxJSON.Account = classicAccount if (sourceTag !== undefined) { if (txJSON.SourceTag && txJSON.SourceTag !== sourceTag) { - return Promise.reject(new ValidationError( - 'The `SourceTag`, if present, must match the tag of the `Account` X-address')) + return Promise.reject( + new ValidationError( + 'The `SourceTag`, if present, must match the tag of the `Account` X-address' + ) + ) } if (sourceTag) { newTxJSON.SourceTag = sourceTag @@ -127,13 +157,23 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, // Destination: if (typeof txJSON.Destination === 'string') { - const {classicAccount: destinationAccount, tag: destinationTag} = getClassicAccountAndTag(txJSON.Destination) + const { + classicAccount: destinationAccount, + tag: destinationTag + } = getClassicAccountAndTag(txJSON.Destination) newTxJSON.Destination = destinationAccount if (destinationTag !== undefined) { - if (TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD.includes(txJSON.TransactionType)) { + if ( + TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD.includes( + txJSON.TransactionType + ) + ) { if (txJSON.DestinationTag && txJSON.DestinationTag !== destinationTag) { - return Promise.reject(new ValidationError( - 'The Payment `DestinationTag`, if present, must match the tag of the `Destination` X-address')) + return Promise.reject( + new ValidationError( + 'The Payment `DestinationTag`, if present, must match the tag of the `Destination` X-address' + ) + ) } if (destinationTag) { newTxJSON.DestinationTag = destinationTag @@ -168,12 +208,20 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, // instructions.maxLedgerVersion // instructions.maxLedgerVersionOffset if (newTxJSON.LastLedgerSequence && instructions.maxLedgerVersion) { - return Promise.reject(new ValidationError('`LastLedgerSequence` in txJSON and `maxLedgerVersion`' + - ' in `instructions` cannot both be set')) + return Promise.reject( + new ValidationError( + '`LastLedgerSequence` in txJSON and `maxLedgerVersion`' + + ' in `instructions` cannot both be set' + ) + ) } if (newTxJSON.LastLedgerSequence && instructions.maxLedgerVersionOffset) { - return Promise.reject(new ValidationError('`LastLedgerSequence` in txJSON and `maxLedgerVersionOffset`' + - ' in `instructions` cannot both be set')) + return Promise.reject( + new ValidationError( + '`LastLedgerSequence` in txJSON and `maxLedgerVersionOffset`' + + ' in `instructions` cannot both be set' + ) + ) } if (newTxJSON.LastLedgerSequence) { return Promise.resolve() @@ -184,8 +232,10 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, } return Promise.resolve() } - const offset = instructions.maxLedgerVersionOffset !== undefined ? - instructions.maxLedgerVersionOffset : 3 + const offset = + instructions.maxLedgerVersionOffset !== undefined + ? instructions.maxLedgerVersionOffset + : 3 return api.connection.getLedgerVersion().then(ledgerVersion => { newTxJSON.LastLedgerSequence = ledgerVersion + offset return @@ -199,35 +249,54 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, // Furthermore, txJSON.Fee is in drops while instructions.fee is in XRP, which would just add to // the confusion. It is simpler to require that only one is used. if (newTxJSON.Fee && instructions.fee) { - return Promise.reject(new ValidationError('`Fee` in txJSON and `fee` in `instructions` cannot both be set')) + return Promise.reject( + new ValidationError( + '`Fee` in txJSON and `fee` in `instructions` cannot both be set' + ) + ) } if (newTxJSON.Fee) { // txJSON.Fee is set. Use this value and do not scale it. return Promise.resolve() } - const multiplier = instructions.signersCount === undefined ? 1 : - instructions.signersCount + 1 + const multiplier = + instructions.signersCount === undefined + ? 1 + : instructions.signersCount + 1 if (instructions.fee !== undefined) { const fee = new BigNumber(instructions.fee) if (fee.isGreaterThan(api._maxFeeXRP)) { - return Promise.reject(new ValidationError(`Fee of ${fee.toString(10)} XRP exceeds ` + - `max of ${api._maxFeeXRP} XRP. To use this fee, increase ` + - '`maxFeeXRP` in the RippleAPI constructor.')) + return Promise.reject( + new ValidationError( + `Fee of ${fee.toString(10)} XRP exceeds ` + + `max of ${api._maxFeeXRP} XRP. To use this fee, increase ` + + '`maxFeeXRP` in the RippleAPI constructor.' + ) + ) } - newTxJSON.Fee = scaleValue(common.xrpToDrops(instructions.fee), multiplier) + newTxJSON.Fee = scaleValue( + common.xrpToDrops(instructions.fee), + multiplier + ) return Promise.resolve() } const cushion = api._feeCushion return api.getFee(cushion).then(fee => { return api.connection.getFeeRef().then(feeRef => { const extraFee = - (newTxJSON.TransactionType !== 'EscrowFinish' || - newTxJSON.Fulfillment === undefined) ? 0 : - (cushion * feeRef * (32 + Math.floor( - Buffer.from(newTxJSON.Fulfillment, 'hex').length / 16))) + newTxJSON.TransactionType !== 'EscrowFinish' || + newTxJSON.Fulfillment === undefined + ? 0 + : cushion * + feeRef * + (32 + + Math.floor( + Buffer.from(newTxJSON.Fulfillment, 'hex').length / 16 + )) const feeDrops = common.xrpToDrops(fee) - const maxFeeXRP = instructions.maxFee ? - BigNumber.min(api._maxFeeXRP, instructions.maxFee) : api._maxFeeXRP + const maxFeeXRP = instructions.maxFee + ? BigNumber.min(api._maxFeeXRP, instructions.maxFee) + : api._maxFeeXRP const maxFeeDrops = common.xrpToDrops(maxFeeXRP) const normalFee = scaleValue(feeDrops, multiplier, extraFee) newTxJSON.Fee = BigNumber.min(normalFee, maxFeeDrops).toString(10) @@ -239,12 +308,19 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, async function prepareSequence(): Promise { if (instructions.sequence !== undefined) { - if (newTxJSON.Sequence === undefined || instructions.sequence === newTxJSON.Sequence) { + if ( + newTxJSON.Sequence === undefined || + instructions.sequence === newTxJSON.Sequence + ) { newTxJSON.Sequence = instructions.sequence return Promise.resolve() } else { // Both txJSON.Sequence and instructions.sequence are defined, and they are NOT equal - return Promise.reject(new ValidationError('`Sequence` in txJSON must match `sequence` in `instructions`')) + return Promise.reject( + new ValidationError( + '`Sequence` in txJSON must match `sequence` in `instructions`' + ) + ) } } if (newTxJSON.Sequence !== undefined) { @@ -271,7 +347,9 @@ function prepareTransaction(txJSON: TransactionJSON, api: RippleAPI, } function convertStringToHex(string: string): string { -return Buffer.from(string, 'utf8').toString('hex').toUpperCase() + return Buffer.from(string, 'utf8') + .toString('hex') + .toUpperCase() } function convertMemo(memo: Memo): {Memo: ApiMemo} { diff --git a/test/api/combine/index.ts b/test/api/combine/index.ts index 618a2bef..75984df4 100644 --- a/test/api/combine/index.ts +++ b/test/api/combine/index.ts @@ -2,9 +2,9 @@ import assert from 'assert-diff' import binary from 'ripple-binary-codec' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const { combine: REQUEST_FIXTURES } = requests -const { combine: RESPONSE_FIXTURES } = responses +import {assertResultMatch, TestSuite} from '../../utils' +const {combine: REQUEST_FIXTURES} = requests +const {combine: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. diff --git a/test/api/computeLedgerHash/index.ts b/test/api/computeLedgerHash/index.ts index 410f90a5..2fb0626d 100644 --- a/test/api/computeLedgerHash/index.ts +++ b/test/api/computeLedgerHash/index.ts @@ -1,8 +1,8 @@ import assert from 'assert-diff' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const { computeLedgerHash: REQUEST_FIXTURES } = requests +import {assertResultMatch, TestSuite} from '../../utils' +const {computeLedgerHash: REQUEST_FIXTURES} = requests /** * Every test suite exports their tests in the default object. @@ -29,7 +29,7 @@ export default { ledger.parentCloseTime = ledger.closeTime let hash try { - hash = api.computeLedgerHash(ledger, { computeTreeHashes: true }) + hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) } catch (error) { assert(error instanceof api.errors.ValidationError) assert.strictEqual( @@ -72,7 +72,7 @@ export default { ledger.parentCloseTime = ledger.closeTime let hash try { - hash = api.computeLedgerHash(ledger, { computeTreeHashes: true }) + hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) } catch (error) { assert(error instanceof api.errors.ValidationError) assert.strictEqual( @@ -114,7 +114,7 @@ export default { ) // fail if required to compute tree hashes try { - hash = computeLedgerHash(ledger, { computeTreeHashes: true }) + hash = computeLedgerHash(ledger, {computeTreeHashes: true}) } catch (error) { assert(error instanceof ValidationError) assert.strictEqual(error.message, expectedError) diff --git a/test/api/constructor/index.ts b/test/api/constructor/index.ts index 21b99c59..e88649fb 100644 --- a/test/api/constructor/index.ts +++ b/test/api/constructor/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' -import { RippleAPI } from 'ripple-api' +import {TestSuite} from '../../utils' +import {RippleAPI} from 'ripple-api' /** * Every test suite exports their tests in the default object. @@ -9,21 +9,21 @@ import { RippleAPI } from 'ripple-api' */ export default { 'RippleAPI - implicit server port': () => { - new RippleAPI({ server: 'wss://s1.ripple.com' }) + new RippleAPI({server: 'wss://s1.ripple.com'}) }, 'RippleAPI invalid options': () => { // @ts-ignore - This is intentionally invalid - assert.throws(() => new RippleAPI({ invalid: true })) + assert.throws(() => new RippleAPI({invalid: true})) }, 'RippleAPI valid options': () => { - const api = new RippleAPI({ server: 'wss://s:1' }) + const api = new RippleAPI({server: 'wss://s:1'}) const privateConnectionUrl = (api.connection as any)._url assert.deepEqual(privateConnectionUrl, 'wss://s:1') }, 'RippleAPI invalid server uri': () => { - assert.throws(() => new RippleAPI({ server: 'wss//s:1' })) + assert.throws(() => new RippleAPI({server: 'wss//s:1'})) } } diff --git a/test/api/deriveAddress/index.ts b/test/api/deriveAddress/index.ts index 763982d6..e7ab3e03 100644 --- a/test/api/deriveAddress/index.ts +++ b/test/api/deriveAddress/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/deriveKeypair/index.ts b/test/api/deriveKeypair/index.ts index 259b1a05..d217f09d 100644 --- a/test/api/deriveKeypair/index.ts +++ b/test/api/deriveKeypair/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/deriveXAddress/index.ts b/test/api/deriveXAddress/index.ts index b12acbdf..c31baa00 100644 --- a/test/api/deriveXAddress/index.ts +++ b/test/api/deriveXAddress/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' -import { RippleAPI } from '../../../src' +import {TestSuite} from '../../utils' +import {RippleAPI} from '../../../src' /** * Every test suite exports their tests in the default object. diff --git a/test/api/dropsToXrp/index.ts b/test/api/dropsToXrp/index.ts index 890522ba..88b03ff1 100644 --- a/test/api/dropsToXrp/index.ts +++ b/test/api/dropsToXrp/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' import BigNumber from 'bignumber.js' /** diff --git a/test/api/errors/index.ts b/test/api/errors/index.ts index 6c528c32..d042cc24 100644 --- a/test/api/errors/index.ts +++ b/test/api/errors/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/formatBidsAndAsks/index.ts b/test/api/formatBidsAndAsks/index.ts index 37840026..c5351e06 100644 --- a/test/api/formatBidsAndAsks/index.ts +++ b/test/api/formatBidsAndAsks/index.ts @@ -1,9 +1,9 @@ import BigNumber from 'bignumber.js' import assert from 'assert-diff' -import { RippleAPI } from 'ripple-api' +import {RippleAPI} from 'ripple-api' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' function checkSortingOfOrders(orders) { let previousRate = '0' @@ -181,7 +181,7 @@ export default { 'sample USD/XRP book has orders sorted correctly': async (api, address) => { const orderbookInfo = { - counter: { currency: 'XRP' }, + counter: {currency: 'XRP'}, base: { currency: 'USD', counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' @@ -325,7 +325,7 @@ export default { orders.forEach(order => { const quantity = order.specification.quantity const totalPrice = order.specification.totalPrice - const { base, counter } = requests.getOrderbook.normal + const {base, counter} = requests.getOrderbook.normal assert.strictEqual(quantity.currency, base.currency) assert.strictEqual(quantity.counterparty, base.counterparty) assert.strictEqual(totalPrice.currency, counter.currency) diff --git a/test/api/generateAddress/index.ts b/test/api/generateAddress/index.ts index f763eac3..ad6b24fe 100644 --- a/test/api/generateAddress/index.ts +++ b/test/api/generateAddress/index.ts @@ -1,7 +1,7 @@ import assert from 'assert-diff' import responses from '../../fixtures/responses' -import { TestSuite } from '../../utils' -const { generateAddress: RESPONSE_FIXTURES } = responses +import {TestSuite} from '../../utils' +const {generateAddress: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -14,7 +14,7 @@ export default { return new Array(16).fill(0) } assert.deepEqual( - api.generateAddress({ entropy: random() }), + api.generateAddress({entropy: random()}), RESPONSE_FIXTURES ) }, @@ -24,7 +24,7 @@ export default { function random() { return new Array(1).fill(0) } - api.generateAddress({ entropy: random() }) + api.generateAddress({entropy: random()}) }, api.errors.UnexpectedError) } } diff --git a/test/api/generateXAddress/index.ts b/test/api/generateXAddress/index.ts index 3cd2f978..33ffe163 100644 --- a/test/api/generateXAddress/index.ts +++ b/test/api/generateXAddress/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' import responses from '../../fixtures/responses' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -13,7 +13,7 @@ export default { return new Array(16).fill(0) } assert.deepEqual( - api.generateXAddress({ entropy: random() }), + api.generateXAddress({entropy: random()}), responses.generateXAddress ) }, @@ -23,7 +23,7 @@ export default { function random() { return new Array(1).fill(0) } - api.generateXAddress({ entropy: random() }) + api.generateXAddress({entropy: random()}) }, api.errors.UnexpectedError) } } diff --git a/test/api/getAccountInfo/index.ts b/test/api/getAccountInfo/index.ts index bd1b7edd..b7fa42d8 100644 --- a/test/api/getAccountInfo/index.ts +++ b/test/api/getAccountInfo/index.ts @@ -1,5 +1,5 @@ import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -20,7 +20,7 @@ export default { 'getAccountInfo - invalid options': async (api, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getAccountInfo(address, { invalid: 'options' }), + api.getAccountInfo(address, {invalid: 'options'}), api.errors.ValidationError ) } diff --git a/test/api/getAccountObjects/index.ts b/test/api/getAccountObjects/index.ts index 14f1e692..0092150a 100644 --- a/test/api/getAccountObjects/index.ts +++ b/test/api/getAccountObjects/index.ts @@ -1,6 +1,6 @@ import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const { getAccountObjects: RESPONSE_FIXTURES } = responses +import {assertResultMatch, TestSuite} from '../../utils' +const {getAccountObjects: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -15,7 +15,7 @@ export default { 'getAccountObjects - invalid options': async (api, address) => { // @ts-ignore - This is intentionally invalid - const result = await api.getAccountObjects(address, { invalid: 'options' }) + const result = await api.getAccountObjects(address, {invalid: 'options'}) assertResultMatch(result, RESPONSE_FIXTURES, 'AccountObjectsResponse') } } diff --git a/test/api/getBalanceSheet/index.ts b/test/api/getBalanceSheet/index.ts index 08406955..ecc93d4f 100644 --- a/test/api/getBalanceSheet/index.ts +++ b/test/api/getBalanceSheet/index.ts @@ -1,4 +1,4 @@ -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -13,13 +13,13 @@ export default { 'getBalanceSheet - invalid options': async (api, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getBalanceSheet(address, { invalid: 'options' }), + api.getBalanceSheet(address, {invalid: 'options'}), api.errors.ValidationError ) }, 'getBalanceSheet - empty': async (api, address) => { - const options = { ledgerVersion: 123456 } + const options = {ledgerVersion: 123456} const result = await api.getBalanceSheet(address, options) assertResultMatch(result, {}, 'getBalanceSheet') } diff --git a/test/api/getBalances/index.ts b/test/api/getBalances/index.ts index 80a7aed7..1ae08dca 100644 --- a/test/api/getBalances/index.ts +++ b/test/api/getBalances/index.ts @@ -1,5 +1,5 @@ import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -13,14 +13,14 @@ export default { }, 'getBalances - limit': async (api, address) => { - const options = { limit: 3, ledgerVersion: 123456 } + const options = {limit: 3, ledgerVersion: 123456} const expectedResponse = responses.getBalances.slice(0, 3) const result = await api.getBalances(address, options) assertResultMatch(result, expectedResponse, 'getBalances') }, 'getBalances - limit & currency': async (api, address) => { - const options = { currency: 'USD', limit: 3 } + const options = {currency: 'USD', limit: 3} const expectedResponse = responses.getBalances .filter(item => item.currency === 'USD') .slice(0, 3) diff --git a/test/api/getFee/index.ts b/test/api/getFee/index.ts index 671b6117..bbba0bc0 100644 --- a/test/api/getFee/index.ts +++ b/test/api/getFee/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -22,7 +22,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { highLoadFactor: true } + data: {highLoadFactor: true} }) ) const fee = await api.getFee() @@ -36,7 +36,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { highLoadFactor: true } + data: {highLoadFactor: true} }) ) const fee = await api.getFee() diff --git a/test/api/getFeeBase/index.ts b/test/api/getFeeBase/index.ts index 32a4ed20..23681ca4 100644 --- a/test/api/getFeeBase/index.ts +++ b/test/api/getFeeBase/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/getFeeRef/index.ts b/test/api/getFeeRef/index.ts index 56e1c90c..d625ce25 100644 --- a/test/api/getFeeRef/index.ts +++ b/test/api/getFeeRef/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/getLedger/index.ts b/test/api/getLedger/index.ts index 461592a3..1fd865bb 100644 --- a/test/api/getLedger/index.ts +++ b/test/api/getLedger/index.ts @@ -1,7 +1,7 @@ import assert from 'assert-diff' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' import responses from '../../fixtures/responses' -const { getLedger: RESPONSE_FIXTURES } = responses +const {getLedger: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -21,7 +21,7 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger') }, 'future ledger version': async api => { - const response = await api.getLedger({ ledgerVersion: 14661789 }) + const response = await api.getLedger({ledgerVersion: 14661789}) assert(!!response) }, 'with state as hashes': async api => { @@ -82,7 +82,7 @@ export default { ...response, parentCloseTime: response.closeTime } - const hash = api.computeLedgerHash(ledger, { computeTreeHashes: true }) + const hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) assert.strictEqual( hash, 'E6DB7365949BF9814D76BCC730B01818EB9136A89DB224F3F9F5AAE4569D758E' diff --git a/test/api/getLedgerVersion/index.ts b/test/api/getLedgerVersion/index.ts index eb8dc0f8..a2edb5d3 100644 --- a/test/api/getLedgerVersion/index.ts +++ b/test/api/getLedgerVersion/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/getOrderbook/index.ts b/test/api/getOrderbook/index.ts index a285a84e..04f4752c 100644 --- a/test/api/getOrderbook/index.ts +++ b/test/api/getOrderbook/index.ts @@ -1,7 +1,7 @@ import assert from 'assert-diff' import responses from '../../fixtures/responses' import requests from '../../fixtures/requests' -import { TestSuite, assertResultMatch, assertRejects } from '../../utils' +import {TestSuite, assertResultMatch, assertRejects} from '../../utils' import BigNumber from 'bignumber.js' function checkSortingOfOrders(orders) { @@ -48,7 +48,7 @@ export default { const response = await api.getOrderbook( address, requests.getOrderbook.normal, - { limit: 20 } + {limit: 20} ) assertResultMatch(response, responses.getOrderbook.normal, 'getOrderbook') }, @@ -90,7 +90,7 @@ export default { 'sample USD/XRP book has orders sorted correctly': async (api, address) => { const orderbookInfo = { - counter: { currency: 'XRP' }, + counter: {currency: 'XRP'}, base: { currency: 'USD', counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' @@ -131,7 +131,7 @@ export default { ;[...response.bids, ...response.asks].forEach(order => { const quantity = order.specification.quantity const totalPrice = order.specification.totalPrice - const { base, counter } = requests.getOrderbook.normal + const {base, counter} = requests.getOrderbook.normal assert.strictEqual(quantity.currency, base.currency) assert.strictEqual(quantity.counterparty, base.counterparty) assert.strictEqual(totalPrice.currency, counter.currency) diff --git a/test/api/getOrders/index.ts b/test/api/getOrders/index.ts index 2e8066b9..afa9dace 100644 --- a/test/api/getOrders/index.ts +++ b/test/api/getOrders/index.ts @@ -1,5 +1,5 @@ import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' export const config = { // TODO: The mock server right now returns a hard-coded string, no matter @@ -20,14 +20,14 @@ export default { }, 'getOrders - limit': async (api, address) => { - const result = await api.getOrders(address, { limit: 20 }) + const result = await api.getOrders(address, {limit: 20}) assertResultMatch(result, responses.getOrders, 'getOrders') }, 'getOrders - invalid options': async (api, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getOrders(address, { invalid: 'options' }), + api.getOrders(address, {invalid: 'options'}), api.errors.ValidationError ) } diff --git a/test/api/getPaths/index.ts b/test/api/getPaths/index.ts index b48617bf..94301e1c 100644 --- a/test/api/getPaths/index.ts +++ b/test/api/getPaths/index.ts @@ -1,10 +1,10 @@ import assert from 'assert-diff' -import { assertResultMatch, assertRejects, TestSuite } from '../../utils' +import {assertResultMatch, assertRejects, TestSuite} from '../../utils' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' import addresses from '../../fixtures/addresses.json' -const { getPaths: REQUEST_FIXTURES } = requests -const { getPaths: RESPONSE_FIXTURES } = responses +const {getPaths: REQUEST_FIXTURES} = requests +const {getPaths: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -83,7 +83,7 @@ export default { return assertRejects( api.getPaths({ ...REQUEST_FIXTURES.normal, - source: { address: addresses.NOTFOUND } + source: {address: addresses.NOTFOUND} }), api.errors.RippleError ) diff --git a/test/api/getPaymentChannel/index.ts b/test/api/getPaymentChannel/index.ts index e0f4beb5..34227718 100644 --- a/test/api/getPaymentChannel/index.ts +++ b/test/api/getPaymentChannel/index.ts @@ -1,6 +1,6 @@ import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const { getPaymentChannel: RESPONSE_FIXTURES } = responses +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const {getPaymentChannel: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. diff --git a/test/api/getServerInfo/index.ts b/test/api/getServerInfo/index.ts index aea396f5..f63b718f 100644 --- a/test/api/getServerInfo/index.ts +++ b/test/api/getServerInfo/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite, assertRejects } from '../../utils' +import {assertResultMatch, TestSuite, assertRejects} from '../../utils' /** * Every test suite exports their tests in the default object. @@ -17,7 +17,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { returnErrorOnServerInfo: true } + data: {returnErrorOnServerInfo: true} }) ) try { @@ -34,7 +34,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { serverInfoWithoutValidated: true } + data: {serverInfoWithoutValidated: true} }) ) const serverInfo = await api.getServerInfo() diff --git a/test/api/getSettings/index.ts b/test/api/getSettings/index.ts index e91d04b8..c090ba07 100644 --- a/test/api/getSettings/index.ts +++ b/test/api/getSettings/index.ts @@ -1,6 +1,6 @@ import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const { getSettings: RESPONSE_FIXTURES } = responses +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const {getSettings: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -21,7 +21,7 @@ export default { 'getSettings - invalid options': async (api, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getSettings(address, { invalid: 'options' }), + api.getSettings(address, {invalid: 'options'}), api.errors.ValidationError ) } diff --git a/test/api/getTransaction/index.ts b/test/api/getTransaction/index.ts index 0bf0be8b..446d1fd7 100644 --- a/test/api/getTransaction/index.ts +++ b/test/api/getTransaction/index.ts @@ -4,12 +4,12 @@ import { NotFoundError, UnexpectedError } from 'ripple-api/common/errors' -import { PendingLedgerVersionError } from '../../../src/common/errors' +import {PendingLedgerVersionError} from '../../../src/common/errors' import hashes from '../../fixtures/hashes.json' import responses from '../../fixtures/responses' import ledgerClosed from '../../fixtures/rippled/ledger-close-newer.json' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const { getTransaction: RESPONSE_FIXTURES } = responses +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const {getTransaction: RESPONSE_FIXTURES} = responses function closeLedger(connection) { connection._ws.emit('message', JSON.stringify(ledgerClosed)) diff --git a/test/api/getTransactions/index.ts b/test/api/getTransactions/index.ts index 01211f04..27579ac5 100644 --- a/test/api/getTransactions/index.ts +++ b/test/api/getTransactions/index.ts @@ -1,11 +1,11 @@ -import { RippleAPI } from 'ripple-api' +import {RippleAPI} from 'ripple-api' import assert from 'assert-diff' -import { assertResultMatch, TestSuite, assertRejects } from '../../utils' +import {assertResultMatch, TestSuite, assertRejects} from '../../utils' import responses from '../../fixtures/responses' import hashes from '../../fixtures/hashes.json' import addresses from '../../fixtures/addresses.json' const utils = RippleAPI._PRIVATE.ledgerUtils -const { getTransactions: RESPONSE_FIXTURES } = responses +const {getTransactions: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -14,7 +14,7 @@ const { getTransactions: RESPONSE_FIXTURES } = responses */ export default { 'default': async (api, address) => { - const options = { types: ['payment', 'order'], initiated: true, limit: 2 } + const options = {types: ['payment', 'order'], initiated: true, limit: 2} const response = await api.getTransactions(address, options) hack(response) assertResultMatch(response, RESPONSE_FIXTURES.normal, 'getTransactions') @@ -122,7 +122,7 @@ export default { // this is the case where core.RippleError just falls // through the api to the user 'error': async (api, address) => { - const options = { types: ['payment', 'order'], initiated: true, limit: 13 } + const options = {types: ['payment', 'order'], initiated: true, limit: 13} return assertRejects( api.getTransactions(address, options), api.errors.RippleError @@ -163,6 +163,6 @@ export default { // format responses, instead of the binary. function hack(response) { response.forEach(element => { - element.outcome.timestamp = "2019-04-01T07:39:01.000Z" + element.outcome.timestamp = '2019-04-01T07:39:01.000Z' }) } diff --git a/test/api/getTrustlines/index.ts b/test/api/getTrustlines/index.ts index 89dde403..c8c1b05b 100644 --- a/test/api/getTrustlines/index.ts +++ b/test/api/getTrustlines/index.ts @@ -1,7 +1,7 @@ import addresses from '../../fixtures/addresses.json' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const { getTrustlines: RESPONSE_FIXTURES } = responses +import {assertResultMatch, TestSuite} from '../../utils' +const {getTrustlines: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -10,13 +10,13 @@ const { getTrustlines: RESPONSE_FIXTURES } = responses */ export default { 'getTrustlines - filtered': async (api, address) => { - const options = { currency: 'USD' } + const options = {currency: 'USD'} const result = await api.getTrustlines(address, options) assertResultMatch(result, RESPONSE_FIXTURES.filtered, 'getTrustlines') }, 'getTrustlines - more than 400 items': async (api, address) => { - const options = { limit: 401 } + const options = {limit: 401} const result = await api.getTrustlines(addresses.THIRD_ACCOUNT, options) assertResultMatch( result, diff --git a/test/api/hasNextPage/index.ts b/test/api/hasNextPage/index.ts index 7c670ff4..d2a6a5e0 100644 --- a/test/api/hasNextPage/index.ts +++ b/test/api/hasNextPage/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/isConnected/index.ts b/test/api/isConnected/index.ts index 1dbbd123..c5660409 100644 --- a/test/api/isConnected/index.ts +++ b/test/api/isConnected/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/isValidAddress/index.ts b/test/api/isValidAddress/index.ts index c5512370..8ab82f1d 100644 --- a/test/api/isValidAddress/index.ts +++ b/test/api/isValidAddress/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' import addresses from '../../fixtures/addresses.json' export default { diff --git a/test/api/isValidSecret/index.ts b/test/api/isValidSecret/index.ts index 42b054dc..e8f6abf8 100644 --- a/test/api/isValidSecret/index.ts +++ b/test/api/isValidSecret/index.ts @@ -1,5 +1,5 @@ import assert from 'assert-diff' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' export default { 'returns true for valid secret': async (api, address) => { diff --git a/test/api/prepareCheckCancel/index.ts b/test/api/prepareCheckCancel/index.ts index b53dd812..328d8ca2 100644 --- a/test/api/prepareCheckCancel/index.ts +++ b/test/api/prepareCheckCancel/index.ts @@ -1,6 +1,6 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareCheckCash/index.ts b/test/api/prepareCheckCash/index.ts index ad311d00..f16cbc98 100644 --- a/test/api/prepareCheckCash/index.ts +++ b/test/api/prepareCheckCash/index.ts @@ -1,6 +1,6 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareCheckCreate/index.ts b/test/api/prepareCheckCreate/index.ts index a2f4bb19..c6bd185a 100644 --- a/test/api/prepareCheckCreate/index.ts +++ b/test/api/prepareCheckCreate/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareEscrowCancellation/index.ts b/test/api/prepareEscrowCancellation/index.ts index 51b7f44b..75fb2d69 100644 --- a/test/api/prepareEscrowCancellation/index.ts +++ b/test/api/prepareEscrowCancellation/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareEscrowCreation/index.ts b/test/api/prepareEscrowCreation/index.ts index 20aab04a..2f81e8bf 100644 --- a/test/api/prepareEscrowCreation/index.ts +++ b/test/api/prepareEscrowCreation/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} export const config = { // TODO: The mock server right now returns a hard-coded string, no matter @@ -10,7 +10,6 @@ export const config = { skipXAddress: true } - /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. diff --git a/test/api/prepareEscrowExecution/index.ts b/test/api/prepareEscrowExecution/index.ts index 3279448d..a875debe 100644 --- a/test/api/prepareEscrowExecution/index.ts +++ b/test/api/prepareEscrowExecution/index.ts @@ -1,7 +1,7 @@ -import { TestSuite, assertRejects, assertResultMatch } from '../../utils' +import {TestSuite, assertRejects, assertResultMatch} from '../../utils' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareOrder/index.ts b/test/api/prepareOrder/index.ts index f2f224d7..c44041d0 100644 --- a/test/api/prepareOrder/index.ts +++ b/test/api/prepareOrder/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareOrderCancellation/index.ts b/test/api/prepareOrderCancellation/index.ts index f3ab10e4..f47ab227 100644 --- a/test/api/prepareOrderCancellation/index.ts +++ b/test/api/prepareOrderCancellation/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/preparePayment/index.ts b/test/api/preparePayment/index.ts index bedc4189..0fbd7412 100644 --- a/test/api/preparePayment/index.ts +++ b/test/api/preparePayment/index.ts @@ -1,10 +1,10 @@ -import { assertResultMatch, TestSuite, assertRejects } from '../../utils' +import {assertResultMatch, TestSuite, assertRejects} from '../../utils' import responses from '../../fixtures/responses' import requests from '../../fixtures/requests' -import { ValidationError } from 'ripple-api/common/errors' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -const { preparePayment: REQUEST_FIXTURES } = requests -const { preparePayment: RESPONSE_FIXTURES } = responses +import {ValidationError} from 'ripple-api/common/errors' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} +const {preparePayment: REQUEST_FIXTURES} = requests +const {preparePayment: RESPONSE_FIXTURES} = responses const RECIPIENT_ADDRESS = 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' /** @@ -52,11 +52,11 @@ export default { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', - maxAmount: { value: '1', currency: 'XRP' } + maxAmount: {value: '1', currency: 'XRP'} }, destination: { address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', - amount: { value: '1', currency: 'XRP' } + amount: {value: '1', currency: 'XRP'} } } const expected = { @@ -80,11 +80,11 @@ export default { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', - maxAmount: { value: '1000000', currency: 'drops' } + maxAmount: {value: '1000000', currency: 'drops'} }, destination: { address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', - amount: { value: '1000000', currency: 'drops' } + amount: {value: '1000000', currency: 'drops'} } } const expected = { @@ -108,11 +108,11 @@ export default { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', - maxAmount: { value: '1000000', currency: 'drops' } + maxAmount: {value: '1000000', currency: 'drops'} }, destination: { address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', - amount: { value: '1', currency: 'XRP' } + amount: {value: '1', currency: 'XRP'} } } const expected = { @@ -136,11 +136,11 @@ export default { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', - maxAmount: { value: '1', currency: 'XRP' } + maxAmount: {value: '1', currency: 'XRP'} }, destination: { address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', - amount: { value: '1000000', currency: 'drops' } + amount: {value: '1000000', currency: 'drops'} } } const expected = { @@ -169,11 +169,11 @@ export default { source: { address: address, // instead of `maxAmount` - amount: { value: '1000', currency: 'drops' } + amount: {value: '1000', currency: 'drops'} }, destination: { address: RECIPIENT_ADDRESS, - amount: { value: '1000', currency: 'drops' } + amount: {value: '1000', currency: 'drops'} } } @@ -190,10 +190,10 @@ export default { ) => { // Marking as "any" to get around the fact that TS won't allow this. const payment: any = { - source: { address: address }, + source: {address: address}, destination: { address: RECIPIENT_ADDRESS, - amount: { value: '1000', currency: 'drops' } + amount: {value: '1000', currency: 'drops'} } } @@ -211,15 +211,15 @@ export default { const payment = { source: { address: address, - maxAmount: { value: '1000', currency: 'drops' } + maxAmount: {value: '1000', currency: 'drops'} }, destination: { address: RECIPIENT_ADDRESS, - amount: { value: '1000', currency: 'drops' } + amount: {value: '1000', currency: 'drops'} } } return assertRejects( - api.preparePayment(address, payment, { fee: '3' }), + api.preparePayment(address, payment, {fee: '3'}), ValidationError, 'Fee of 3 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the RippleAPI constructor.' ) @@ -419,7 +419,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { loadFactor: 5407.96875 } + data: {loadFactor: 5407.96875} }) ) const expectedResponse = { diff --git a/test/api/preparePaymentChannelClaim/index.ts b/test/api/preparePaymentChannelClaim/index.ts index dc9d4d35..31f58520 100644 --- a/test/api/preparePaymentChannelClaim/index.ts +++ b/test/api/preparePaymentChannelClaim/index.ts @@ -1,10 +1,10 @@ import assert from 'assert-diff' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -const { preparePaymentChannelClaim: REQUEST_FIXTURES } = requests -const { preparePaymentChannelClaim: RESPONSE_FIXTURES } = responses +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} +const {preparePaymentChannelClaim: REQUEST_FIXTURES} = requests +const {preparePaymentChannelClaim: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. diff --git a/test/api/preparePaymentChannelCreate/index.ts b/test/api/preparePaymentChannelCreate/index.ts index f523ce9e..214f6edb 100644 --- a/test/api/preparePaymentChannelCreate/index.ts +++ b/test/api/preparePaymentChannelCreate/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} export const config = { // TODO: The mock server right now returns a hard-coded string, no matter diff --git a/test/api/preparePaymentChannelFund/index.ts b/test/api/preparePaymentChannelFund/index.ts index 8bc23dff..43feeb50 100644 --- a/test/api/preparePaymentChannelFund/index.ts +++ b/test/api/preparePaymentChannelFund/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/prepareSettings/index.ts b/test/api/prepareSettings/index.ts index c4fea9eb..71b32844 100644 --- a/test/api/prepareSettings/index.ts +++ b/test/api/prepareSettings/index.ts @@ -1,8 +1,8 @@ import assert from 'assert-diff' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. @@ -44,7 +44,7 @@ export default { ) }, 'regularKey': async (api, address) => { - const regularKey = { regularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD' } + const regularKey = {regularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD'} const response = await api.prepareSettings( address, regularKey, @@ -53,7 +53,7 @@ export default { assertResultMatch(response, responses.prepareSettings.regularKey, 'prepare') }, 'remove regularKey': async (api, address) => { - const regularKey = { regularKey: null } + const regularKey = {regularKey: null} const response = await api.prepareSettings( address, regularKey, @@ -66,7 +66,7 @@ export default { ) }, 'flag set': async (api, address) => { - const settings = { requireDestinationTag: true } + const settings = {requireDestinationTag: true} const response = await api.prepareSettings( address, settings, @@ -75,7 +75,7 @@ export default { assertResultMatch(response, responses.prepareSettings.flagSet, 'prepare') }, 'flag clear': async (api, address) => { - const settings = { requireDestinationTag: false } + const settings = {requireDestinationTag: false} const response = await api.prepareSettings( address, settings, @@ -84,7 +84,7 @@ export default { assertResultMatch(response, responses.prepareSettings.flagClear, 'prepare') }, 'set depositAuth flag': async (api, address) => { - const settings = { depositAuth: true } + const settings = {depositAuth: true} const response = await api.prepareSettings( address, settings, @@ -97,7 +97,7 @@ export default { ) }, 'clear depositAuth flag': async (api, address) => { - const settings = { depositAuth: false } + const settings = {depositAuth: false} const response = await api.prepareSettings( address, settings, @@ -110,7 +110,7 @@ export default { ) }, 'integer field clear': async (api, address) => { - const settings = { transferRate: null } + const settings = {transferRate: null} const response = await api.prepareSettings( address, settings, @@ -120,7 +120,7 @@ export default { assert.strictEqual(JSON.parse(response.txJSON).TransferRate, 0) }, 'set transferRate': async (api, address) => { - const settings = { transferRate: 1 } + const settings = {transferRate: 1} const response = await api.prepareSettings( address, settings, diff --git a/test/api/prepareTransaction/index.ts b/test/api/prepareTransaction/index.ts index 8b0cf939..575b0a60 100644 --- a/test/api/prepareTransaction/index.ts +++ b/test/api/prepareTransaction/index.ts @@ -1,8 +1,8 @@ -import { RippledError, ValidationError } from 'ripple-api/common/errors' +import {RippledError, ValidationError} from 'ripple-api/common/errors' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} export const config = { // TODO: The mock server right now returns a hard-coded string, no matter @@ -1026,7 +1026,7 @@ export default { api.connection._send( JSON.stringify({ command: 'config', - data: { loadFactor: 5407.96875 } + data: {loadFactor: 5407.96875} }) ) diff --git a/test/api/prepareTrustline/index.ts b/test/api/prepareTrustline/index.ts index 6d026f2e..de96d2f8 100644 --- a/test/api/prepareTrustline/index.ts +++ b/test/api/prepareTrustline/index.ts @@ -1,7 +1,7 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' +const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. diff --git a/test/api/request/index.ts b/test/api/request/index.ts index bb989b0c..7a2f22e7 100644 --- a/test/api/request/index.ts +++ b/test/api/request/index.ts @@ -1,5 +1,5 @@ import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/requestNextPage/index.ts b/test/api/requestNextPage/index.ts index 5559c28a..933fca85 100644 --- a/test/api/requestNextPage/index.ts +++ b/test/api/requestNextPage/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' -import { LedgerData } from 'ripple-api/common/types/objects' -import { assertRejects, TestSuite } from '../../utils' +import {LedgerData} from 'ripple-api/common/types/objects' +import {assertRejects, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/sign/index.ts b/test/api/sign/index.ts index 9cbd69bf..ae9a2090 100644 --- a/test/api/sign/index.ts +++ b/test/api/sign/index.ts @@ -1,12 +1,12 @@ import assert from 'assert-diff' -import { RippleAPI } from 'ripple-api' +import {RippleAPI} from 'ripple-api' import binary from 'ripple-binary-codec' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { TestSuite } from '../../utils' -const { schemaValidator } = RippleAPI._PRIVATE -const { sign: REQUEST_FIXTURES } = requests -const { sign: RESPONSE_FIXTURES } = responses +import {TestSuite} from '../../utils' +const {schemaValidator} = RippleAPI._PRIVATE +const {sign: REQUEST_FIXTURES} = requests +const {sign: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. @@ -187,7 +187,7 @@ export default { value: '31415' } } - const prepared = await api.prepareOrder(address, order, { sequence: 123 }) + const prepared = await api.prepareOrder(address, order, {sequence: 123}) const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' try { api.sign(prepared.txJSON, secret) diff --git a/test/api/signPaymentChannelClaim/index.ts b/test/api/signPaymentChannelClaim/index.ts index defe0ba9..55ac004a 100644 --- a/test/api/signPaymentChannelClaim/index.ts +++ b/test/api/signPaymentChannelClaim/index.ts @@ -1,4 +1,4 @@ -import { TestSuite, assertResultMatch } from '../../utils' +import {TestSuite, assertResultMatch} from '../../utils' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' diff --git a/test/api/submit/index.ts b/test/api/submit/index.ts index 0e27c848..ce7beabb 100644 --- a/test/api/submit/index.ts +++ b/test/api/submit/index.ts @@ -1,5 +1,5 @@ import responses from '../../fixtures/responses' -import { assertRejects, assertResultMatch, TestSuite } from '../../utils' +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/verifyPaymentChannelClaim/index.ts b/test/api/verifyPaymentChannelClaim/index.ts index d5f34dd7..fb6f540d 100644 --- a/test/api/verifyPaymentChannelClaim/index.ts +++ b/test/api/verifyPaymentChannelClaim/index.ts @@ -1,6 +1,6 @@ import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' -import { assertResultMatch, TestSuite } from '../../utils' +import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/api/xrpToDrops/index.ts b/test/api/xrpToDrops/index.ts index f1d14f51..a46df6d4 100644 --- a/test/api/xrpToDrops/index.ts +++ b/test/api/xrpToDrops/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' import BigNumber from 'bignumber.js' -import { TestSuite } from '../../utils' +import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. diff --git a/test/broadcast-api-test.ts b/test/broadcast-api-test.ts index a84c4ecf..8de8583f 100644 --- a/test/broadcast-api-test.ts +++ b/test/broadcast-api-test.ts @@ -1,67 +1,73 @@ -import _ from 'lodash'; -import assert from 'assert-diff'; -import setupAPI from './setup-api'; -import responses from './fixtures/responses'; -import ledgerClosed from './fixtures/rippled/ledger-close.json'; -import {RippleAPI} from 'ripple-api'; -const schemaValidator = RippleAPI._PRIVATE.schemaValidator; +import _ from 'lodash' +import assert from 'assert-diff' +import setupAPI from './setup-api' +import responses from './fixtures/responses' +import ledgerClosed from './fixtures/rippled/ledger-close.json' +import {RippleAPI} from 'ripple-api' +const schemaValidator = RippleAPI._PRIVATE.schemaValidator -const TIMEOUT = 20000; +const TIMEOUT = 20000 function checkResult(expected, schemaName, response) { if (expected.txJSON) { - assert(response.txJSON); - assert.deepEqual(JSON.parse(response.txJSON), JSON.parse(expected.txJSON)); + assert(response.txJSON) + assert.deepEqual(JSON.parse(response.txJSON), JSON.parse(expected.txJSON)) } - assert.deepEqual(_.omit(response, 'txJSON'), _.omit(expected, 'txJSON')); + assert.deepEqual(_.omit(response, 'txJSON'), _.omit(expected, 'txJSON')) if (schemaName) { - schemaValidator.schemaValidate(schemaName, response); + schemaValidator.schemaValidate(schemaName, response) } - return response; + return response } describe('RippleAPIBroadcast', function() { - this.timeout(TIMEOUT); - beforeEach(setupAPI.setupBroadcast); - afterEach(setupAPI.teardown); + this.timeout(TIMEOUT) + beforeEach(setupAPI.setupBroadcast) + afterEach(setupAPI.teardown) it('base', function() { - const expected = {request_server_info: 1}; - this.mocks.forEach(mock => mock.expect(_.assign({}, expected))); - assert(this.api.isConnected()); - return this.api.getServerInfo().then( - _.partial(checkResult, responses.getServerInfo, 'getServerInfo')); - }); + const expected = {request_server_info: 1} + this.mocks.forEach(mock => mock.expect(_.assign({}, expected))) + assert(this.api.isConnected()) + return this.api + .getServerInfo() + .then(_.partial(checkResult, responses.getServerInfo, 'getServerInfo')) + }) it('ledger', function(done) { - let gotLedger = 0; + let gotLedger = 0 this.api.on('ledger', () => { - gotLedger++; - }); - const ledgerNext = _.assign({}, ledgerClosed); - ledgerNext.ledger_index++; + gotLedger++ + }) + const ledgerNext = _.assign({}, ledgerClosed) + ledgerNext.ledger_index++ - this.api._apis.forEach(api => api.connection._send(JSON.stringify({ - command: 'echo', - data: ledgerNext - }))); + this.api._apis.forEach(api => + api.connection._send( + JSON.stringify({ + command: 'echo', + data: ledgerNext + }) + ) + ) setTimeout(() => { - assert.strictEqual(gotLedger, 1); - done(); - }, 1250); - }); + assert.strictEqual(gotLedger, 1) + done() + }, 1250) + }) it('error propagation', function(done) { this.api.once('error', (type, info) => { - assert.strictEqual(type, 'type'); - assert.strictEqual(info, 'info'); - done(); - }); - this.api._apis[1].connection._send(JSON.stringify({ - command: 'echo', - data: {error: 'type', error_message: 'info'} - })); - }); - -}); + assert.strictEqual(type, 'type') + assert.strictEqual(info, 'info') + done() + }) + this.api._apis[1].connection._send( + JSON.stringify({ + command: 'echo', + data: {error: 'type', error_message: 'info'} + }) + ) + }) +}) diff --git a/test/connection-test.ts b/test/connection-test.ts index cbc387fb..88428f56 100644 --- a/test/connection-test.ts +++ b/test/connection-test.ts @@ -1,431 +1,489 @@ -import _ from 'lodash'; -import net from 'net'; -import assert from 'assert-diff'; -import setupAPI from './setup-api'; -import {RippleAPI} from 'ripple-api'; -import ledgerClose from './fixtures/rippled/ledger-close.json'; -const utils = RippleAPI._PRIVATE.ledgerUtils; +import _ from 'lodash' +import net from 'net' +import assert from 'assert-diff' +import setupAPI from './setup-api' +import {RippleAPI} from 'ripple-api' +import ledgerClose from './fixtures/rippled/ledger-close.json' +const utils = RippleAPI._PRIVATE.ledgerUtils - -const TIMEOUT = 200000; // how long before each test case times out -const isBrowser = (process as any).browser; +const TIMEOUT = 200000 // how long before each test case times out +const isBrowser = (process as any).browser function createServer() { return new Promise((resolve, reject) => { - const server = net.createServer(); + const server = net.createServer() server.on('listening', function() { - resolve(server); - }); + resolve(server) + }) server.on('error', function(error) { - reject(error); - }); - server.listen(0, '0.0.0.0'); - }); + reject(error) + }) + server.listen(0, '0.0.0.0') + }) } describe('Connection', function() { - this.timeout(TIMEOUT); - beforeEach(setupAPI.setup); - afterEach(setupAPI.teardown); + this.timeout(TIMEOUT) + beforeEach(setupAPI.setup) + afterEach(setupAPI.teardown) it('default options', function() { - const connection: any = new utils.common.Connection('url'); - assert.strictEqual(connection._url, 'url'); - assert(_.isUndefined(connection._config.proxy)); - assert(_.isUndefined(connection._config.authorization)); - }); + const connection: any = new utils.common.Connection('url') + assert.strictEqual(connection._url, 'url') + assert(_.isUndefined(connection._config.proxy)) + assert(_.isUndefined(connection._config.authorization)) + }) describe('trace', () => { - const message1 = '{"type": "transaction"}'; - const message2 = '{"type": "path_find"}'; - const expectedMessages = [['send', message1], ['receive', message2]]; - const originalConsoleLog = console.log; + const message1 = '{"type": "transaction"}' + const message2 = '{"type": "path_find"}' + const expectedMessages = [ + ['send', message1], + ['receive', message2] + ] + const originalConsoleLog = console.log afterEach(() => { - console.log = originalConsoleLog; - }); + console.log = originalConsoleLog + }) it('as false', function() { - const messages = []; - console.log = (id, message) => messages.push([id, message]); - const connection: any = new utils.common.Connection('url', {trace: false}); - connection._ws = {send: function() {}}; - connection._send(message1); - connection._onMessage(message2); - assert.deepEqual(messages, []); - }); + const messages = [] + console.log = (id, message) => messages.push([id, message]) + const connection: any = new utils.common.Connection('url', {trace: false}) + connection._ws = {send: function() {}} + connection._send(message1) + connection._onMessage(message2) + assert.deepEqual(messages, []) + }) it('as true', function() { - const messages = []; - console.log = (id, message) => messages.push([id, message]); - const connection: any = new utils.common.Connection('url', {trace: true}); - connection._ws = {send: function() {}}; - connection._send(message1); - connection._onMessage(message2); - assert.deepEqual(messages, expectedMessages); - }); + const messages = [] + console.log = (id, message) => messages.push([id, message]) + const connection: any = new utils.common.Connection('url', {trace: true}) + connection._ws = {send: function() {}} + connection._send(message1) + connection._onMessage(message2) + assert.deepEqual(messages, expectedMessages) + }) it('as a function', function() { - const messages = []; + const messages = [] const connection: any = new utils.common.Connection('url', { trace: (id, message) => messages.push([id, message]) - }); - connection._ws = {send: function() {}}; - connection._send(message1); - connection._onMessage(message2); - assert.deepEqual(messages, expectedMessages); - }); - }); + }) + connection._ws = {send: function() {}} + connection._send(message1) + connection._onMessage(message2) + assert.deepEqual(messages, expectedMessages) + }) + }) it('with proxy', function(done) { if (isBrowser) { - done(); - return; + done() + return } createServer().then((server: any) => { - const port = server.address().port; - const expect = 'CONNECT localhost'; + const port = server.address().port + const expect = 'CONNECT localhost' server.on('connection', socket => { socket.on('data', data => { - const got = data.toString('ascii', 0, expect.length); - assert.strictEqual(got, expect); - server.close(); - connection.disconnect(); - done(); - }); - }); + const got = data.toString('ascii', 0, expect.length) + assert.strictEqual(got, expect) + server.close() + connection.disconnect() + done() + }) + }) const options = { proxy: 'ws://localhost:' + port, authorization: 'authorization', trustedCertificates: ['path/to/pem'] - }; - const connection = new utils.common.Connection(this.api.connection._url, options); - connection.connect().catch((err) => { - assert(err instanceof this.api.errors.NotConnectedError); - }); - }, done); - }); + } + const connection = new utils.common.Connection( + this.api.connection._url, + options + ) + connection.connect().catch(err => { + assert(err instanceof this.api.errors.NotConnectedError) + }) + }, done) + }) it('Multiply disconnect calls', function() { - this.api.disconnect(); - return this.api.disconnect(); - }); + this.api.disconnect() + return this.api.disconnect() + }) it('reconnect', function() { - return this.api.connection.reconnect(); - }); + return this.api.connection.reconnect() + }) it('NotConnectedError', function() { - const connection = new utils.common.Connection('url'); - return connection.getLedgerVersion().then(() => { - assert(false, 'Should throw NotConnectedError'); - }).catch(error => { - assert(error instanceof this.api.errors.NotConnectedError); - }); - }); + const connection = new utils.common.Connection('url') + return connection + .getLedgerVersion() + .then(() => { + assert(false, 'Should throw NotConnectedError') + }) + .catch(error => { + assert(error instanceof this.api.errors.NotConnectedError) + }) + }) - it('should throw NotConnectedError if server not responding ', function( - done - ) { + it('should throw NotConnectedError if server not responding ', function(done) { if (isBrowser) { - const phantomTest = /PhantomJS/; + const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } // Address where no one listens - const connection = - new utils.common.Connection('ws://testripple.circleci.com:129'); - connection.on('error', done); + const connection = new utils.common.Connection( + 'ws://testripple.circleci.com:129' + ) + connection.on('error', done) connection.connect().catch(error => { - assert(error instanceof this.api.errors.NotConnectedError); - done(); - }); - }); + assert(error instanceof this.api.errors.NotConnectedError) + done() + }) + }) it('DisconnectedError', function() { - this.api.connection._send(JSON.stringify({ - command: 'config', - data: {disconnectOnServerInfo: true} - })); - return this.api.getServerInfo().then(() => { - assert(false, 'Should throw DisconnectedError'); - }).catch(error => { - assert(error instanceof this.api.errors.DisconnectedError); - }); - }); + this.api.connection._send( + JSON.stringify({ + command: 'config', + data: {disconnectOnServerInfo: true} + }) + ) + return this.api + .getServerInfo() + .then(() => { + assert(false, 'Should throw DisconnectedError') + }) + .catch(error => { + assert(error instanceof this.api.errors.DisconnectedError) + }) + }) it('TimeoutError', function() { this.api.connection._send = function() { - return Promise.resolve({}); - }; - const request = {command: 'server_info'}; - return this.api.connection.request(request, 1).then(() => { - assert(false, 'Should throw TimeoutError'); - }).catch(error => { - assert(error instanceof this.api.errors.TimeoutError); - }); - }); + return Promise.resolve({}) + } + const request = {command: 'server_info'} + return this.api.connection + .request(request, 1) + .then(() => { + assert(false, 'Should throw TimeoutError') + }) + .catch(error => { + assert(error instanceof this.api.errors.TimeoutError) + }) + }) it('DisconnectedError on send', function() { this.api.connection._ws.send = function(message, options, callback) { - callback({message: 'not connected'}); - }; - return this.api.getServerInfo().then(() => { - assert(false, 'Should throw DisconnectedError'); - }).catch(error => { - assert(error instanceof this.api.errors.DisconnectedError); - assert.strictEqual(error.message, 'not connected'); - }); - }); + callback({message: 'not connected'}) + } + return this.api + .getServerInfo() + .then(() => { + assert(false, 'Should throw DisconnectedError') + }) + .catch(error => { + assert(error instanceof this.api.errors.DisconnectedError) + assert.strictEqual(error.message, 'not connected') + }) + }) it('ResponseFormatError', function() { this.api.connection._send = function(message) { - const parsed = JSON.parse(message); + const parsed = JSON.parse(message) setTimeout(() => { - this._ws.emit('message', JSON.stringify({ - id: parsed.id, - type: 'response', - status: 'unrecognized' - })); - }, 2); - return new Promise(() => {}); - }; - return this.api.getServerInfo().then(() => { - assert(false, 'Should throw ResponseFormatError'); - }).catch(error => { - assert(error instanceof this.api.errors.ResponseFormatError); - }); - }); + this._ws.emit( + 'message', + JSON.stringify({ + id: parsed.id, + type: 'response', + status: 'unrecognized' + }) + ) + }, 2) + return new Promise(() => {}) + } + return this.api + .getServerInfo() + .then(() => { + assert(false, 'Should throw ResponseFormatError') + }) + .catch(error => { + assert(error instanceof this.api.errors.ResponseFormatError) + }) + }) it('reconnect on unexpected close ', function(done) { this.api.connection.on('connected', () => { - done(); - }); + done() + }) setTimeout(() => { - this.api.connection._ws.close(); - }, 1); - }); + this.api.connection._ws.close() + }, 1) + }) describe('reconnection test', function() { beforeEach(function() { - this.api.connection.__workingUrl = this.api.connection._url; + this.api.connection.__workingUrl = this.api.connection._url this.api.connection.__doReturnBad = function() { - this._url = this.__badUrl; - const self = this; + this._url = this.__badUrl + const self = this function onReconnect(num) { if (num >= 2) { - self._url = self.__workingUrl; - self.removeListener('reconnecting', onReconnect); + self._url = self.__workingUrl + self.removeListener('reconnecting', onReconnect) } } - this.on('reconnecting', onReconnect); - }; - }); + this.on('reconnecting', onReconnect) + } + }) - afterEach(function() { - - }); + afterEach(function() {}) it('reconnect on several unexpected close', function(done) { if (isBrowser) { - const phantomTest = /PhantomJS/; + const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } - this.timeout(70001); - const self = this; - self.api.connection.__badUrl = 'ws://testripple.circleci.com:129'; + this.timeout(70001) + const self = this + self.api.connection.__badUrl = 'ws://testripple.circleci.com:129' function breakConnection() { - self.api.connection.__doReturnBad(); - self.api.connection._send(JSON.stringify({ - command: 'test_command', - data: {disconnectIn: 10} - })); + self.api.connection.__doReturnBad() + self.api.connection._send( + JSON.stringify({ + command: 'test_command', + data: {disconnectIn: 10} + }) + ) } - let connectsCount = 0; - let disconnectsCount = 0; - let reconnectsCount = 0; - let code = 0; + let connectsCount = 0 + let disconnectsCount = 0 + let reconnectsCount = 0 + let code = 0 this.api.connection.on('reconnecting', () => { - reconnectsCount += 1; - }); + reconnectsCount += 1 + }) this.api.connection.on('disconnected', _code => { - code = _code; - disconnectsCount += 1; - }); - const num = 3; + code = _code + disconnectsCount += 1 + }) + const num = 3 this.api.connection.on('connected', () => { - connectsCount += 1; + connectsCount += 1 if (connectsCount < num) { - breakConnection(); + breakConnection() } if (connectsCount === num) { if (disconnectsCount !== num) { - done(new Error('disconnectsCount must be equal to ' + num + - '(got ' + disconnectsCount + ' instead)')); + done( + new Error( + 'disconnectsCount must be equal to ' + + num + + '(got ' + + disconnectsCount + + ' instead)' + ) + ) } else if (reconnectsCount !== num * 2) { - done(new Error('reconnectsCount must be equal to ' + num * 2 + - ' (got ' + reconnectsCount + ' instead)')); + done( + new Error( + 'reconnectsCount must be equal to ' + + num * 2 + + ' (got ' + + reconnectsCount + + ' instead)' + ) + ) } else if (code !== 1006) { - done(new Error('disconnect must send code 1006 (got ' + code + - ' instead)')); + done( + new Error( + 'disconnect must send code 1006 (got ' + code + ' instead)' + ) + ) } else { - done(); + done() } } - }); + }) - breakConnection(); - }); - }); + breakConnection() + }) + }) it('reconnect event on heartbeat failure', function(done) { if (isBrowser) { - const phantomTest = /PhantomJS/; + const phantomTest = /PhantomJS/ if (phantomTest.test(navigator.userAgent)) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } // Set the heartbeat to less than the 1 second ping response - this.api.connection._config.timeout = 500; + this.api.connection._config.timeout = 500 // Drop the test runner timeout, since this should be a quick test - this.timeout(5000); + this.timeout(5000) // Hook up a listener for the reconnect event - this.api.connection.on('reconnect', () => done()); + this.api.connection.on('reconnect', () => done()) // Trigger a heartbeat - this.api.connection._heartbeat(); -}); + this.api.connection._heartbeat() + }) - - 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 => { - assert.strictEqual(code, 1000); - done(); - }); - this.api.disconnect(); - }); + assert.strictEqual(code, 1000) + done() + }) + this.api.disconnect() + }) - 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.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.once('disconnected', code => { - assert.strictEqual(code, 1006); - done(); - }); - this.api.connection._send(JSON.stringify({ - command: 'test_command', - data: {disconnectIn: 10} - })); - }); + assert.strictEqual(code, 1006) + done() + }) + this.api.connection._send( + JSON.stringify({ + command: 'test_command', + data: {disconnectIn: 10} + }) + ) + }) it('should emit connected event on after reconnect', function(done) { - this.api.once('connected', done); - this.api.connection._ws.close(); - }); + this.api.once('connected', done) + this.api.connection._ws.close() + }) it('Multiply connect calls', function() { return this.api.connect().then(() => { - return this.api.connect(); - }); - }); + return this.api.connect() + }) + }) it('hasLedgerVersion', function() { return this.api.connection.hasLedgerVersion(8819951).then(result => { - assert(result); - }); - }); + assert(result) + }) + }) it('Cannot connect because no server', function() { - const connection = new utils.common.Connection(undefined as string); - return connection.connect().then(() => { - assert(false, 'Should throw ConnectionError'); - }).catch(error => { - assert(error instanceof this.api.errors.ConnectionError, 'Should throw ConnectionError'); - }); - }); + const connection = new utils.common.Connection(undefined as string) + return connection + .connect() + .then(() => { + assert(false, 'Should throw ConnectionError') + }) + .catch(error => { + assert( + error instanceof this.api.errors.ConnectionError, + 'Should throw ConnectionError' + ) + }) + }) it('connect multiserver error', function() { assert.throws(function() { - new RippleAPI({servers: ['wss://server1.com', 'wss://server2.com']} as any); - }, this.api.errors.RippleError); - }); + new RippleAPI({ + servers: ['wss://server1.com', 'wss://server2.com'] + } as any) + }, this.api.errors.RippleError) + }) it('connect throws error', function(done) { this.api.once('error', (type, info) => { - assert.strictEqual(type, 'type'); - assert.strictEqual(info, 'info'); - done(); - }); - this.api.connection.emit('error', 'type', 'info'); - }); + assert.strictEqual(type, 'type') + assert.strictEqual(info, 'info') + done() + }) + this.api.connection.emit('error', 'type', 'info') + }) it('emit stream messages', function(done) { - let transactionCount = 0; - let pathFindCount = 0; + let transactionCount = 0 + let pathFindCount = 0 this.api.connection.on('transaction', () => { - transactionCount++; - }); + transactionCount++ + }) this.api.connection.on('path_find', () => { - pathFindCount++; - }); + pathFindCount++ + }) this.api.connection.on('1', () => { - assert.strictEqual(transactionCount, 1); - assert.strictEqual(pathFindCount, 1); - done(); - }); + assert.strictEqual(transactionCount, 1) + assert.strictEqual(pathFindCount, 1) + done() + }) - this.api.connection._onMessage(JSON.stringify({ - type: 'transaction' - })); - this.api.connection._onMessage(JSON.stringify({ - type: 'path_find' - })); - this.api.connection._onMessage(JSON.stringify({ - type: 'response', id: 1 - })); - }); + this.api.connection._onMessage( + JSON.stringify({ + type: 'transaction' + }) + ) + this.api.connection._onMessage( + JSON.stringify({ + type: 'path_find' + }) + ) + this.api.connection._onMessage( + JSON.stringify({ + type: 'response', + id: 1 + }) + ) + }) it('invalid message id', function(done) { this.api.on('error', (errorCode, errorMessage, message) => { - assert.strictEqual(errorCode, 'badMessage'); - assert.strictEqual(errorMessage, 'valid id not found in response'); - assert.strictEqual(message, - '{"type":"response","id":"must be integer"}'); - done(); - }); - this.api.connection._onMessage(JSON.stringify({ - type: 'response', id: 'must be integer' - })); - }); + assert.strictEqual(errorCode, 'badMessage') + assert.strictEqual(errorMessage, 'valid id not found in response') + assert.strictEqual(message, '{"type":"response","id":"must be integer"}') + done() + }) + this.api.connection._onMessage( + JSON.stringify({ + type: 'response', + id: 'must be integer' + }) + ) + }) it('propagates error message', function(done) { this.api.on('error', (errorCode, errorMessage, data) => { - assert.strictEqual(errorCode, 'slowDown'); - assert.strictEqual(errorMessage, 'slow down'); - assert.deepEqual(data, {error: 'slowDown', error_message: 'slow down'}); - done(); - }); - this.api.connection._onMessage(JSON.stringify({ - error: 'slowDown', error_message: 'slow down' - })); - }); + assert.strictEqual(errorCode, 'slowDown') + assert.strictEqual(errorMessage, 'slow down') + assert.deepEqual(data, {error: 'slowDown', error_message: 'slow down'}) + done() + }) + this.api.connection._onMessage( + JSON.stringify({ + error: 'slowDown', + error_message: 'slow down' + }) + ) + }) it('propagates RippledError data', function(done) { this.api.request('subscribe', {streams: 'validations'}).catch(error => { @@ -434,76 +492,96 @@ describe('Connection', function() { assert.strictEqual(error.message, 'Invalid parameters.') assert.strictEqual(error.data.error_code, 31) assert.strictEqual(error.data.error_message, 'Invalid parameters.') - assert.deepEqual(error.data.request, { command: 'subscribe', id: 0, streams: 'validations' }) + assert.deepEqual(error.data.request, { + command: 'subscribe', + id: 0, + streams: 'validations' + }) assert.strictEqual(error.data.status, 'error') assert.strictEqual(error.data.type, 'response') done() }) - }); + }) it('unrecognized message type', function(done) { // This enables us to automatically support any // new messages added by rippled in the future. - this.api.connection.on('unknown', (event) => { + this.api.connection.on('unknown', event => { assert.deepEqual(event, {type: 'unknown'}) - done(); - }); + done() + }) - this.api.connection._onMessage(JSON.stringify({type: 'unknown'})); - }); + this.api.connection._onMessage(JSON.stringify({type: 'unknown'})) + }) it('ledger close without validated_ledgers', function(done) { - const message = _.omit(ledgerClose, 'validated_ledgers'); + const message = _.omit(ledgerClose, 'validated_ledgers') this.api.on('ledger', function(ledger) { - assert.strictEqual(ledger.ledgerVersion, 8819951); - done(); - }); - this.api.connection._ws.emit('message', JSON.stringify(message)); - }); + assert.strictEqual(ledger.ledgerVersion, 8819951) + done() + }) + this.api.connection._ws.emit('message', JSON.stringify(message)) + }) - it('should throw RippledNotInitializedError if server does not have ' + - 'validated ledgers', function() { + it( + 'should throw RippledNotInitializedError if server does not have ' + + 'validated ledgers', + function() { + this.timeout(3000) - this.timeout(3000); + this.api.connection._send( + JSON.stringify({ + command: 'global_config', + data: {returnEmptySubscribeRequest: 1} + }) + ) - this.api.connection._send(JSON.stringify({ - command: 'global_config', - data: {returnEmptySubscribeRequest: 1} - })); + const api = new RippleAPI({server: this.api.connection._url}) + return api.connect().then( + () => { + assert(false, 'Must have thrown!') + }, + error => { + assert( + error instanceof this.api.errors.RippledNotInitializedError, + 'Must throw RippledNotInitializedError, got instead ' + + String(error) + ) + } + ) + } + ) - const api = new RippleAPI({server: this.api.connection._url}); - return api.connect().then(() => { - assert(false, 'Must have thrown!'); - }, error => { - assert(error instanceof this.api.errors.RippledNotInitializedError, - 'Must throw RippledNotInitializedError, got instead ' + String(error)); - }); - }); - - it('should try to reconnect on empty subscribe response on reconnect', - function(done) { - this.timeout(23000); + it('should try to reconnect on empty subscribe response on reconnect', function(done) { + this.timeout(23000) this.api.on('error', error => { - done(error || new Error('Should not emit error.')); - }); - let disconnectedCount = 0; + done(error || new Error('Should not emit error.')) + }) + let disconnectedCount = 0 this.api.on('connected', () => { - done(disconnectedCount !== 1 ? - new Error('Wrong number of disconnects') : undefined); - }); + done( + disconnectedCount !== 1 + ? new Error('Wrong number of disconnects') + : undefined + ) + }) this.api.on('disconnected', () => { - disconnectedCount++; - }); + disconnectedCount++ + }) - this.api.connection._send(JSON.stringify({ - command: 'global_config', - data: {returnEmptySubscribeRequest: 3} - })); + this.api.connection._send( + JSON.stringify({ + command: 'global_config', + data: {returnEmptySubscribeRequest: 3} + }) + ) - this.api.connection._send(JSON.stringify({ - command: 'test_command', - data: {disconnectIn: 10} - })); - }); -}); + this.api.connection._send( + JSON.stringify({ + command: 'test_command', + data: {disconnectIn: 10} + }) + ) + }) +}) diff --git a/test/hashes-test.ts b/test/hashes-test.ts index 75c2cba7..5bfcd0c5 100644 --- a/test/hashes-test.ts +++ b/test/hashes-test.ts @@ -1,123 +1,152 @@ -import assert from 'assert'; -import fs from 'fs'; -import * as hashes from '../src/common/hashes'; +import assert from 'assert' +import fs from 'fs' +import * as hashes from '../src/common/hashes' /** -* Expects a corresponding ledger dump in $repo/test/fixtures/rippled folder -*/ + * Expects a corresponding ledger dump in $repo/test/fixtures/rippled folder + */ function createLedgerTest(ledgerIndex: number) { describe(String(ledgerIndex), function() { - var path = __dirname + '/fixtures/rippled/ledger-full-' + ledgerIndex + '.json'; + var path = + __dirname + '/fixtures/rippled/ledger-full-' + ledgerIndex + '.json' - var ledgerRaw = fs.readFileSync(path, {encoding: 'utf8'}); - var ledgerJSON = JSON.parse(ledgerRaw); + var ledgerRaw = fs.readFileSync(path, {encoding: 'utf8'}) + var ledgerJSON = JSON.parse(ledgerRaw) - var hasAccounts = Array.isArray(ledgerJSON.accountState) - && ledgerJSON.accountState.length > 0; + var hasAccounts = + Array.isArray(ledgerJSON.accountState) && + ledgerJSON.accountState.length > 0 if (hasAccounts) { it('has account_hash of ' + ledgerJSON.account_hash, function() { - assert.equal(ledgerJSON.account_hash, - hashes.computeStateTreeHash(ledgerJSON.accountState)); - }); + assert.equal( + ledgerJSON.account_hash, + hashes.computeStateTreeHash(ledgerJSON.accountState) + ) + }) } it('has transaction_hash of ' + ledgerJSON.transaction_hash, function() { - assert.equal(ledgerJSON.transaction_hash, - hashes.computeTransactionTreeHash(ledgerJSON.transactions)); - }); - }); + assert.equal( + ledgerJSON.transaction_hash, + hashes.computeTransactionTreeHash(ledgerJSON.transactions) + ) + }) + }) } describe('Ledger', function() { // This is the first recorded ledger with a non empty transaction set - createLedgerTest(38129); + createLedgerTest(38129) // Because, why not. - createLedgerTest(40000); + createLedgerTest(40000) // 1311 AffectedNodes, no accounts - createLedgerTest(7501326); + createLedgerTest(7501326) describe('calcAccountRootEntryHash', function() { it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function() { - var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'; - var expectedEntryHash = '2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8'; - var actualEntryHash = hashes.computeAccountHash(account); + var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' + var expectedEntryHash = + '2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8' + var actualEntryHash = hashes.computeAccountHash(account) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) describe('calcRippleStateEntryHash', function() { it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function() { - var account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'; - var account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY'; - var currency = 'USD'; + var account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' + var account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY' + var currency = 'USD' - var expectedEntryHash = 'C683B5BB928F025F1E860D9D69D6C554C2202DE0D45877ADB3077DA4CB9E125C'; + var expectedEntryHash = + 'C683B5BB928F025F1E860D9D69D6C554C2202DE0D45877ADB3077DA4CB9E125C' var actualEntryHash1 = hashes.computeTrustlineHash( - account1, account2, currency); + account1, + account2, + currency + ) var actualEntryHash2 = hashes.computeTrustlineHash( - account2, account1, currency); + account2, + account1, + currency + ) - assert.equal(actualEntryHash1, expectedEntryHash); - assert.equal(actualEntryHash2, expectedEntryHash); - }); + assert.equal(actualEntryHash1, expectedEntryHash) + assert.equal(actualEntryHash2, expectedEntryHash) + }) it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function() { - var account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV'; - var account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj'; - var currency = 'UAM'; + var account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV' + var account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj' + var currency = 'UAM' - var expectedEntryHash = 'AE9ADDC584358E5847ADFC971834E471436FC3E9DE6EA1773DF49F419DC0F65E'; + var expectedEntryHash = + 'AE9ADDC584358E5847ADFC971834E471436FC3E9DE6EA1773DF49F419DC0F65E' var actualEntryHash1 = hashes.computeTrustlineHash( - account1, account2, currency); + account1, + account2, + currency + ) var actualEntryHash2 = hashes.computeTrustlineHash( - account2, account1, currency); + account2, + account1, + currency + ) - assert.equal(actualEntryHash1, expectedEntryHash); - assert.equal(actualEntryHash2, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash1, expectedEntryHash) + assert.equal(actualEntryHash2, expectedEntryHash) + }) + }) describe('calcOfferEntryHash', function() { it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function() { - var account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw'; - var sequence = 137; - var expectedEntryHash = '03F0AED09DEEE74CEF85CD57A0429D6113507CF759C597BABB4ADB752F734CE3'; - var actualEntryHash = hashes.computeOrderHash(account, sequence); + var account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw' + var sequence = 137 + var expectedEntryHash = + '03F0AED09DEEE74CEF85CD57A0429D6113507CF759C597BABB4ADB752F734CE3' + var actualEntryHash = hashes.computeOrderHash(account, sequence) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) describe('computeSignerListHash', function() { it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function() { - var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'; - var expectedEntryHash = '778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF'; - var actualEntryHash = hashes.computeSignerListHash(account); - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' + var expectedEntryHash = + '778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF' + var actualEntryHash = hashes.computeSignerListHash(account) + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) describe('calcEscrowEntryHash', function() { it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function() { - var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x'; - var sequence = 84; - var expectedEntryHash = '61E8E8ED53FA2CEBE192B23897071E9A75217BF5A410E9CB5B45AAB7AECA567A'; - var actualEntryHash = hashes.computeEscrowHash(account, sequence); + var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' + var sequence = 84 + var expectedEntryHash = + '61E8E8ED53FA2CEBE192B23897071E9A75217BF5A410E9CB5B45AAB7AECA567A' + var actualEntryHash = hashes.computeEscrowHash(account, sequence) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) describe('calcPaymentChannelEntryHash', function() { it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function() { - var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x'; + var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' var dstAccount = 'rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso' - var sequence = 82; - var expectedEntryHash = 'E35708503B3C3143FB522D749AAFCC296E8060F0FB371A9A56FAE0B1ED127366'; - var actualEntryHash = hashes.computePaymentChannelHash(account, dstAccount, sequence); + var sequence = 82 + var expectedEntryHash = + 'E35708503B3C3143FB522D749AAFCC296E8060F0FB371A9A56FAE0B1ED127366' + var actualEntryHash = hashes.computePaymentChannelHash( + account, + dstAccount, + sequence + ) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); -}); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) +}) diff --git a/test/integration/broadcast-test.ts b/test/integration/broadcast-test.ts index 61fefc31..11da1dd4 100644 --- a/test/integration/broadcast-test.ts +++ b/test/integration/broadcast-test.ts @@ -1,16 +1,16 @@ -import {RippleAPIBroadcast} from '../../src'; +import {RippleAPIBroadcast} from '../../src' function main() { - const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com']; - const api = new RippleAPIBroadcast(servers); + const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com'] + const api = new RippleAPIBroadcast(servers) api.connect().then(() => { api.getServerInfo().then(info => { - console.log(JSON.stringify(info, null, 2)); - }); + console.log(JSON.stringify(info, null, 2)) + }) api.on('ledger', ledger => { - console.log(JSON.stringify(ledger, null, 2)); - }); - }); + console.log(JSON.stringify(ledger, null, 2)) + }) + }) } -main(); +main() diff --git a/test/integration/connection-test.ts b/test/integration/connection-test.ts index 20ebbc4d..3a590bdc 100644 --- a/test/integration/connection-test.ts +++ b/test/integration/connection-test.ts @@ -1,53 +1,56 @@ -import Connection from '../../src/common/connection'; +import Connection from '../../src/common/connection' const request1 = { command: 'server_info' -}; +} const request2 = { command: 'account_info', account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59' -}; +} const request3 = { command: 'account_info' -}; +} const request4 = { command: 'account_info', account: 'invalid' -}; +} function makeRequest(connection, request) { - return connection.request(request).then((response) => { - console.log(request); - console.log(JSON.stringify(response, null, 2)); - }).catch((error) => { - console.log(request); - console.log(error); - }); + return connection + .request(request) + .then(response => { + console.log(request) + console.log(JSON.stringify(response, null, 2)) + }) + .catch(error => { + console.log(request) + console.log(error) + }) } function main() { - const connection = new Connection('wss://s1.ripple.com'); + const connection = new Connection('wss://s1.ripple.com') connection.connect().then(() => { - console.log('Connected'); + console.log('Connected') Promise.all([ makeRequest(connection, request1), makeRequest(connection, request2), makeRequest(connection, request3), makeRequest(connection, request4) ]).then(() => { - console.log('Done'); - }); - connection.getLedgerVersion().then(console.log); + console.log('Done') + }) + connection.getLedgerVersion().then(console.log) connection.on('ledgerClosed', ledger => { - console.log(ledger); - connection.getLedgerVersion().then(console.log); - }); - connection.hasLedgerVersions(1, 100).then(console.log); - connection.hasLedgerVersions(16631039, 16631040).then(console.log); - }); + console.log(ledger) + connection.getLedgerVersion().then(console.log) + }) + connection.hasLedgerVersions(1, 100).then(console.log) + connection.hasLedgerVersions(16631039, 16631040).then(console.log) + }) } -main(); +main() diff --git a/test/integration/integration-test.ts b/test/integration/integration-test.ts index bd5a4953..7117d290 100644 --- a/test/integration/integration-test.ts +++ b/test/integration/integration-test.ts @@ -1,116 +1,154 @@ -import _ from 'lodash'; -import assert from 'assert'; -import wallet from './wallet'; -import requests from '../fixtures/requests'; -import {RippleAPI} from 'ripple-api'; -import {isValidAddress} from 'ripple-address-codec'; -import {payTo, ledgerAccept} from './utils'; -import {errors} from 'ripple-api/common'; -import {isValidSecret} from 'ripple-api/common/utils'; - +import _ from 'lodash' +import assert from 'assert' +import wallet from './wallet' +import requests from '../fixtures/requests' +import {RippleAPI} from 'ripple-api' +import {isValidAddress} from 'ripple-address-codec' +import {payTo, ledgerAccept} from './utils' +import {errors} from 'ripple-api/common' +import {isValidSecret} from 'ripple-api/common/utils' // how long before each test case times out -const TIMEOUT = 20000; -const INTERVAL = 1000; // how long to wait between checks for validated ledger +const TIMEOUT = 20000 +const INTERVAL = 1000 // how long to wait between checks for validated ledger -const serverUrl = 'ws://127.0.0.1:6006'; +const serverUrl = 'ws://127.0.0.1:6006' function acceptLedger(api) { - return api.connection.request({command: 'ledger_accept'}); + return api.connection.request({command: 'ledger_accept'}) } function verifyTransaction(testcase, hash, type, options, txData, address) { - console.log('VERIFY...'); - return testcase.api.getTransaction(hash, options).then(data => { - assert(data && data.outcome); - assert.strictEqual(data.type, type); - assert.strictEqual(data.address, address); - assert.strictEqual(data.outcome.result, 'tesSUCCESS'); - if (testcase.transactions !== undefined) { - testcase.transactions.push(hash); - } - return {txJSON: JSON.stringify(txData), id: hash, tx: data}; - }).catch(error => { - if (error instanceof errors.PendingLedgerVersionError) { - console.log('NOT VALIDATED YET...'); - return new Promise((resolve, reject) => { - setTimeout(() => verifyTransaction(testcase, hash, type, - options, txData, address).then(resolve, reject), INTERVAL); - }); - } - console.log(error.stack); - assert(false, 'Transaction not successful: ' + error.message); - }); + console.log('VERIFY...') + return testcase.api + .getTransaction(hash, options) + .then(data => { + assert(data && data.outcome) + assert.strictEqual(data.type, type) + assert.strictEqual(data.address, address) + assert.strictEqual(data.outcome.result, 'tesSUCCESS') + if (testcase.transactions !== undefined) { + testcase.transactions.push(hash) + } + return {txJSON: JSON.stringify(txData), id: hash, tx: data} + }) + .catch(error => { + if (error instanceof errors.PendingLedgerVersionError) { + console.log('NOT VALIDATED YET...') + return new Promise((resolve, reject) => { + setTimeout( + () => + verifyTransaction( + testcase, + hash, + type, + options, + txData, + address + ).then(resolve, reject), + INTERVAL + ) + }) + } + console.log(error.stack) + assert(false, 'Transaction not successful: ' + error.message) + }) } -function testTransaction(testcase, type, lastClosedLedgerVersion, prepared, - address = wallet.getAddress(), secret = wallet.getSecret()) { - const txJSON = prepared.txJSON; - assert(txJSON, 'missing txJSON'); - const txData = JSON.parse(txJSON); - assert.strictEqual(txData.Account, address); - const signedData = testcase.api.sign(txJSON, secret); - console.log('PREPARED...'); - return testcase.api.submit(signedData.signedTransaction) - .then(data => testcase.test.title.indexOf('multisign') !== -1 ? - acceptLedger(testcase.api).then(() => data) : data).then(data => { - console.log('SUBMITTED...'); - assert.strictEqual(data.resultCode, 'tesSUCCESS'); - const options = { - minLedgerVersion: lastClosedLedgerVersion, - maxLedgerVersion: txData.LastLedgerSequence - }; - ledgerAccept(testcase.api); - return new Promise((resolve, reject) => { - setTimeout(() => verifyTransaction(testcase, signedData.id, type, - options, txData, address).then(resolve, reject), INTERVAL); - }); - }); +function testTransaction( + testcase, + type, + lastClosedLedgerVersion, + prepared, + address = wallet.getAddress(), + secret = wallet.getSecret() +) { + const txJSON = prepared.txJSON + assert(txJSON, 'missing txJSON') + const txData = JSON.parse(txJSON) + assert.strictEqual(txData.Account, address) + const signedData = testcase.api.sign(txJSON, secret) + console.log('PREPARED...') + return testcase.api + .submit(signedData.signedTransaction) + .then(data => + testcase.test.title.indexOf('multisign') !== -1 + ? acceptLedger(testcase.api).then(() => data) + : data + ) + .then(data => { + console.log('SUBMITTED...') + assert.strictEqual(data.resultCode, 'tesSUCCESS') + const options = { + minLedgerVersion: lastClosedLedgerVersion, + maxLedgerVersion: txData.LastLedgerSequence + } + ledgerAccept(testcase.api) + return new Promise((resolve, reject) => { + setTimeout( + () => + verifyTransaction( + testcase, + signedData.id, + type, + options, + txData, + address + ).then(resolve, reject), + INTERVAL + ) + }) + }) } function setup(this: any, server = 'wss://s1.ripple.com') { - this.api = new RippleAPI({server}); - console.log('CONNECTING...'); - return this.api.connect().then(() => { - console.log('CONNECTED...'); - }, error => { - console.log('ERROR:', error); - throw error; - }); + this.api = new RippleAPI({server}) + console.log('CONNECTING...') + return this.api.connect().then( + () => { + console.log('CONNECTED...') + }, + error => { + console.log('ERROR:', error) + throw error + } + ) } -const masterAccount = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'; -const masterSecret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb'; +const masterAccount = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' +const masterSecret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' function makeTrustLine(testcase, address, secret) { - const api = testcase.api; + const api = testcase.api const specification = { currency: 'USD', counterparty: masterAccount, limit: '1341.1', ripplingDisabled: true - }; - const trust = api.prepareTrustline(address, specification, {}) + } + const trust = api + .prepareTrustline(address, specification, {}) .then(data => { - const signed = api.sign(data.txJSON, secret); + const signed = api.sign(data.txJSON, secret) if (address === wallet.getAddress()) { - testcase.transactions.push(signed.id); + testcase.transactions.push(signed.id) } - return api.submit(signed.signedTransaction); + return api.submit(signed.signedTransaction) }) - .then(() => ledgerAccept(api)); - return trust; + .then(() => ledgerAccept(api)) + return trust } function makeOrder(api, address, specification, secret) { - return api.prepareOrder(address, specification) + return api + .prepareOrder(address, specification) .then(data => api.sign(data.txJSON, secret)) .then(signed => api.submit(signed.signedTransaction)) - .then(() => ledgerAccept(api)); + .then(() => ledgerAccept(api)) } function setupAccounts(testcase) { - const api = testcase.api; + const api = testcase.api const promise = payTo(api, 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM') .then(() => payTo(api, wallet.getAddress())) @@ -118,15 +156,22 @@ function setupAccounts(testcase) { .then(() => payTo(api, 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc')) .then(() => payTo(api, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { - return api.prepareSettings(masterAccount, {defaultRipple: true}) - .then(data => api.sign(data.txJSON, masterSecret)) - .then(signed => api.submit(signed.signedTransaction)) - .then(() => ledgerAccept(api)); + return api + .prepareSettings(masterAccount, {defaultRipple: true}) + .then(data => api.sign(data.txJSON, masterSecret)) + .then(signed => api.submit(signed.signedTransaction)) + .then(() => ledgerAccept(api)) }) - .then(() => makeTrustLine(testcase, wallet.getAddress(), - wallet.getSecret())) - .then(() => makeTrustLine(testcase, testcase.newWallet.address, - testcase.newWallet.secret)) + .then(() => + makeTrustLine(testcase, wallet.getAddress(), wallet.getSecret()) + ) + .then(() => + makeTrustLine( + testcase, + testcase.newWallet.address, + testcase.newWallet.secret + ) + ) .then(() => payTo(api, wallet.getAddress(), '123', 'USD', masterAccount)) .then(() => payTo(api, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { @@ -141,9 +186,13 @@ function setupAccounts(testcase) { currency: 'XRP', value: '432' } - }; - return makeOrder(testcase.api, testcase.newWallet.address, - orderSpecification, testcase.newWallet.secret); + } + return makeOrder( + testcase.api, + testcase.newWallet.address, + orderSpecification, + testcase.newWallet.secret + ) }) .then(() => { const orderSpecification = { @@ -157,64 +206,76 @@ function setupAccounts(testcase) { value: '171', counterparty: masterAccount } - }; - return makeOrder(testcase.api, masterAccount, orderSpecification, - masterSecret); - }); - return promise; + } + return makeOrder( + testcase.api, + masterAccount, + orderSpecification, + masterSecret + ) + }) + return promise } function teardown(this: any) { - return this.api.disconnect(); + return this.api.disconnect() } function suiteSetup(this: any) { - this.transactions = []; + this.transactions = [] - return setup.bind(this)(serverUrl) - .then(() => ledgerAccept(this.api)) - .then(() => this.newWallet = this.api.generateAddress()) - // two times to give time to server to send `ledgerClosed` event - // so getLedgerVersion will return right value - .then(() => ledgerAccept(this.api)) - .then(() => this.api.getLedgerVersion()) - .then(ledgerVersion => { - this.startLedgerVersion = ledgerVersion; - }) - .then(() => setupAccounts(this)) - .then(() => teardown.bind(this)()); + return ( + setup + .bind(this)(serverUrl) + .then(() => ledgerAccept(this.api)) + .then(() => (this.newWallet = this.api.generateAddress())) + // two times to give time to server to send `ledgerClosed` event + // so getLedgerVersion will return right value + .then(() => ledgerAccept(this.api)) + .then(() => this.api.getLedgerVersion()) + .then(ledgerVersion => { + this.startLedgerVersion = ledgerVersion + }) + .then(() => setupAccounts(this)) + .then(() => teardown.bind(this)()) + ) } describe('integration tests', function() { - const address = wallet.getAddress(); - const instructions = {maxLedgerVersionOffset: 10}; - this.timeout(TIMEOUT); - - before(suiteSetup); - beforeEach(_.partial(setup, serverUrl)); - afterEach(teardown); + const address = wallet.getAddress() + const instructions = {maxLedgerVersionOffset: 10} + this.timeout(TIMEOUT) + before(suiteSetup) + beforeEach(_.partial(setup, serverUrl)) + afterEach(teardown) it('settings', function() { return this.api.getLedgerVersion().then(ledgerVersion => { - return this.api.prepareSettings(address, - requests.prepareSettings.domain, instructions).then(prepared => - testTransaction(this, 'settings', ledgerVersion, prepared)); - }); - }); - + return this.api + .prepareSettings(address, requests.prepareSettings.domain, instructions) + .then(prepared => + testTransaction(this, 'settings', ledgerVersion, prepared) + ) + }) + }) it('trustline', function() { return this.api.getLedgerVersion().then(ledgerVersion => { - return this.api.prepareTrustline(address, - requests.prepareTrustline.simple, instructions).then(prepared => - testTransaction(this, 'trustline', ledgerVersion, prepared)); - }); - }); - + return this.api + .prepareTrustline( + address, + requests.prepareTrustline.simple, + instructions + ) + .then(prepared => + testTransaction(this, 'trustline', ledgerVersion, prepared) + ) + }) + }) it('payment', function() { - const amount = {currency: 'XRP', value: '0.000001'}; + const amount = {currency: 'XRP', value: '0.000001'} const paymentSpecification = { source: { address: address, @@ -224,14 +285,15 @@ describe('integration tests', function() { address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc', amount: amount } - }; + } return this.api.getLedgerVersion().then(ledgerVersion => { - return this.api.preparePayment(address, - paymentSpecification, instructions).then(prepared => - testTransaction(this, 'payment', ledgerVersion, prepared)); - }); - }); - + return this.api + .preparePayment(address, paymentSpecification, instructions) + .then(prepared => + testTransaction(this, 'payment', ledgerVersion, prepared) + ) + }) + }) it('order', function() { const orderSpecification = { @@ -245,105 +307,111 @@ describe('integration tests', function() { currency: 'XRP', value: '0.0002' } - }; + } return this.api.getLedgerVersion().then(ledgerVersion => { - return this.api.prepareOrder(address, orderSpecification, instructions) + return this.api + .prepareOrder(address, orderSpecification, instructions) .then(prepared => - testTransaction(this, 'order', ledgerVersion, prepared)) + testTransaction(this, 'order', ledgerVersion, prepared) + ) .then(result => { - const txData = JSON.parse(result.txJSON); + const txData = JSON.parse(result.txJSON) return this.api.getOrders(address).then(orders => { - assert(orders && orders.length > 0); - const createdOrder = _.first(_.filter(orders, order => { - return order.properties.sequence === txData.Sequence; - })); - assert(createdOrder); - assert.strictEqual(createdOrder.properties.maker, address); - assert.deepEqual(createdOrder.specification, orderSpecification); - return txData; - }); + assert(orders && orders.length > 0) + const createdOrder = _.first( + _.filter(orders, order => { + return order.properties.sequence === txData.Sequence + }) + ) + assert(createdOrder) + assert.strictEqual(createdOrder.properties.maker, address) + assert.deepEqual(createdOrder.specification, orderSpecification) + return txData + }) }) - .then(txData => this.api.prepareOrderCancellation( - address, {orderSequence: txData.Sequence}, instructions) - .then(prepared => testTransaction(this, 'orderCancellation', - ledgerVersion, prepared)) - ); - }); - }); - + .then(txData => + this.api + .prepareOrderCancellation( + address, + {orderSequence: txData.Sequence}, + instructions + ) + .then(prepared => + testTransaction( + this, + 'orderCancellation', + ledgerVersion, + prepared + ) + ) + ) + }) + }) it('isConnected', function() { - assert(this.api.isConnected()); - }); - + assert(this.api.isConnected()) + }) it('getServerInfo', function() { return this.api.getServerInfo().then(data => { - assert(data && data.pubkeyNode); - }); - }); - + assert(data && data.pubkeyNode) + }) + }) it('getFee', function() { return this.api.getFee().then(fee => { - assert.strictEqual(typeof fee, 'string'); - assert(!isNaN(Number(fee))); - assert(parseFloat(fee) === Number(fee)); - }); - }); - + assert.strictEqual(typeof fee, 'string') + assert(!isNaN(Number(fee))) + assert(parseFloat(fee) === Number(fee)) + }) + }) it('getLedgerVersion', function() { return this.api.getLedgerVersion().then(ledgerVersion => { - assert.strictEqual(typeof ledgerVersion, 'number'); - assert(ledgerVersion >= this.startLedgerVersion); - }); - }); - + assert.strictEqual(typeof ledgerVersion, 'number') + assert(ledgerVersion >= this.startLedgerVersion) + }) + }) it('getTransactions', function() { const options = { initiated: true, minLedgerVersion: this.startLedgerVersion - }; + } return this.api.getTransactions(address, options).then(transactionsData => { - assert(transactionsData); - assert.strictEqual(transactionsData.length, this.transactions.length); - }); - }); - + assert(transactionsData) + assert.strictEqual(transactionsData.length, this.transactions.length) + }) + }) it('getTrustlines', function() { - const fixture = requests.prepareTrustline.simple; - const options = _.pick(fixture, ['currency', 'counterparty']); + const fixture = requests.prepareTrustline.simple + const options = _.pick(fixture, ['currency', 'counterparty']) 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)); - assert.strictEqual(specification.currency, fixture.currency); - assert.strictEqual(specification.counterparty, fixture.counterparty); - }); - }); - + assert(data && data.length > 0 && data[0] && data[0].specification) + const specification = data[0].specification + assert.strictEqual(Number(specification.limit), Number(fixture.limit)) + assert.strictEqual(specification.currency, fixture.currency) + assert.strictEqual(specification.counterparty, fixture.counterparty) + }) + }) it('getBalances', function() { - const fixture = requests.prepareTrustline.simple; - const options = _.pick(fixture, ['currency', 'counterparty']); + const fixture = requests.prepareTrustline.simple + const options = _.pick(fixture, ['currency', 'counterparty']) 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); - }); - }); - + assert(data && data.length > 0 && data[0]) + assert.strictEqual(data[0].currency, fixture.currency) + assert.strictEqual(data[0].counterparty, fixture.counterparty) + }) + }) it('getSettings', function() { return this.api.getSettings(address).then(data => { - assert(data); - assert.strictEqual(data.domain, requests.prepareSettings.domain.domain); - }); - }); - + assert(data) + assert.strictEqual(data.domain, requests.prepareSettings.domain.domain) + }) + }) it('getOrderbook', function() { const orderbook = { @@ -354,25 +422,24 @@ describe('integration tests', function() { currency: 'USD', counterparty: masterAccount } - }; + } 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]; - assert(bid && bid.specification && bid.specification.quantity); - assert(bid.specification.totalPrice); - assert.strictEqual(bid.specification.direction, 'buy'); - assert.strictEqual(bid.specification.quantity.currency, 'XRP'); - assert.strictEqual(bid.specification.totalPrice.currency, 'USD'); - const ask = book.asks[0]; - assert(ask && ask.specification && ask.specification.quantity); - assert(ask.specification.totalPrice); - assert.strictEqual(ask.specification.direction, 'sell'); - assert.strictEqual(ask.specification.quantity.currency, 'XRP'); - assert.strictEqual(ask.specification.totalPrice.currency, 'USD'); - }); - }); - + assert(book && book.bids && book.bids.length > 0) + assert(book.asks && book.asks.length > 0) + const bid = book.bids[0] + assert(bid && bid.specification && bid.specification.quantity) + assert(bid.specification.totalPrice) + assert.strictEqual(bid.specification.direction, 'buy') + assert.strictEqual(bid.specification.quantity.currency, 'XRP') + assert.strictEqual(bid.specification.totalPrice.currency, 'USD') + const ask = book.asks[0] + assert(ask && ask.specification && ask.specification.quantity) + assert(ask.specification.totalPrice) + assert.strictEqual(ask.specification.direction, 'sell') + assert.strictEqual(ask.specification.quantity.currency, 'XRP') + assert.strictEqual(ask.specification.totalPrice.currency, 'USD') + }) + }) it('getPaths', function() { const pathfind = { @@ -387,16 +454,15 @@ describe('integration tests', function() { counterparty: masterAccount } } - }; + } return this.api.getPaths(pathfind).then(data => { - assert(data && data.length > 0); - const path = data[0]; - assert(path && path.source); - assert.strictEqual(path.source.address, address); - assert(path.paths && path.paths.length > 0); - }); - }); - + assert(data && data.length > 0) + const path = data[0] + assert(path && path.source) + assert.strictEqual(path.source.address, address) + assert(path.paths && path.paths.length > 0) + }) + }) it('getPaths - send all', function() { const pathfind = { @@ -413,43 +479,45 @@ describe('integration tests', function() { currency: 'USD' } } - }; + } return this.api.getPaths(pathfind).then(data => { - assert(data && data.length > 0); - assert(_.every(data, path => { - return parseFloat(path.source.amount.value) - <= parseFloat(pathfind.source.amount.value); - })); - const path = data[0]; - assert(path && path.source); - assert.strictEqual(path.source.address, pathfind.source.address); - assert(path.paths && path.paths.length > 0); - }); - }); - + assert(data && data.length > 0) + assert( + _.every(data, path => { + return ( + parseFloat(path.source.amount.value) <= + parseFloat(pathfind.source.amount.value) + ) + }) + ) + const path = data[0] + assert(path && path.source) + assert.strictEqual(path.source.address, pathfind.source.address) + assert(path.paths && path.paths.length > 0) + }) + }) it('generateWallet', function() { - const newWallet = this.api.generateAddress(); - assert(newWallet && newWallet.address && newWallet.secret); - assert(isValidAddress(newWallet.address)); - assert(isValidSecret(newWallet.secret)); - }); - -}); + const newWallet = this.api.generateAddress() + assert(newWallet && newWallet.address && newWallet.secret) + assert(isValidAddress(newWallet.address)) + assert(isValidSecret(newWallet.secret)) + }) +}) describe('integration tests - standalone rippled', function() { - const instructions = {maxLedgerVersionOffset: 10}; - this.timeout(TIMEOUT); + const instructions = {maxLedgerVersionOffset: 10} + this.timeout(TIMEOUT) - beforeEach(_.partial(setup, serverUrl)); - afterEach(teardown); - const address = 'r5nx8ZkwEbFztnc8Qyi22DE9JYjRzNmvs'; - const secret = 'ss6F8381Br6wwpy9p582H8sBt19J3'; - const signer1address = 'rQDhz2ZNXmhxzCYwxU6qAbdxsHA4HV45Y2'; - const signer1secret = 'shK6YXzwYfnFVn3YZSaMh5zuAddKx'; - const signer2address = 'r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud'; - const signer2secret = 'shUHQnL4EH27V4EiBrj6EfhWvZngF'; + beforeEach(_.partial(setup, serverUrl)) + afterEach(teardown) + const address = 'r5nx8ZkwEbFztnc8Qyi22DE9JYjRzNmvs' + const secret = 'ss6F8381Br6wwpy9p582H8sBt19J3' + const signer1address = 'rQDhz2ZNXmhxzCYwxU6qAbdxsHA4HV45Y2' + const signer1secret = 'shK6YXzwYfnFVn3YZSaMh5zuAddKx' + const signer2address = 'r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud' + const signer2secret = 'shUHQnL4EH27V4EiBrj6EfhWvZngF' it('submit multisigned transaction', function() { const signers = { @@ -458,42 +526,67 @@ describe('integration tests - standalone rippled', function() { {address: signer1address, weight: 1}, {address: signer2address, weight: 1} ] - }; - let minLedgerVersion = null; - return payTo(this.api, address).then(() => { - return this.api.getLedgerVersion().then(ledgerVersion => { - minLedgerVersion = ledgerVersion; - return this.api.prepareSettings(address, {signers}, instructions) - .then(prepared => { - return testTransaction(this, 'settings', ledgerVersion, prepared, - address, secret); - }); - }); - }).then(() => { - const multisignInstructions = - _.assign({}, instructions, {signersCount: 2}); - return this.api.prepareSettings( - address, {domain: 'example.com'}, multisignInstructions) - .then(prepared => { - const signed1 = this.api.sign( - prepared.txJSON, signer1secret, {signAs: signer1address}); - const signed2 = this.api.sign( - prepared.txJSON, signer2secret, {signAs: signer2address}); - const combined = this.api.combine([ - signed1.signedTransaction, signed2.signedTransaction - ]); - return this.api.submit(combined.signedTransaction) - .then(response => acceptLedger(this.api).then(() => response)) - .then(response => { - assert.strictEqual(response.resultCode, 'tesSUCCESS'); - const options = {minLedgerVersion}; - return verifyTransaction(this, combined.id, 'settings', - options, {}, address); - }).catch(error => { - console.log(error.message); - throw error; - }); - }); - }); - }); -}); + } + let minLedgerVersion = null + return payTo(this.api, address) + .then(() => { + return this.api.getLedgerVersion().then(ledgerVersion => { + minLedgerVersion = ledgerVersion + return this.api + .prepareSettings(address, {signers}, instructions) + .then(prepared => { + return testTransaction( + this, + 'settings', + ledgerVersion, + prepared, + address, + secret + ) + }) + }) + }) + .then(() => { + const multisignInstructions = _.assign({}, instructions, { + signersCount: 2 + }) + return this.api + .prepareSettings( + address, + {domain: 'example.com'}, + multisignInstructions + ) + .then(prepared => { + const signed1 = this.api.sign(prepared.txJSON, signer1secret, { + signAs: signer1address + }) + const signed2 = this.api.sign(prepared.txJSON, signer2secret, { + signAs: signer2address + }) + const combined = this.api.combine([ + signed1.signedTransaction, + signed2.signedTransaction + ]) + return this.api + .submit(combined.signedTransaction) + .then(response => acceptLedger(this.api).then(() => response)) + .then(response => { + assert.strictEqual(response.resultCode, 'tesSUCCESS') + const options = {minLedgerVersion} + return verifyTransaction( + this, + combined.id, + 'settings', + options, + {}, + address + ) + }) + .catch(error => { + console.log(error.message) + throw error + }) + }) + }) + }) +}) diff --git a/test/mock-rippled.ts b/test/mock-rippled.ts index e343fbe1..2c6b7a33 100644 --- a/test/mock-rippled.ts +++ b/test/mock-rippled.ts @@ -1,652 +1,753 @@ -import _ from 'lodash'; -import fs from 'fs'; -import assert from 'assert'; -import {Server as WebSocketServer} from 'ws'; -import {EventEmitter2} from 'eventemitter2'; -import fixtures from './fixtures/rippled'; -import addresses from './fixtures/addresses.json'; -import hashes from './fixtures/hashes.json'; -import transactionsResponse from './fixtures/rippled/account-tx'; -import accountLinesResponse from './fixtures/rippled/account-lines'; -import accountObjectsResponse from './fixtures/rippled/account-objects'; -import fullLedger from './fixtures/rippled/ledger-full-38129.json'; -import {getFreePort} from './utils'; +import _ from 'lodash' +import fs from 'fs' +import assert from 'assert' +import {Server as WebSocketServer} from 'ws' +import {EventEmitter2} from 'eventemitter2' +import fixtures from './fixtures/rippled' +import addresses from './fixtures/addresses.json' +import hashes from './fixtures/hashes.json' +import transactionsResponse from './fixtures/rippled/account-tx' +import accountLinesResponse from './fixtures/rippled/account-lines' +import accountObjectsResponse from './fixtures/rippled/account-objects' +import fullLedger from './fixtures/rippled/ledger-full-38129.json' +import {getFreePort} from './utils' function isUSD(json) { - return json === 'USD' || json === '0000000000000000000000005553440000000000'; + return json === 'USD' || json === '0000000000000000000000005553440000000000' } function isBTC(json) { - return json === 'BTC' || json === '0000000000000000000000004254430000000000'; + return json === 'BTC' || json === '0000000000000000000000004254430000000000' } function createResponse(request, response, overrides = {}) { - const result = _.assign({}, response.result, overrides); - const change = response.result && !_.isEmpty(overrides) ? - { id: request.id, result: result } : { id: request.id }; - return JSON.stringify(_.assign({}, response, change)); + const result = _.assign({}, response.result, overrides) + const change = + response.result && !_.isEmpty(overrides) + ? {id: request.id, result: result} + : {id: request.id} + return JSON.stringify(_.assign({}, response, change)) } function createLedgerResponse(request, response) { - const newResponse = JSON.parse(createResponse(request, response)); + const newResponse = JSON.parse(createResponse(request, response)) if (newResponse.result && newResponse.result.ledger) { if (!request.transactions) { - delete newResponse.result.ledger.transactions; + delete newResponse.result.ledger.transactions } if (!request.accounts) { - delete newResponse.result.ledger.accountState; + delete newResponse.result.ledger.accountState } // the following fields were not in the ledger response in the past if (newResponse.result.ledger.close_flags === undefined) { - newResponse.result.ledger.close_flags = 0; + newResponse.result.ledger.close_flags = 0 } if (newResponse.result.ledger.parent_close_time === undefined) { newResponse.result.ledger.parent_close_time = - newResponse.result.ledger.close_time - 10; + newResponse.result.ledger.close_time - 10 } } - return JSON.stringify(newResponse); + return JSON.stringify(newResponse) } -// We mock out WebSocketServer in these tests and add a lot of custom +// We mock out WebSocketServer in these tests and add a lot of custom // properties not defined on the normal WebSocketServer object. -type MockedWebSocketServer = any; +type MockedWebSocketServer = any export function createMockRippled(port) { - const mock = new WebSocketServer({ port: port }) as MockedWebSocketServer; - _.assign(mock, EventEmitter2.prototype); + const mock = new WebSocketServer({port: port}) as MockedWebSocketServer + _.assign(mock, EventEmitter2.prototype) - const close = mock.close; - mock.close = function () { + const close = mock.close + mock.close = function() { if (mock.expectedRequests !== undefined) { - const allRequestsMade = _.every(mock.expectedRequests, function (counter) { - return counter === 0; - }); + const allRequestsMade = _.every(mock.expectedRequests, function(counter) { + return counter === 0 + }) if (!allRequestsMade) { - const json = JSON.stringify(mock.expectedRequests, null, 2); - const indent = ' '; - const indented = indent + json.replace(/\n/g, '\n' + indent); - assert(false, 'Not all expected requests were made:\n' + indented); + const json = JSON.stringify(mock.expectedRequests, null, 2) + const indent = ' ' + const indented = indent + json.replace(/\n/g, '\n' + indent) + assert(false, 'Not all expected requests were made:\n' + indented) } } - close.call(mock); - }; + close.call(mock) + } - mock.expect = function (expectedRequests) { - mock.expectedRequests = expectedRequests; - }; + mock.expect = function(expectedRequests) { + mock.expectedRequests = expectedRequests + } - mock.on('connection', function (this: MockedWebSocketServer, conn: any) { + mock.on('connection', function(this: MockedWebSocketServer, conn: any) { if (mock.config.breakNextConnection) { - mock.config.breakNextConnection = false; - conn.terminate(); - return; + mock.config.breakNextConnection = false + conn.terminate() + return } - this.socket = conn; - conn.config = {}; - conn.on('message', function (requestJSON) { + this.socket = conn + conn.config = {} + conn.on('message', function(requestJSON) { try { - const request = JSON.parse(requestJSON); - mock.emit('request_' + request.command, request, conn); - } catch(err) { - console.error('Error: ' + err.message); - assert(false, err.message); + const request = JSON.parse(requestJSON) + mock.emit('request_' + request.command, request, conn) + } catch (err) { + console.error('Error: ' + err.message) + assert(false, err.message) } - }); - }); + }) + }) - mock.config = {}; + mock.config = {} - mock.onAny(function (this: MockedWebSocketServer) { + mock.onAny(function(this: MockedWebSocketServer) { if (this.event.indexOf('request_') !== 0) { - return; + return } if (mock.listeners(this.event).length === 0) { - throw new Error('No event handler registered for ' + this.event); + throw new Error('No event handler registered for ' + this.event) } if (mock.expectedRequests === undefined) { - return; // TODO: fail here to require expectedRequests + return // TODO: fail here to require expectedRequests } - const expectedCount = mock.expectedRequests[this.event]; + const expectedCount = mock.expectedRequests[this.event] if (expectedCount === undefined || expectedCount === 0) { - throw new Error('Unexpected request: ' + this.event); + throw new Error('Unexpected request: ' + this.event) } - mock.expectedRequests[this.event] -= 1; - }); + mock.expectedRequests[this.event] -= 1 + }) - mock.on('request_config', function (request, conn) { - assert.strictEqual(request.command, 'config'); - conn.config = _.assign(conn.config, request.data); - }); + mock.on('request_config', function(request, conn) { + assert.strictEqual(request.command, 'config') + conn.config = _.assign(conn.config, request.data) + }) - mock.on('request_test_command', function (request, conn) { - assert.strictEqual(request.command, 'test_command'); + mock.on('request_test_command', function(request, conn) { + assert.strictEqual(request.command, 'test_command') if (request.data.disconnectIn) { - setTimeout(conn.terminate.bind(conn), request.data.disconnectIn); + setTimeout(conn.terminate.bind(conn), request.data.disconnectIn) } else if (request.data.openOnOtherPort) { getFreePort().then(newPort => { - createMockRippled(newPort); - conn.send(createResponse(request, { - status: 'success', type: 'response', - result: { port: newPort } - } - )); - }); + createMockRippled(newPort) + conn.send( + createResponse(request, { + status: 'success', + type: 'response', + result: {port: newPort} + }) + ) + }) } else if (request.data.closeServerAndReopen) { setTimeout(() => { - conn.terminate(); + conn.terminate() close.call(mock, () => { setTimeout(() => { - createMockRippled(port); - }, request.data.closeServerAndReopen); - }); - }, 10); + createMockRippled(port) + }, request.data.closeServerAndReopen) + }) + }, 10) } - }); + }) - mock.on('request_global_config', function (request, conn) { - assert.strictEqual(request.command, 'global_config'); - mock.config = _.assign(conn.config, request.data); - }); + mock.on('request_global_config', function(request, conn) { + assert.strictEqual(request.command, 'global_config') + mock.config = _.assign(conn.config, request.data) + }) - mock.on('request_echo', function (request, conn) { - assert.strictEqual(request.command, 'echo'); - conn.send(JSON.stringify(request.data)); - }); + mock.on('request_echo', function(request, conn) { + assert.strictEqual(request.command, 'echo') + conn.send(JSON.stringify(request.data)) + }) - mock.on('request_server_info', function (request, conn) { - assert.strictEqual(request.command, 'server_info'); + mock.on('request_server_info', function(request, conn) { + assert.strictEqual(request.command, 'server_info') if (conn.config.highLoadFactor || conn.config.loadFactor) { const response = { - "id": 0, - "status": "success", - "type": "response", - "result": { - "info": { - "build_version": "0.24.0-rc1", - "complete_ledgers": "32570-6595042", - "hostid": "ARTS", - "io_latency_ms": 1, - "last_close": { - "converge_time_s": 2.007, - "proposers": 4 + id: 0, + status: 'success', + type: 'response', + result: { + info: { + build_version: '0.24.0-rc1', + complete_ledgers: '32570-6595042', + hostid: 'ARTS', + io_latency_ms: 1, + last_close: { + converge_time_s: 2.007, + proposers: 4 }, - "load_factor": conn.config.loadFactor || 4294967296, - "peers": 53, - "pubkey_node": "n94wWvFUmaKGYrKUGgpv1DyYgDeXRGdACkNQaSe7zJiy5Znio7UC", - "server_state": "full", - "validated_ledger": { - "age": 5, - "base_fee_xrp": 0.00001, - "hash": "4482DEE5362332F54A4036ED57EE1767C9F33CF7CE5A6670355C16CECE381D46", - "reserve_base_xrp": 20, - "reserve_inc_xrp": 5, - "seq": 6595042 + load_factor: conn.config.loadFactor || 4294967296, + peers: 53, + pubkey_node: 'n94wWvFUmaKGYrKUGgpv1DyYgDeXRGdACkNQaSe7zJiy5Znio7UC', + server_state: 'full', + validated_ledger: { + age: 5, + base_fee_xrp: 0.00001, + hash: + '4482DEE5362332F54A4036ED57EE1767C9F33CF7CE5A6670355C16CECE381D46', + reserve_base_xrp: 20, + reserve_inc_xrp: 5, + seq: 6595042 }, - "validation_quorum": 3 + validation_quorum: 3 } } } - conn.send(createResponse(request, response)); + conn.send(createResponse(request, response)) } else if (conn.config.returnErrorOnServerInfo) { - conn.send(createResponse(request, fixtures.server_info.error)); + conn.send(createResponse(request, fixtures.server_info.error)) } else if (conn.config.disconnectOnServerInfo) { - conn.close(); + conn.close() } else if (conn.config.serverInfoWithoutValidated) { - conn.send(createResponse(request, fixtures.server_info.noValidated)); + conn.send(createResponse(request, fixtures.server_info.noValidated)) } else if (mock.config.returnSyncingServerInfo) { - mock.config.returnSyncingServerInfo--; - conn.send(createResponse(request, fixtures.server_info.syncing)); + mock.config.returnSyncingServerInfo-- + conn.send(createResponse(request, fixtures.server_info.syncing)) } else { - conn.send(createResponse(request, fixtures.server_info.normal)); + conn.send(createResponse(request, fixtures.server_info.normal)) } - }); + }) - mock.on('request_subscribe', function (request, conn) { - assert.strictEqual(request.command, 'subscribe'); + mock.on('request_subscribe', function(request, conn) { + assert.strictEqual(request.command, 'subscribe') if (request && request.streams === 'validations') { conn.send(createResponse(request, fixtures.subscribe_error)) } else if (mock.config.returnEmptySubscribeRequest) { - mock.config.returnEmptySubscribeRequest--; - conn.send(createResponse(request, fixtures.empty)); + mock.config.returnEmptySubscribeRequest-- + conn.send(createResponse(request, fixtures.empty)) } else if (request.accounts) { - assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1); + assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1) } - conn.send(createResponse(request, fixtures.subscribe)); - }); + conn.send(createResponse(request, fixtures.subscribe)) + }) - mock.on('request_unsubscribe', function (request, conn) { - assert.strictEqual(request.command, 'unsubscribe'); + mock.on('request_unsubscribe', function(request, conn) { + assert.strictEqual(request.command, 'unsubscribe') if (request.accounts) { - assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1); + assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1) } else { - assert.deepEqual(request.streams, ['ledger', 'server']); + assert.deepEqual(request.streams, ['ledger', 'server']) } - conn.send(createResponse(request, fixtures.unsubscribe)); - }); + conn.send(createResponse(request, fixtures.unsubscribe)) + }) - mock.on('request_account_objects', function (request, conn) { - assert.strictEqual(request.command, 'account_objects'); + mock.on('request_account_objects', function(request, conn) { + assert.strictEqual(request.command, 'account_objects') if (request.account === addresses.ACCOUNT) { - conn.send(accountObjectsResponse(request)); + conn.send(accountObjectsResponse(request)) } else { - assert(false, 'Unrecognized account address: ' + request.account); + assert(false, 'Unrecognized account address: ' + request.account) } - }); + }) - mock.on('request_account_info', function (request, conn) { - assert.strictEqual(request.command, 'account_info'); + mock.on('request_account_info', function(request, conn) { + assert.strictEqual(request.command, 'account_info') if (request.account === addresses.ACCOUNT) { - conn.send(createResponse(request, fixtures.account_info.normal)); + conn.send(createResponse(request, fixtures.account_info.normal)) } else if (request.account === addresses.NOTFOUND) { - conn.send(createResponse(request, fixtures.account_info.notfound)); + conn.send(createResponse(request, fixtures.account_info.notfound)) } else if (request.account === addresses.THIRD_ACCOUNT) { - const response = Object.assign({}, fixtures.account_info.normal); - response.Account = addresses.THIRD_ACCOUNT; - conn.send(createResponse(request, response)); + const response = Object.assign({}, fixtures.account_info.normal) + response.Account = addresses.THIRD_ACCOUNT + conn.send(createResponse(request, response)) } else if (request.account === undefined) { - const response = Object.assign({}, { - error: 'invalidParams', - error_code: 31, - error_message: 'Missing field \'account\'.', - id: 2, - request: { command: 'account_info', id: 2 }, - status: 'error', - type: 'response' - }); - conn.send(createResponse(request, response)); + const response = Object.assign( + {}, + { + error: 'invalidParams', + error_code: 31, + error_message: "Missing field 'account'.", + id: 2, + request: {command: 'account_info', id: 2}, + status: 'error', + type: 'response' + } + ) + conn.send(createResponse(request, response)) } else { - const response = Object.assign({}, { - account: request.account, - error: 'actNotFound', - error_code: 19, - error_message: 'Account not found.', - id: 2, - ledger_current_index: 17714714, - request: + const response = Object.assign( + {}, + { + account: request.account, + error: 'actNotFound', + error_code: 19, + error_message: 'Account not found.', + id: 2, + ledger_current_index: 17714714, + request: + // This will be inaccurate, but that's OK because this is just a mock rippled + { + account: 'rogvkYnY8SWjxkJNgU4ZRVfLeRyt5DR9i', + command: 'account_info', + id: 2 + }, - // This will be inaccurate, but that's OK because this is just a mock rippled - { account: 'rogvkYnY8SWjxkJNgU4ZRVfLeRyt5DR9i', - command: 'account_info', - id: 2 }, - - status: 'error', - type: 'response', - validated: false - }); - conn.send(createResponse(request, response)); + status: 'error', + type: 'response', + validated: false + } + ) + conn.send(createResponse(request, response)) } - }); + }) - mock.on('request_ledger', function (request, conn) { - assert.strictEqual(request.command, 'ledger'); + mock.on('request_ledger', function(request, conn) { + assert.strictEqual(request.command, 'ledger') if (request.ledger_index === 34) { - conn.send(createLedgerResponse(request, fixtures.ledger.notFound)); + conn.send(createLedgerResponse(request, fixtures.ledger.notFound)) } else if (request.ledger_index === 6) { - conn.send(createResponse(request, fixtures.ledger.withStateAsHashes)); + conn.send(createResponse(request, fixtures.ledger.withStateAsHashes)) } else if (request.ledger_index === 9038215) { - conn.send( - createLedgerResponse(request, fixtures.ledger.withoutCloseTime)); + conn.send(createLedgerResponse(request, fixtures.ledger.withoutCloseTime)) } else if (request.ledger_index === 4181996) { - conn.send(createLedgerResponse(request, fixtures.ledger.withSettingsTx)); - } else if (request.ledger_index === 22420574 && - request.expand === true && request.transactions === true) { + conn.send(createLedgerResponse(request, fixtures.ledger.withSettingsTx)) + } else if ( + request.ledger_index === 22420574 && + request.expand === true && + request.transactions === true + ) { conn.send( - createLedgerResponse(request, fixtures.ledger.withPartialPayment)); + createLedgerResponse(request, fixtures.ledger.withPartialPayment) + ) } else if (request.ledger_index === 100001) { conn.send( - createLedgerResponse(request, fixtures.ledger.pre2014withPartial)); + createLedgerResponse(request, fixtures.ledger.pre2014withPartial) + ) } else if (request.ledger_index === 38129) { - const response = _.assign({}, fixtures.ledger.normal, - { result: { ledger: fullLedger } }); - conn.send(createLedgerResponse(request, response)); - } else if (request.ledger_hash === '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D') { - conn.send(createLedgerResponse(request, fixtures.ledger.normalByHash)); - } else if (request.ledger_index === 'validated' || - request.ledger_index === 14661789 || - request.ledger_index === 14661788 /* getTransaction - order */) { - conn.send(createLedgerResponse(request, fixtures.ledger.normal)); + const response = _.assign({}, fixtures.ledger.normal, { + result: {ledger: fullLedger} + }) + conn.send(createLedgerResponse(request, response)) + } else if ( + request.ledger_hash === + '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D' + ) { + conn.send(createLedgerResponse(request, fixtures.ledger.normalByHash)) + } else if ( + request.ledger_index === 'validated' || + request.ledger_index === 14661789 || + request.ledger_index === 14661788 /* getTransaction - order */ + ) { + conn.send(createLedgerResponse(request, fixtures.ledger.normal)) } else { - assert(false, 'Unrecognized ledger request: ' + JSON.stringify(request)); + assert(false, 'Unrecognized ledger request: ' + JSON.stringify(request)) } - }); + }) - mock.on('request_ledger_data', function (request, conn) { - assert.strictEqual(request.command, 'ledger_data'); + mock.on('request_ledger_data', function(request, conn) { + assert.strictEqual(request.command, 'ledger_data') if (request.marker) { - conn.send(createResponse(request, fixtures.ledger_data.last_page)); + conn.send(createResponse(request, fixtures.ledger_data.last_page)) } else { - conn.send(createResponse(request, fixtures.ledger_data.first_page)); + conn.send(createResponse(request, fixtures.ledger_data.first_page)) } - }); + }) - mock.on('request_ledger_entry', function (request, conn) { - assert.strictEqual(request.command, 'ledger_entry'); - if (request.index === - 'E30E709CF009A1F26E0E5C48F7AA1BFB79393764F15FB108BDC6E06D3CBD8415') { - conn.send(createResponse(request, fixtures.payment_channel.normal)); - } else if (request.index === - 'D77CD4713AA08195E6B6D0E5BC023DA11B052EBFF0B5B22EDA8AE85345BCF661') { - conn.send(createResponse(request, fixtures.payment_channel.full)); - } else if (request.index === - '8EF9CCB9D85458C8D020B3452848BBB42EAFDDDB69A93DD9D1223741A4CA562B') { - conn.send(createResponse(request, fixtures.escrow)); + mock.on('request_ledger_entry', function(request, conn) { + assert.strictEqual(request.command, 'ledger_entry') + if ( + request.index === + 'E30E709CF009A1F26E0E5C48F7AA1BFB79393764F15FB108BDC6E06D3CBD8415' + ) { + conn.send(createResponse(request, fixtures.payment_channel.normal)) + } else if ( + request.index === + 'D77CD4713AA08195E6B6D0E5BC023DA11B052EBFF0B5B22EDA8AE85345BCF661' + ) { + conn.send(createResponse(request, fixtures.payment_channel.full)) + } else if ( + request.index === + '8EF9CCB9D85458C8D020B3452848BBB42EAFDDDB69A93DD9D1223741A4CA562B' + ) { + conn.send(createResponse(request, fixtures.escrow)) } else { - conn.send(createResponse(request, fixtures.ledger_entry.error)); + conn.send(createResponse(request, fixtures.ledger_entry.error)) } - }); + }) - mock.on('request_ping', function (request, conn) { + mock.on('request_ping', function(request, conn) { // NOTE: We give the response a timeout of 2 second, so that tests can // set their timeout threshold to greater than or less than this number // to test timeouts. setTimeout(() => { - conn.send(createResponse(request, { - "result": {}, - "status": "success", - "type": "response" - })); - }, 1000 * 2); - }); + conn.send( + createResponse(request, { + result: {}, + status: 'success', + type: 'response' + }) + ) + }, 1000 * 2) + }) - mock.on('request_tx', function (request, conn) { - assert.strictEqual(request.command, 'tx'); + mock.on('request_tx', function(request, conn) { + assert.strictEqual(request.command, 'tx') if (request.transaction === hashes.VALID_TRANSACTION_HASH) { - conn.send(createResponse(request, fixtures.tx.Payment)); - } else if (request.transaction === - '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B') { - conn.send(createResponse(request, fixtures.tx.AccountSet)); - } else if (request.transaction === - '8925FC8844A1E930E2CC76AD0A15E7665AFCC5425376D548BB1413F484C31B8C') { - conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOn)); - } else if (request.transaction === - 'C8C5E20DFB1BF533D0D81A2ED23F0A3CBD1EF2EE8A902A1D760500473CC9C582') { - conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOff)); - } else if (request.transaction === - '278E6687C1C60C6873996210A6523564B63F2844FB1019576C157353B1813E60') { - conn.send(createResponse(request, fixtures.tx.RegularKey)); - } else if (request.transaction === - '10A6FB4A66EE80BED46AAE4815D7DC43B97E944984CCD5B93BCF3F8538CABC51') { - conn.send(createResponse(request, fixtures.tx.OfferCreate)); - } else if (request.transaction === - '458101D51051230B1D56E9ACAFAA34451BF65FA000F95DF6F0FF5B3A62D83FC2') { - conn.send(createResponse(request, fixtures.tx.OfferCreateSell)); - } else if (request.transaction === - '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E') { - conn.send(createResponse(request, fixtures.tx.OfferCancel)); - } else if (request.transaction === - '635A0769BD94710A1F6A76CDE65A3BC661B20B798807D1BBBDADCEA26420538D') { - conn.send(createResponse(request, fixtures.tx.TrustSet)); - } else if (request.transaction === - '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11') { - conn.send(createResponse(request, fixtures.tx.NoLedgerIndex)); - } else if (request.transaction === - '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA12') { - conn.send(createResponse(request, fixtures.tx.NoLedgerFound)); - } else if (request.transaction === - '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A04') { - conn.send(createResponse(request, fixtures.tx.LedgerWithoutTime)); - } else if (request.transaction === - 'FE72FAD0FA7CA904FB6C633A1666EDF0B9C73B2F5A4555D37EEF2739A78A531B') { - conn.send(createResponse(request, fixtures.tx.TrustSetFrozenOff)); - } else if (request.transaction === - 'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002') { - conn.send(createResponse(request, fixtures.tx.TrustSetNoQuality)); - } else if (request.transaction === - '9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220') { - conn.send(createResponse(request, fixtures.tx.TrustSetAddMemo)); - }else if (request.transaction === - '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10') { - conn.send(createResponse(request, fixtures.tx.NotValidated)); + conn.send(createResponse(request, fixtures.tx.Payment)) + } else if ( + request.transaction === + '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B' + ) { + conn.send(createResponse(request, fixtures.tx.AccountSet)) + } else if ( + request.transaction === + '8925FC8844A1E930E2CC76AD0A15E7665AFCC5425376D548BB1413F484C31B8C' + ) { + conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOn)) + } else if ( + request.transaction === + 'C8C5E20DFB1BF533D0D81A2ED23F0A3CBD1EF2EE8A902A1D760500473CC9C582' + ) { + conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOff)) + } else if ( + request.transaction === + '278E6687C1C60C6873996210A6523564B63F2844FB1019576C157353B1813E60' + ) { + conn.send(createResponse(request, fixtures.tx.RegularKey)) + } else if ( + request.transaction === + '10A6FB4A66EE80BED46AAE4815D7DC43B97E944984CCD5B93BCF3F8538CABC51' + ) { + conn.send(createResponse(request, fixtures.tx.OfferCreate)) + } else if ( + request.transaction === + '458101D51051230B1D56E9ACAFAA34451BF65FA000F95DF6F0FF5B3A62D83FC2' + ) { + conn.send(createResponse(request, fixtures.tx.OfferCreateSell)) + } else if ( + request.transaction === + '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E' + ) { + conn.send(createResponse(request, fixtures.tx.OfferCancel)) + } else if ( + request.transaction === + '635A0769BD94710A1F6A76CDE65A3BC661B20B798807D1BBBDADCEA26420538D' + ) { + conn.send(createResponse(request, fixtures.tx.TrustSet)) + } else if ( + request.transaction === + '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11' + ) { + conn.send(createResponse(request, fixtures.tx.NoLedgerIndex)) + } else if ( + request.transaction === + '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA12' + ) { + conn.send(createResponse(request, fixtures.tx.NoLedgerFound)) + } else if ( + request.transaction === + '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A04' + ) { + conn.send(createResponse(request, fixtures.tx.LedgerWithoutTime)) + } else if ( + request.transaction === + 'FE72FAD0FA7CA904FB6C633A1666EDF0B9C73B2F5A4555D37EEF2739A78A531B' + ) { + conn.send(createResponse(request, fixtures.tx.TrustSetFrozenOff)) + } else if ( + request.transaction === + 'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002' + ) { + conn.send(createResponse(request, fixtures.tx.TrustSetNoQuality)) + } else if ( + request.transaction === + '9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220' + ) { + conn.send(createResponse(request, fixtures.tx.TrustSetAddMemo)) + } else if ( + request.transaction === + '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10' + ) { + conn.send(createResponse(request, fixtures.tx.NotValidated)) } else if (request.transaction === hashes.NOTFOUND_TRANSACTION_HASH) { - conn.send(createResponse(request, fixtures.tx.NotFound)); - } else if (request.transaction === - '097B9491CC76B64831F1FEA82EAA93BCD728106D90B65A072C933888E946C40B') { - conn.send(createResponse(request, fixtures.tx.OfferWithExpiration)); + conn.send(createResponse(request, fixtures.tx.NotFound)) + } else if ( + request.transaction === + '097B9491CC76B64831F1FEA82EAA93BCD728106D90B65A072C933888E946C40B' + ) { + conn.send(createResponse(request, fixtures.tx.OfferWithExpiration)) } // Checks - - else if (request.transaction === - '605A2E2C8E48AECAF5C56085D1AEAA0348DC838CE122C9188F94EB19DA05C2FE') { - conn.send(createResponse(request, fixtures.tx.CheckCreate)); - } else if (request.transaction === - 'B4105D1B2D83819647E4692B7C5843D674283F669524BD50C9614182E3A12CD4') { - conn.send(createResponse(request, fixtures.tx.CheckCancel)); - } else if (request.transaction === - '8321208465F70BA52C28BCC4F646BAF3B012BA13B57576C0336F42D77E3E0749') { - conn.send(createResponse(request, fixtures.tx.CheckCash)); + else if ( + request.transaction === + '605A2E2C8E48AECAF5C56085D1AEAA0348DC838CE122C9188F94EB19DA05C2FE' + ) { + conn.send(createResponse(request, fixtures.tx.CheckCreate)) + } else if ( + request.transaction === + 'B4105D1B2D83819647E4692B7C5843D674283F669524BD50C9614182E3A12CD4' + ) { + conn.send(createResponse(request, fixtures.tx.CheckCancel)) + } else if ( + request.transaction === + '8321208465F70BA52C28BCC4F646BAF3B012BA13B57576C0336F42D77E3E0749' + ) { + conn.send(createResponse(request, fixtures.tx.CheckCash)) } // Escrows - - else if (request.transaction === - '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE1') { - conn.send(createResponse(request, fixtures.tx.EscrowCreation)); - } else if (request.transaction === - 'F346E542FFB7A8398C30A87B952668DAB48B7D421094F8B71776DA19775A3B22') { - conn.send(createResponse(request, fixtures.tx.EscrowCancellation)); - } else if (request.transaction === - 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD136993B') { - conn.send(createResponse(request, fixtures.tx.EscrowExecution)); - } else if (request.transaction === - 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD1369931') { - conn.send(createResponse(request, - fixtures.tx.EscrowExecutionSimple)); + else if ( + request.transaction === + '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE1' + ) { + conn.send(createResponse(request, fixtures.tx.EscrowCreation)) + } else if ( + request.transaction === + 'F346E542FFB7A8398C30A87B952668DAB48B7D421094F8B71776DA19775A3B22' + ) { + conn.send(createResponse(request, fixtures.tx.EscrowCancellation)) + } else if ( + request.transaction === + 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD136993B' + ) { + conn.send(createResponse(request, fixtures.tx.EscrowExecution)) + } else if ( + request.transaction === + 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD1369931' + ) { + conn.send(createResponse(request, fixtures.tx.EscrowExecutionSimple)) } // Payment Channels - - else if (request.transaction === - '0E9CA3AB1053FC0C1CBAA75F636FE1EC92F118C7056BBEF5D63E4C116458A16D') { - conn.send(createResponse(request, fixtures.tx.PaymentChannelCreate)); - } else if (request.transaction === - 'CD053D8867007A6A4ACB7A432605FE476D088DCB515AFFC886CF2B4EB6D2AE8B') { - conn.send(createResponse(request, fixtures.tx.PaymentChannelFund)); - } else if (request.transaction === - '81B9ECAE7195EB6E8034AEDF44D8415A7A803E14513FDBB34FA984AB37D59563') { - conn.send(createResponse(request, fixtures.tx.PaymentChannelClaim)); - } else if (request.transaction === - 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11') { - conn.send(createResponse(request, fixtures.tx.Unrecognized)); - } else if (request.transaction === - 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B') { - conn.send(createResponse(request, fixtures.tx.NoMeta)); - } else if (request.transaction === - '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA13') { - conn.send(createResponse(request, fixtures.tx.LedgerZero)); - } else if (request.transaction === - 'A971B83ABED51D83749B73F3C1AAA627CD965AFF74BE8CD98299512D6FB0658F') { - conn.send(createResponse(request, fixtures.tx.Amendment)); - } else if (request.transaction === - 'C6A40F56127436DCD830B1B35FF939FD05B5747D30D6542572B7A835239817AF') { - conn.send(createResponse(request, fixtures.tx.SetFee)); + else if ( + request.transaction === + '0E9CA3AB1053FC0C1CBAA75F636FE1EC92F118C7056BBEF5D63E4C116458A16D' + ) { + conn.send(createResponse(request, fixtures.tx.PaymentChannelCreate)) + } else if ( + request.transaction === + 'CD053D8867007A6A4ACB7A432605FE476D088DCB515AFFC886CF2B4EB6D2AE8B' + ) { + conn.send(createResponse(request, fixtures.tx.PaymentChannelFund)) + } else if ( + request.transaction === + '81B9ECAE7195EB6E8034AEDF44D8415A7A803E14513FDBB34FA984AB37D59563' + ) { + conn.send(createResponse(request, fixtures.tx.PaymentChannelClaim)) + } else if ( + request.transaction === + 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11' + ) { + conn.send(createResponse(request, fixtures.tx.Unrecognized)) + } else if ( + request.transaction === + 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B' + ) { + conn.send(createResponse(request, fixtures.tx.NoMeta)) + } else if ( + request.transaction === + '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA13' + ) { + conn.send(createResponse(request, fixtures.tx.LedgerZero)) + } else if ( + request.transaction === + 'A971B83ABED51D83749B73F3C1AAA627CD965AFF74BE8CD98299512D6FB0658F' + ) { + conn.send(createResponse(request, fixtures.tx.Amendment)) + } else if ( + request.transaction === + 'C6A40F56127436DCD830B1B35FF939FD05B5747D30D6542572B7A835239817AF' + ) { + conn.send(createResponse(request, fixtures.tx.SetFee)) } else { - assert(false, 'Unrecognized transaction hash: ' + request.transaction); + assert(false, 'Unrecognized transaction hash: ' + request.transaction) } - }); + }) - mock.on('request_submit', function (request, conn) { - assert.strictEqual(request.command, 'submit'); + mock.on('request_submit', function(request, conn) { + assert.strictEqual(request.command, 'submit') if (request.tx_blob === 'BAD') { - conn.send(createResponse(request, fixtures.submit.failure)); + conn.send(createResponse(request, fixtures.submit.failure)) } else { - conn.send(createResponse(request, fixtures.submit.success)); + conn.send(createResponse(request, fixtures.submit.success)) } - }); + }) - mock.on('request_submit_multisigned', function (request, conn) { - assert.strictEqual(request.command, 'submit_multisigned'); - conn.send(createResponse(request, fixtures.submit.success)); - }); + mock.on('request_submit_multisigned', function(request, conn) { + assert.strictEqual(request.command, 'submit_multisigned') + conn.send(createResponse(request, fixtures.submit.success)) + }) - mock.on('request_account_lines', function (request, conn) { + mock.on('request_account_lines', function(request, conn) { if (request.account === addresses.ACCOUNT) { - conn.send(accountLinesResponse.normal(request)); + conn.send(accountLinesResponse.normal(request)) } else if (request.account === addresses.OTHER_ACCOUNT) { - conn.send(accountLinesResponse.counterparty(request)); + conn.send(accountLinesResponse.counterparty(request)) } else if (request.account === addresses.THIRD_ACCOUNT) { - conn.send(accountLinesResponse.manyItems(request)); + conn.send(accountLinesResponse.manyItems(request)) } else if (request.account === addresses.NOTFOUND) { - conn.send(createResponse(request, fixtures.account_info.notfound)); + conn.send(createResponse(request, fixtures.account_info.notfound)) } else { - assert(false, 'Unrecognized account address: ' + request.account); + assert(false, 'Unrecognized account address: ' + request.account) } - }); + }) - mock.on('request_account_tx', function (request, conn) { + mock.on('request_account_tx', function(request, conn) { if (request.account === addresses.ACCOUNT) { - conn.send(transactionsResponse(request)); + conn.send(transactionsResponse(request)) } else if (request.account === addresses.OTHER_ACCOUNT) { - conn.send(createResponse(request, fixtures.account_tx.one)); + conn.send(createResponse(request, fixtures.account_tx.one)) } else { - assert(false, 'Unrecognized account address: ' + request.account); + assert(false, 'Unrecognized account address: ' + request.account) } - }); + }) - mock.on('request_account_offers', function (request, conn) { + mock.on('request_account_offers', function(request, conn) { if (request.account === addresses.ACCOUNT) { - conn.send(fixtures.account_offers(request)); + conn.send(fixtures.account_offers(request)) } else { - assert(false, 'Unrecognized account address: ' + request.account); + assert(false, 'Unrecognized account address: ' + request.account) } - }); + }) - let requestsCache = undefined; + let requestsCache = undefined - mock.on('request_book_offers', function (request, conn) { + mock.on('request_book_offers', function(request, conn) { if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') { - conn.send(createResponse(request, fixtures.book_offers.xrp_usd)); - } else if (request.taker_gets.issuer - === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') { - conn.send(createResponse(request, fixtures.book_offers.usd_xrp)); - } else if (isBTC(request.taker_gets.currency) - && isUSD(request.taker_pays.currency)) { + conn.send(createResponse(request, fixtures.book_offers.xrp_usd)) + } else if ( + request.taker_gets.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw' + ) { + conn.send(createResponse(request, fixtures.book_offers.usd_xrp)) + } else if ( + isBTC(request.taker_gets.currency) && + isUSD(request.taker_pays.currency) + ) { conn.send( - fixtures.book_offers.fabric.requestBookOffersBidsResponse(request)); - } else if (isUSD(request.taker_gets.currency) - && isBTC(request.taker_pays.currency)) { + fixtures.book_offers.fabric.requestBookOffersBidsResponse(request) + ) + } else if ( + isUSD(request.taker_gets.currency) && + isBTC(request.taker_pays.currency) + ) { conn.send( - fixtures.book_offers.fabric.requestBookOffersAsksResponse(request)); + fixtures.book_offers.fabric.requestBookOffersAsksResponse(request) + ) } else { - const rippledDir = 'test/fixtures/rippled'; + const rippledDir = 'test/fixtures/rippled' if (!requestsCache) { - requestsCache = fs.readdirSync(rippledDir + '/requests'); + requestsCache = fs.readdirSync(rippledDir + '/requests') } for (var i = 0; i < requestsCache.length; i++) { - const file = requestsCache[i]; - const json = fs.readFileSync(rippledDir + '/requests/' + file, 'utf8'); - const r = JSON.parse(json); - const requestWithoutId = Object.assign({}, request); - delete requestWithoutId.id; + const file = requestsCache[i] + const json = fs.readFileSync(rippledDir + '/requests/' + file, 'utf8') + const r = JSON.parse(json) + const requestWithoutId = Object.assign({}, request) + delete requestWithoutId.id if (JSON.stringify(requestWithoutId) === JSON.stringify(r)) { - const responseFile = rippledDir + '/responses/' + file.split('.')[0] + '-res.json'; - const res = fs.readFileSync(responseFile, 'utf8'); + const responseFile = + rippledDir + '/responses/' + file.split('.')[0] + '-res.json' + const res = fs.readFileSync(responseFile, 'utf8') const response = createResponse(request, { - "id": 0, - "type": "response", - "status": "success", - "result": JSON.parse(res) - }); - conn.send(response); - return; + id: 0, + type: 'response', + status: 'success', + result: JSON.parse(res) + }) + conn.send(response) + return } } - assert(false, 'Unrecognized order book: ' + JSON.stringify(request)); + assert(false, 'Unrecognized order book: ' + JSON.stringify(request)) } - }); + }) - mock.on('request_ripple_path_find', function (request, conn) { - let response = null; - if (request.subcommand === 'close') { // for path_find command - return; + mock.on('request_ripple_path_find', function(request, conn) { + let response = null + if (request.subcommand === 'close') { + // for path_find command + return } if (request.source_account === 'rB2NTuTTS3eNCsWxZYzJ4wqRqxNLZqA9Vx') { // getPaths - result path has source_amount in drops response = createResponse(request, { - "id": 0, - "type": "response", - "status": "success", - "result": { - "alternatives": [ + id: 0, + type: 'response', + status: 'success', + result: { + alternatives: [ { - "destination_amount": { - "currency": "EUR", - "issuer": "rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u", - "value": "1" + destination_amount: { + currency: 'EUR', + issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u', + value: '1' }, - "paths_canonical": [], - "paths_computed": [ + paths_canonical: [], + paths_computed: [ [ { - "currency": "USD", - "issuer": "rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u", - "type": 48, - "type_hex": "0000000000000030" + currency: 'USD', + issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u', + type: 48, + type_hex: '0000000000000030' }, { - "currency": "EUR", - "issuer": "rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u", - "type": 48, - "type_hex": "0000000000000030" + currency: 'EUR', + issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u', + type: 48, + type_hex: '0000000000000030' } ] ], - "source_amount": "1000000" + source_amount: '1000000' } ], - "destination_account": "rhpJkBfZGQyT1xeDbwtKEuSrSXw3QZSAy5", - "destination_amount": { - "currency": "EUR", - "issuer": "rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u", - "value": "-1" + destination_account: 'rhpJkBfZGQyT1xeDbwtKEuSrSXw3QZSAy5', + destination_amount: { + currency: 'EUR', + issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u', + value: '-1' }, - "destination_currencies": [ - "EUR", - "XRP" - ], - "full_reply": true, - "id": 2, - "source_account": "rB2NTuTTS3eNCsWxZYzJ4wqRqxNLZqA9Vx", - "status": "success" + destination_currencies: ['EUR', 'XRP'], + full_reply: true, + id: 2, + source_account: 'rB2NTuTTS3eNCsWxZYzJ4wqRqxNLZqA9Vx', + status: 'success' } }) } else if (request.source_account === addresses.NOTFOUND) { - response = createResponse(request, fixtures.path_find.srcActNotFound); + response = createResponse(request, fixtures.path_find.srcActNotFound) } else if (request.source_account === addresses.SOURCE_LOW_FUNDS) { - response = createResponse(request, fixtures.path_find.sourceAmountLow); + response = createResponse(request, fixtures.path_find.sourceAmountLow) } else if (request.source_account === addresses.OTHER_ACCOUNT) { - response = createResponse(request, fixtures.path_find.sendUSD); + response = createResponse(request, fixtures.path_find.sendUSD) } else if (request.source_account === addresses.THIRD_ACCOUNT) { response = createResponse(request, fixtures.path_find.XrpToXrp, { destination_amount: request.destination_amount, destination_address: request.destination_address - }); + }) } else if (request.source_account === addresses.ACCOUNT) { - if (request.destination_account === 'ra5nK24KXen9AHvsdFTKHSANinZseWnPcX' && - // Important: Ensure that destination_amount.value is correct - request.destination_amount.value === "-1") { - response = createResponse(request, fixtures.path_find.sendAll); + if ( + request.destination_account === 'ra5nK24KXen9AHvsdFTKHSANinZseWnPcX' && + // Important: Ensure that destination_amount.value is correct + request.destination_amount.value === '-1' + ) { + response = createResponse(request, fixtures.path_find.sendAll) } else { response = fixtures.path_find.generate.generateIOUPaymentPaths( - request.id, request.source_account, request.destination_account, - request.destination_amount); + request.id, + request.source_account, + request.destination_account, + request.destination_amount + ) } } else { - assert(false, 'Unrecognized path find request: ' - + JSON.stringify(request)); + assert( + false, + 'Unrecognized path find request: ' + JSON.stringify(request) + ) } - conn.send(response); - }); + conn.send(response) + }) - mock.on('request_gateway_balances', function (request, conn) { + mock.on('request_gateway_balances', function(request, conn) { if (request.ledger_index === 123456) { - conn.send(createResponse(request, fixtures.unsubscribe)); + conn.send(createResponse(request, fixtures.unsubscribe)) } else { - conn.send(createResponse(request, fixtures.gateway_balances)); + conn.send(createResponse(request, fixtures.gateway_balances)) } - }); + }) - return mock; -}; + return mock +} diff --git a/test/mocked-server.ts b/test/mocked-server.ts index 249b6f97..63933d3d 100644 --- a/test/mocked-server.ts +++ b/test/mocked-server.ts @@ -1,15 +1,15 @@ -const port = 34371; -import {createMockRippled} from './mock-rippled'; +const port = 34371 +import {createMockRippled} from './mock-rippled' function main() { if (global.describe) { // we are running inside mocha, exiting - return; + return } - console.log('starting server on port ' + port); - createMockRippled(port); - console.log('starting server on port ' + String(port + 1)); - createMockRippled(port + 1); + console.log('starting server on port ' + port) + createMockRippled(port) + console.log('starting server on port ' + String(port + 1)) + createMockRippled(port + 1) } -main(); +main() diff --git a/test/rangeset-test.ts b/test/rangeset-test.ts index 0f1d8f6c..aa10898a 100644 --- a/test/rangeset-test.ts +++ b/test/rangeset-test.ts @@ -1,80 +1,80 @@ -import assert from 'assert'; -import {RippleAPI} from 'ripple-api'; -const RangeSet = RippleAPI._PRIVATE.RangeSet; +import assert from 'assert' +import {RippleAPI} from 'ripple-api' +const RangeSet = RippleAPI._PRIVATE.RangeSet describe('RangeSet', function() { it('addRange()/addValue()', function() { - const r = new RangeSet(); + const r = new RangeSet() - r.addRange(4, 5); - r.addRange(7, 10); - r.addRange(1, 2); - r.addValue(3); + r.addRange(4, 5) + r.addRange(7, 10) + r.addRange(1, 2) + r.addValue(3) - assert.deepEqual(r.serialize(), '1-5,7-10'); - }); + assert.deepEqual(r.serialize(), '1-5,7-10') + }) it('addValue()/addRange() -- malformed', function() { - const r = new RangeSet(); + const r = new RangeSet() assert.throws(function() { - r.addRange(2, 1); - }); - }); + r.addRange(2, 1) + }) + }) it('parseAndAddRanges()', function() { - const r = new RangeSet(); - r.parseAndAddRanges('4-5,7-10,1-2,3-3'); - assert.deepEqual(r.serialize(), '1-5,7-10'); - }); + const r = new RangeSet() + r.parseAndAddRanges('4-5,7-10,1-2,3-3') + assert.deepEqual(r.serialize(), '1-5,7-10') + }) it('parseAndAddRanges() -- single ledger', function() { - const r = new RangeSet(); + const r = new RangeSet() - r.parseAndAddRanges('3'); - assert.strictEqual(r.serialize(), '3-3'); - assert(r.containsValue(3)); - assert(!r.containsValue(0)); - assert(!r.containsValue(2)); - assert(!r.containsValue(4)); - assert(r.containsRange(3, 3)); - assert(!r.containsRange(2, 3)); - assert(!r.containsRange(3, 4)); + r.parseAndAddRanges('3') + assert.strictEqual(r.serialize(), '3-3') + assert(r.containsValue(3)) + assert(!r.containsValue(0)) + assert(!r.containsValue(2)) + assert(!r.containsValue(4)) + assert(r.containsRange(3, 3)) + assert(!r.containsRange(2, 3)) + assert(!r.containsRange(3, 4)) - r.parseAndAddRanges('1-5'); - assert.strictEqual(r.serialize(), '1-5'); - assert(r.containsValue(3)); - assert(r.containsValue(1)); - assert(r.containsValue(5)); - assert(!r.containsValue(6)); - assert(!r.containsValue(0)); - assert(r.containsRange(1, 5)); - assert(r.containsRange(2, 4)); - assert(!r.containsRange(1, 6)); - assert(!r.containsRange(0, 3)); - }); + r.parseAndAddRanges('1-5') + assert.strictEqual(r.serialize(), '1-5') + assert(r.containsValue(3)) + assert(r.containsValue(1)) + assert(r.containsValue(5)) + assert(!r.containsValue(6)) + assert(!r.containsValue(0)) + assert(r.containsRange(1, 5)) + assert(r.containsRange(2, 4)) + assert(!r.containsRange(1, 6)) + assert(!r.containsRange(0, 3)) + }) it('containsValue()', function() { - const r = new RangeSet(); + const r = new RangeSet() - r.addRange(32570, 11005146); - r.addValue(11005147); + r.addRange(32570, 11005146) + r.addValue(11005147) - assert.strictEqual(r.containsValue(1), false); - assert.strictEqual(r.containsValue(32569), false); - assert.strictEqual(r.containsValue(32570), true); - assert.strictEqual(r.containsValue(50000), true); - assert.strictEqual(r.containsValue(11005146), true); - assert.strictEqual(r.containsValue(11005147), true); - assert.strictEqual(r.containsValue(11005148), false); - assert.strictEqual(r.containsValue(12000000), false); - }); + assert.strictEqual(r.containsValue(1), false) + assert.strictEqual(r.containsValue(32569), false) + assert.strictEqual(r.containsValue(32570), true) + assert.strictEqual(r.containsValue(50000), true) + assert.strictEqual(r.containsValue(11005146), true) + assert.strictEqual(r.containsValue(11005147), true) + assert.strictEqual(r.containsValue(11005148), false) + assert.strictEqual(r.containsValue(12000000), false) + }) it('reset()', function() { - const r = new RangeSet(); + const r = new RangeSet() - r.addRange(4, 5); - r.addRange(7, 10); - r.reset(); + r.addRange(4, 5) + r.addRange(7, 10) + r.reset() - assert.deepEqual(r.serialize(), ''); - }); -}); + assert.deepEqual(r.serialize(), '') + }) +}) diff --git a/test/ripple-api-test-private.ts b/test/ripple-api-test-private.ts index 93924edc..1c712d01 100644 --- a/test/ripple-api-test-private.ts +++ b/test/ripple-api-test-private.ts @@ -1,14 +1,14 @@ import assert from 'assert-diff' import _ from 'lodash' -import { RippleAPI } from 'ripple-api' -import { RecursiveData } from 'ripple-api/ledger/utils' -import { assertRejects, assertResultMatch } from './utils' +import {RippleAPI} from 'ripple-api' +import {RecursiveData} from 'ripple-api/ledger/utils' +import {assertRejects, assertResultMatch} from './utils' import addresses from './fixtures/addresses.json' import responses from './fixtures/responses' import ledgerClosed from './fixtures/rippled/ledger-close-newer.json' import setupAPI from './setup-api' -const { validate, schemaValidator, ledgerUtils } = RippleAPI._PRIVATE +const {validate, schemaValidator, ledgerUtils} = RippleAPI._PRIVATE const address = addresses.ACCOUNT assert.options.strict = true @@ -21,22 +21,22 @@ describe('RippleAPI', function() { afterEach(setupAPI.teardown) it('RippleAPI - implicit server port', function() { - new RippleAPI({ server: 'wss://s1.ripple.com' }) + new RippleAPI({server: 'wss://s1.ripple.com'}) }) it('RippleAPI invalid options', function() { // @ts-ignore - This is intentionally invalid - assert.throws(() => new RippleAPI({ invalid: true })) + assert.throws(() => new RippleAPI({invalid: true})) }) it('RippleAPI valid options', function() { - const api = new RippleAPI({ server: 'wss://s:1' }) + const api = new RippleAPI({server: 'wss://s:1'}) const privateConnectionUrl = (api.connection as any)._url assert.deepEqual(privateConnectionUrl, 'wss://s:1') }) it('RippleAPI invalid server uri', function() { - assert.throws(() => new RippleAPI({ server: 'wss//s:1' })) + assert.throws(() => new RippleAPI({server: 'wss//s:1'})) }) xit('RippleAPI connect() times out after 2 seconds', function() { @@ -87,7 +87,7 @@ describe('RippleAPI', function() { minLedgerVersion: 20000, maxLedgerVersion: 10000 } - const thunk = _.partial(validate.getTransactions, { address, options }) + const thunk = _.partial(validate.getTransactions, {address, options}) assert.throws(thunk, this.api.errors.ValidationError) assert.throws( thunk, @@ -97,7 +97,7 @@ describe('RippleAPI', function() { it('secret', function() { function validateSecret(secret) { - validate.sign({ txJSON: '', secret }) + validate.sign({txJSON: '', secret}) } assert.doesNotThrow( _.partial(validateSecret, 'shzjfakiK79YQdMjy4h8cGGfQSV6u') @@ -132,7 +132,7 @@ describe('RippleAPI', function() { }) it('common utils - toRippledAmount', async () => { - const amount = { issuer: 'is', currency: 'c', value: 'v' } + const amount = {issuer: 'is', currency: 'c', value: 'v'} assert.deepEqual(ledgerUtils.common.toRippledAmount(amount), { issuer: 'is', currency: 'c', @@ -142,12 +142,12 @@ describe('RippleAPI', function() { it('ledger utils - renameCounterpartyToIssuerInOrder', async () => { const order = { - taker_gets: { counterparty: '1', currency: 'XRP' }, - taker_pays: { counterparty: '1', currency: 'XRP' } + taker_gets: {counterparty: '1', currency: 'XRP'}, + taker_pays: {counterparty: '1', currency: 'XRP'} } const expected = { - taker_gets: { issuer: '1', currency: 'XRP' }, - taker_pays: { issuer: '1', currency: 'XRP' } + taker_gets: {issuer: '1', currency: 'XRP'}, + taker_pays: {issuer: '1', currency: 'XRP'} } assert.deepEqual( ledgerUtils.renameCounterpartyToIssuerInOrder(order), @@ -158,14 +158,14 @@ describe('RippleAPI', function() { it('ledger utils - compareTransactions', async () => { // @ts-ignore assert.strictEqual(ledgerUtils.compareTransactions({}, {}), 0) - let first: any = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } - let second: any = { outcome: { ledgerVersion: 1, indexInLedger: 200 } } + let first: any = {outcome: {ledgerVersion: 1, indexInLedger: 100}} + let second: any = {outcome: {ledgerVersion: 1, indexInLedger: 200}} assert.strictEqual(ledgerUtils.compareTransactions(first, second), -1) - first = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } - second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + first = {outcome: {ledgerVersion: 1, indexInLedger: 100}} + second = {outcome: {ledgerVersion: 1, indexInLedger: 100}} assert.strictEqual(ledgerUtils.compareTransactions(first, second), 0) - first = { outcome: { ledgerVersion: 1, indexInLedger: 200 } } - second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + first = {outcome: {ledgerVersion: 1, indexInLedger: 200}} + second = {outcome: {ledgerVersion: 1, indexInLedger: 100}} assert.strictEqual(ledgerUtils.compareTransactions(first, second), 1) }) @@ -176,7 +176,7 @@ describe('RippleAPI', function() { reject(new Error()) return } - resolve({ marker: 'A', results: [1] }) + resolve({marker: 'A', results: [1]}) }) } await assertRejects(ledgerUtils.getRecursive(getter, 10), Error) diff --git a/test/ripple-api-test.ts b/test/ripple-api-test.ts index 380f7392..73c2969b 100644 --- a/test/ripple-api-test.ts +++ b/test/ripple-api-test.ts @@ -1,7 +1,7 @@ import setupAPI from './setup-api' -import { RippleAPI } from 'ripple-api' +import {RippleAPI} from 'ripple-api' import addresses from './fixtures/addresses.json' -import { getAllPublicMethods, loadTestSuites } from './utils' +import {getAllPublicMethods, loadTestSuites} from './utils' /** * RippleAPI Test Runner @@ -30,11 +30,7 @@ describe('RippleAPI [Test Runner]', function() { const allTestSuites = loadTestSuites() // Run all the tests: - for (const { - name: methodName, - tests, - config - } of allTestSuites) { + for (const {name: methodName, tests, config} of allTestSuites) { describe(`api.${methodName}`, () => { // Run each test with the original-style address. describe(`[Original Address]`, () => { @@ -58,14 +54,14 @@ 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. it.skip(`${methodName} - no test suite found`, () => { - throw new Error( - `Test file not found! Create file "test/api/${methodName}/index.ts".` - ) + throw new Error( + `Test file not found! Create file "test/api/${methodName}/index.ts".` + ) }) } } diff --git a/test/setup-api-web.ts b/test/setup-api-web.ts index ba878435..d5698b4c 100644 --- a/test/setup-api-web.ts +++ b/test/setup-api-web.ts @@ -1,50 +1,65 @@ -import {RippleAPI, RippleAPIBroadcast} from 'ripple-api'; -import ledgerClosed from './fixtures/rippled/ledger-close.json'; +import {RippleAPI, RippleAPIBroadcast} from 'ripple-api' +import ledgerClosed from './fixtures/rippled/ledger-close.json' -const port = 34371; -const baseUrl = 'ws://testripple.circleci.com:'; +const port = 34371 +const baseUrl = 'ws://testripple.circleci.com:' function setup(this: any, port_ = port) { - const tapi = new RippleAPI({server: baseUrl + port_}); - return tapi.connect().then(() => { - return tapi.connection.request({ - command: 'test_command', - data: {openOnOtherPort: true} - }); - }).then(got => { - return new Promise((resolve, reject) => { - this.api = new RippleAPI({server: baseUrl + got.port}); - this.api.connect().then(() => { - this.api.once('ledger', () => resolve()); - this.api.connection._ws.emit('message', JSON.stringify(ledgerClosed)); - }).catch(reject); - }); - }).then(() => { - return tapi.disconnect(); - }); + const tapi = new RippleAPI({server: baseUrl + port_}) + return tapi + .connect() + .then(() => { + return tapi.connection.request({ + command: 'test_command', + data: {openOnOtherPort: true} + }) + }) + .then(got => { + return new Promise((resolve, reject) => { + this.api = new RippleAPI({server: baseUrl + got.port}) + this.api + .connect() + .then(() => { + this.api.once('ledger', () => resolve()) + this.api.connection._ws.emit( + 'message', + JSON.stringify(ledgerClosed) + ) + }) + .catch(reject) + }) + }) + .then(() => { + return tapi.disconnect() + }) } function setupBroadcast(this: any) { - const servers = [port, port + 1].map(port_ => baseUrl + port_); - this.api = new RippleAPIBroadcast(servers); + const servers = [port, port + 1].map(port_ => baseUrl + port_) + this.api = new RippleAPIBroadcast(servers) return new Promise((resolve, reject) => { - this.api.connect().then(() => { - this.api.once('ledger', () => resolve()); - this.api._apis[0].connection._ws.emit('message', - JSON.stringify(ledgerClosed)); - }).catch(reject); - }); + this.api + .connect() + .then(() => { + this.api.once('ledger', () => resolve()) + this.api._apis[0].connection._ws.emit( + 'message', + JSON.stringify(ledgerClosed) + ) + }) + .catch(reject) + }) } function teardown(this: any) { if (this.api.isConnected()) { - return this.api.disconnect(); + return this.api.disconnect() } - return undefined; + return undefined } export default { setup: setup, teardown: teardown, setupBroadcast: setupBroadcast -}; +} diff --git a/test/setup-api.ts b/test/setup-api.ts index 422e4fdf..82828a76 100644 --- a/test/setup-api.ts +++ b/test/setup-api.ts @@ -1,53 +1,65 @@ -import {RippleAPI, RippleAPIBroadcast} from 'ripple-api'; -import ledgerClosed from './fixtures/rippled/ledger-close.json'; -import {createMockRippled} from './mock-rippled'; -import {getFreePort} from './utils'; +import {RippleAPI, RippleAPIBroadcast} from 'ripple-api' +import ledgerClosed from './fixtures/rippled/ledger-close.json' +import {createMockRippled} from './mock-rippled' +import {getFreePort} from './utils' function setupMockRippledConnection(testcase, port) { return new Promise((resolve, reject) => { - testcase.mockRippled = createMockRippled(port); - testcase._mockedServerPort = port; - testcase.api = new RippleAPI({server: 'ws://localhost:' + port}); - testcase.api.connect().then(() => { - testcase.api.once('ledger', () => resolve()); - testcase.api.connection._ws.emit('message', JSON.stringify(ledgerClosed)); - }).catch(reject); - }); + testcase.mockRippled = createMockRippled(port) + testcase._mockedServerPort = port + testcase.api = new RippleAPI({server: 'ws://localhost:' + port}) + testcase.api + .connect() + .then(() => { + testcase.api.once('ledger', () => resolve()) + testcase.api.connection._ws.emit( + 'message', + JSON.stringify(ledgerClosed) + ) + }) + .catch(reject) + }) } function setupMockRippledConnectionForBroadcast(testcase, ports) { return new Promise((resolve, reject) => { - const servers = ports.map(port => 'ws://localhost:' + port); - testcase.mocks = ports.map(port => createMockRippled(port)); - testcase.api = new RippleAPIBroadcast(servers); - testcase.api.connect().then(() => { - testcase.api.once('ledger', () => resolve()); - testcase.mocks[0].socket.send(JSON.stringify(ledgerClosed)); - }).catch(reject); - }); + const servers = ports.map(port => 'ws://localhost:' + port) + testcase.mocks = ports.map(port => createMockRippled(port)) + testcase.api = new RippleAPIBroadcast(servers) + testcase.api + .connect() + .then(() => { + testcase.api.once('ledger', () => resolve()) + testcase.mocks[0].socket.send(JSON.stringify(ledgerClosed)) + }) + .catch(reject) + }) } function setup(this: any) { return getFreePort().then(port => { - return setupMockRippledConnection(this, port); - }); + return setupMockRippledConnection(this, port) + }) } function setupBroadcast(this: any) { return Promise.all([getFreePort(), getFreePort()]).then(ports => { - return setupMockRippledConnectionForBroadcast(this, ports); - }); + return setupMockRippledConnectionForBroadcast(this, ports) + }) } function teardown(this: any, done) { - this.api.disconnect().then(() => { - if (this.mockRippled !== undefined) { - this.mockRippled.close(); - } else { - this.mocks.forEach(mock => mock.close()); - } - setImmediate(done); - }).catch(done); + this.api + .disconnect() + .then(() => { + if (this.mockRippled !== undefined) { + this.mockRippled.close() + } else { + this.mocks.forEach(mock => mock.close()) + } + setImmediate(done) + }) + .catch(done) } export default { @@ -55,4 +67,4 @@ export default { teardown: teardown, setupBroadcast: setupBroadcast, createMockRippled: createMockRippled -}; +} diff --git a/test/shamap-test.ts b/test/shamap-test.ts index 155100ef..cfeedccb 100644 --- a/test/shamap-test.ts +++ b/test/shamap-test.ts @@ -1,33 +1,32 @@ -import assert from 'assert'; -import {SHAMap, NodeType} from '../src/common/hashes/shamap'; +import assert from 'assert' +import {SHAMap, NodeType} from '../src/common/hashes/shamap' const TYPE_TRANSACTION_NO_METADATA = NodeType.TRANSACTION_NO_METADATA -var HEX_ZERO = '00000000000000000000000000000000' + - '00000000000000000000000000000000'; +var HEX_ZERO = + '00000000000000000000000000000000' + '00000000000000000000000000000000' /** -* Generates data to hash for testing -*/ + * Generates data to hash for testing + */ function intToVuc(v: number): string { - var ret = ''; + var ret = '' for (var i = 0; i < 32; i++) { - ret += '0'; - ret += v.toString(16).toUpperCase(); + ret += '0' + ret += v.toString(16).toUpperCase() } - return ret; + return ret } function fillShamapTest(shamap: any, keys: string[], hashes: string[]) { for (var i = 0; i < keys.length; i++) { - var data = intToVuc(i); - shamap.addItem(keys[i].toUpperCase(), data, TYPE_TRANSACTION_NO_METADATA); - assert.equal(shamap.hash, hashes[i]); + var data = intToVuc(i) + shamap.addItem(keys[i].toUpperCase(), data, TYPE_TRANSACTION_NO_METADATA) + assert.equal(shamap.hash, hashes[i]) } } describe('SHAMap', function() { - describe('#addItem', function() { it('will add new nodes to v1', function() { var keys = [ @@ -39,7 +38,7 @@ describe('SHAMap', function() { 'b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', 'f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', '292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8' - ]; + ] var hashesv1 = [ 'B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C64B6281F7F', @@ -50,12 +49,11 @@ describe('SHAMap', function() { 'D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D98A84D9DDE4', '76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF94361143615', 'DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA02BBE7230E5' - ]; + ] - - var shamapv1 = new SHAMap(); - assert.equal(shamapv1.hash, HEX_ZERO); - fillShamapTest(shamapv1, keys, hashesv1); - }); - }); -}); + var shamapv1 = new SHAMap() + assert.equal(shamapv1.hash, HEX_ZERO) + fillShamapTest(shamapv1, keys, hashesv1) + }) + }) +}) diff --git a/test/utils.ts b/test/utils.ts index 16b437d3..30ea040f 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -2,9 +2,9 @@ import net from 'net' import _ from 'lodash' import fs from 'fs' import path from 'path' -import { RippleAPI } from 'ripple-api' +import {RippleAPI} from 'ripple-api' import assert from 'assert-diff' -const { schemaValidator } = RippleAPI._PRIVATE +const {schemaValidator} = RippleAPI._PRIVATE /** * The test function. It takes a RippleAPI object and then some other data to @@ -122,7 +122,9 @@ export function getAllPublicMethods(api: RippleAPI) { } export function loadTestSuites(): LoadedTestSuite[] { - const allTests = fs.readdirSync(path.join(__dirname, 'api'), { encoding: 'utf8' }) + const allTests = fs.readdirSync(path.join(__dirname, 'api'), { + encoding: 'utf8' + }) return allTests .map(methodName => { if (methodName.startsWith('.DS_Store')) { diff --git a/yarn.lock b/yarn.lock index 2f7efb19..f528fb75 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3524,6 +3524,11 @@ prelude-ls@~1.1.2: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= +prettier@^1.19.1: + version "1.19.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb" + integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew== + process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2"