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