fix: sequence 0 check, lint and format

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -18,15 +18,18 @@ import {assertResultMatch, TestSuite} from '../../utils'
* - Check out "test/api/index.ts" for more information about the test runner.
*/
export default <TestSuite>{
'creates a ticket successfully with a sequence number': async (api, address) => {
'creates a ticket successfully with a sequence number': async (
api,
address
) => {
const expected = {
txJSON:
'{"TransactionType":"TicketCreate", "TicketCount": 2, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence":23,"Fee":"12"}',
instructions: {
maxLedgerVersion: 8819954,
sequence: 23,
fee: '0.000012'
}
txJSON:
'{"TransactionType":"TicketCreate", "TicketCount": 2, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence":23,"Fee":"12"}',
instructions: {
maxLedgerVersion: 8819954,
sequence: 23,
fee: '0.000012'
}
}
const response = await api.prepareTicket(address, 2)
assertResultMatch(response, expected, 'prepare')
@@ -34,13 +37,13 @@ export default <TestSuite>{
'creates a ticket successfully with another ticket': async (api, address) => {
const expected = {
txJSON:
'{"TransactionType":"TicketCreate", "TicketCount": 1, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence": 0,"TicketSequence":23,"Fee":"12"}',
instructions: {
maxLedgerVersion: 8819954,
ticketSequence: 23,
fee: '0.000012'
}
txJSON:
'{"TransactionType":"TicketCreate", "TicketCount": 1, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence": 0,"TicketSequence":23,"Fee":"12"}',
instructions: {
maxLedgerVersion: 8819954,
ticketSequence: 23,
fee: '0.000012'
}
}
const instructions = {
maxLedgerVersion: 8819954,

View File

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

View File

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

View File

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

View File

@@ -8,11 +8,11 @@ import {TestSuite} from '../../utils'
* - Check out "test/api/index.ts" for more information about the test runner.
*/
export default <TestSuite>{
'works with a typical amount': function(api) {
'works with a typical amount': function (api) {
const drops = api.xrpToDrops('2')
assert.strictEqual(drops, '2000000', '2 XRP equals 2 million drops')
},
'works with fractions': function(api) {
'works with fractions': function (api) {
let drops = api.xrpToDrops('3.456789')
assert.strictEqual(drops, '3456789', '3.456789 XRP equals 3,456,789 drops')
drops = api.xrpToDrops('3.400000')
@@ -22,7 +22,7 @@ export default <TestSuite>{
drops = api.xrpToDrops('0.0000010')
assert.strictEqual(drops, '1', '0.0000010 XRP equals 1 drop')
},
'works with zero': function(api) {
'works with zero': function (api) {
let drops = api.xrpToDrops('0')
assert.strictEqual(drops, '0', '0 XRP equals 0 drops')
drops = api.xrpToDrops('-0') // negative zero is equivalent to zero
@@ -32,17 +32,17 @@ export default <TestSuite>{
drops = api.xrpToDrops('0.0000000')
assert.strictEqual(drops, '0', '0.0000000 XRP equals 0 drops')
},
'works with a negative value': function(api) {
'works with a negative value': function (api) {
const drops = api.xrpToDrops('-2')
assert.strictEqual(drops, '-2000000', '-2 XRP equals -2 million drops')
},
'works with a value ending with a decimal point': function(api) {
'works with a value ending with a decimal point': function (api) {
let drops = api.xrpToDrops('2.')
assert.strictEqual(drops, '2000000', '2. XRP equals 2000000 drops')
drops = api.xrpToDrops('-2.')
assert.strictEqual(drops, '-2000000', '-2. XRP equals -2000000 drops')
},
'works with BigNumber objects': function(api) {
'works with BigNumber objects': function (api) {
let drops = api.xrpToDrops(new BigNumber(2))
assert.strictEqual(
drops,
@@ -56,7 +56,7 @@ export default <TestSuite>{
'(BigNumber) -2 XRP equals -2 million drops'
)
},
'works with a number': function(api) {
'works with a number': function (api) {
// This is not recommended. Use strings or BigNumber objects to avoid precision errors.
let drops = api.xrpToDrops(2)
assert.strictEqual(
@@ -71,7 +71,7 @@ export default <TestSuite>{
'(number) -2 XRP equals -2 million drops'
)
},
'throws with an amount with too many decimal places': function(api) {
'throws with an amount with too many decimal places': function (api) {
assert.throws(() => {
api.xrpToDrops('1.1234567')
}, /has too many decimal places/)
@@ -79,7 +79,7 @@ export default <TestSuite>{
api.xrpToDrops('0.0000001')
}, /has too many decimal places/)
},
'throws with an invalid value': function(api) {
'throws with an invalid value': function (api) {
assert.throws(() => {
api.xrpToDrops('FOO')
}, /invalid value/)
@@ -93,7 +93,7 @@ export default <TestSuite>{
api.xrpToDrops('.')
}, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./)
},
'throws with an amount more than one decimal point': function(api) {
'throws with an amount more than one decimal point': function (api) {
assert.throws(() => {
api.xrpToDrops('1.0.0')
}, /xrpToDrops: invalid value '1\.0\.0'/)

View File

@@ -1,15 +1,15 @@
import assert from 'assert-diff'
import {ExponentialBackoff} from '../src/common/backoff'
describe('ExponentialBackoff', function() {
it('duration() return value starts with the min value', function() {
describe('ExponentialBackoff', function () {
it('duration() return value starts with the min value', function () {
// default: 100ms
assert(new ExponentialBackoff().duration(), 100)
assert(new ExponentialBackoff({min: 100}).duration(), 100)
assert(new ExponentialBackoff({min: 123}).duration(), 123)
})
it('duration() return value increases when called multiple times', function() {
it('duration() return value increases when called multiple times', function () {
const backoff = new ExponentialBackoff({min: 100, max: 1000})
assert.strictEqual(backoff.duration(), 100)
assert.strictEqual(backoff.duration(), 200)
@@ -17,7 +17,7 @@ describe('ExponentialBackoff', function() {
assert.strictEqual(backoff.duration(), 800)
})
it('duration() never returns greater than the max value', function() {
it('duration() never returns greater than the max value', function () {
const backoff = new ExponentialBackoff({min: 300, max: 1000})
assert.strictEqual(backoff.duration(), 300)
assert.strictEqual(backoff.duration(), 600)
@@ -25,7 +25,7 @@ describe('ExponentialBackoff', function() {
assert.strictEqual(backoff.duration(), 1000)
})
it('reset() will reset the duration() value', function() {
it('reset() will reset the duration() value', function () {
const backoff = new ExponentialBackoff({min: 100, max: 1000})
assert.strictEqual(backoff.duration(), 100)
assert.strictEqual(backoff.duration(), 200)

View File

@@ -21,21 +21,21 @@ function checkResult(expected, schemaName, response) {
return response
}
describe('RippleAPIBroadcast', function() {
describe('RippleAPIBroadcast', function () {
this.timeout(TIMEOUT)
beforeEach(setupAPI.setupBroadcast)
afterEach(setupAPI.teardown)
it('base', function() {
it('base', function () {
const expected = {request_server_info: 1}
this.mocks.forEach(mock => mock.expect(_.assign({}, expected)))
this.mocks.forEach((mock) => mock.expect(_.assign({}, expected)))
assert(this.api.isConnected())
return this.api
.getServerInfo()
.then(_.partial(checkResult, responses.getServerInfo, 'getServerInfo'))
})
it('ledger', function(done) {
it('ledger', function (done) {
let gotLedger = 0
this.api.on('ledger', () => {
gotLedger++
@@ -43,7 +43,7 @@ describe('RippleAPIBroadcast', function() {
const ledgerNext = _.assign({}, ledgerClosed)
ledgerNext.ledger_index++
this.api._apis.forEach(api =>
this.api._apis.forEach((api) =>
api.connection
.request({
command: 'echo',
@@ -58,7 +58,7 @@ describe('RippleAPIBroadcast', function() {
}, 1250)
})
it('error propagation', function(done) {
it('error propagation', function (done) {
this.api.once('error', (type, info) => {
assert.strictEqual(type, 'type')
assert.strictEqual(info, 'info')

View File

@@ -13,22 +13,22 @@ const isBrowser = (process as any).browser
function createServer() {
return new Promise((resolve, reject) => {
const server = net.createServer()
server.on('listening', function() {
server.on('listening', function () {
resolve(server)
})
server.on('error', function(error) {
server.on('error', function (error) {
reject(error)
})
server.listen(0, '0.0.0.0')
})
}
describe('Connection', function() {
describe('Connection', function () {
this.timeout(TIMEOUT)
beforeEach(setupAPI.setup)
afterEach(setupAPI.teardown)
it('default options', function() {
it('default options', function () {
const connection: any = new utils.common.Connection('url')
assert.strictEqual(connection._url, 'url')
assert(_.isUndefined(connection._config.proxy))
@@ -49,39 +49,39 @@ describe('Connection', function() {
console.log = originalConsoleLog
})
it('as false', function() {
it('as false', function () {
const messages = []
console.log = (id, message) => messages.push([id, message])
const connection: any = new utils.common.Connection('url', {trace: false})
connection._ws = {send: function() {}}
connection._ws = {send: function () {}}
connection.request(mockedRequestData)
connection._onMessage(mockedResponse)
assert.deepEqual(messages, [])
})
it('as true', function() {
it('as true', function () {
const messages = []
console.log = (id, message) => messages.push([id, message])
const connection: any = new utils.common.Connection('url', {trace: true})
connection._ws = {send: function() {}}
connection._ws = {send: function () {}}
connection.request(mockedRequestData)
connection._onMessage(mockedResponse)
assert.deepEqual(messages, expectedMessages)
})
it('as a function', function() {
it('as a function', function () {
const messages = []
const connection: any = new utils.common.Connection('url', {
trace: (id, message) => messages.push([id, message])
})
connection._ws = {send: function() {}}
connection._ws = {send: function () {}}
connection.request(mockedRequestData)
connection._onMessage(mockedResponse)
assert.deepEqual(messages, expectedMessages)
})
})
it('ledger methods work as expected', async function() {
it('ledger methods work as expected', async function () {
assert.strictEqual(await this.api.connection.getLedgerVersion(), 8819951)
assert.strictEqual(
await this.api.connection.hasLedgerVersion(8819951),
@@ -101,7 +101,7 @@ describe('Connection', function() {
assert.strictEqual(await this.api.connection.getReserveBase(), 20000000) // 20 XRP
})
it('with proxy', function(done) {
it('with proxy', function (done) {
if (isBrowser) {
done()
return
@@ -109,8 +109,8 @@ describe('Connection', function() {
createServer().then((server: any) => {
const port = server.address().port
const expect = 'CONNECT localhost'
server.on('connection', socket => {
socket.on('data', data => {
server.on('connection', (socket) => {
socket.on('data', (data) => {
const got = data.toString('ascii', 0, expect.length)
assert.strictEqual(got, expect)
server.close()
@@ -128,34 +128,34 @@ describe('Connection', function() {
this.api.connection._url,
options
)
connection.connect().catch(err => {
connection.connect().catch((err) => {
assert(err instanceof this.api.errors.NotConnectedError)
})
}, done)
})
it('Multiply disconnect calls', function() {
it('Multiply disconnect calls', function () {
this.api.disconnect()
return this.api.disconnect()
})
it('reconnect', function() {
it('reconnect', function () {
return this.api.connection.reconnect()
})
it('NotConnectedError', function() {
it('NotConnectedError', function () {
const connection = new utils.common.Connection('url')
return connection
.getLedgerVersion()
.then(() => {
assert(false, 'Should throw NotConnectedError')
})
.catch(error => {
.catch((error) => {
assert(error instanceof this.api.errors.NotConnectedError)
})
})
it('should throw NotConnectedError if server not responding ', function(done) {
it('should throw NotConnectedError if server not responding ', function (done) {
if (isBrowser) {
const phantomTest = /PhantomJS/
if (phantomTest.test(navigator.userAgent)) {
@@ -170,13 +170,13 @@ describe('Connection', function() {
'ws://testripple.circleci.com:129'
)
connection.on('error', done)
connection.connect().catch(error => {
connection.connect().catch((error) => {
assert(error instanceof this.api.errors.NotConnectedError)
done()
})
})
it('DisconnectedError', async function() {
it('DisconnectedError', async function () {
await this.api.connection.request({
command: 'config',
data: {disconnectOnServerInfo: true}
@@ -186,13 +186,13 @@ describe('Connection', function() {
.then(() => {
assert(false, 'Should throw DisconnectedError')
})
.catch(error => {
.catch((error) => {
assert(error instanceof this.api.errors.DisconnectedError)
})
})
it('TimeoutError', function() {
this.api.connection._ws.send = function(message, options, callback) {
it('TimeoutError', function () {
this.api.connection._ws.send = function (message, options, callback) {
callback(null)
}
const request = {command: 'server_info'}
@@ -201,13 +201,13 @@ describe('Connection', function() {
.then(() => {
assert(false, 'Should throw TimeoutError')
})
.catch(error => {
.catch((error) => {
assert(error instanceof this.api.errors.TimeoutError)
})
})
it('DisconnectedError on send', function() {
this.api.connection._ws.send = function(message, options, callback) {
it('DisconnectedError on send', function () {
this.api.connection._ws.send = function (message, options, callback) {
callback({message: 'not connected'})
}
return this.api
@@ -215,13 +215,13 @@ describe('Connection', function() {
.then(() => {
assert(false, 'Should throw DisconnectedError')
})
.catch(error => {
.catch((error) => {
assert(error instanceof this.api.errors.DisconnectedError)
assert.strictEqual(error.message, 'not connected')
})
})
it('DisconnectedError on initial _onOpen send', async function() {
it('DisconnectedError on initial _onOpen send', async function () {
// _onOpen previously could throw PromiseRejectionHandledWarning: Promise rejection was handled asynchronously
// do not rely on the api.setup hook to test this as it bypasses the case, disconnect api connection first
await this.api.disconnect()
@@ -229,7 +229,7 @@ describe('Connection', function() {
// stub _onOpen to only run logic relevant to test case
this.api.connection._onOpen = () => {
// overload websocket send on open when _ws exists
this.api.connection._ws.send = function(data, options, cb) {
this.api.connection._ws.send = function (data, options, cb) {
// recent ws throws this error instead of calling back
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)')
}
@@ -248,18 +248,18 @@ describe('Connection', function() {
}
})
it('ResponseFormatError', function() {
it('ResponseFormatError', function () {
return this.api
.request('test_command', {data: {unrecognizedResponse: true}})
.then(() => {
assert(false, 'Should throw ResponseFormatError')
})
.catch(error => {
.catch((error) => {
assert(error instanceof this.api.errors.ResponseFormatError)
})
})
it('reconnect on unexpected close', function(done) {
it('reconnect on unexpected close', function (done) {
this.api.connection.on('connected', () => {
done()
})
@@ -268,8 +268,8 @@ describe('Connection', function() {
}, 1)
})
describe('reconnection test', function() {
it('reconnect on several unexpected close', function(done) {
describe('reconnection test', function () {
it('reconnect on several unexpected close', function (done) {
if (isBrowser) {
const phantomTest = /PhantomJS/
if (phantomTest.test(navigator.userAgent)) {
@@ -296,7 +296,7 @@ describe('Connection', function() {
this.api.connection.on('reconnecting', () => {
reconnectsCount += 1
})
this.api.connection.on('disconnected', _code => {
this.api.connection.on('disconnected', (_code) => {
code = _code
disconnectsCount += 1
})
@@ -343,7 +343,7 @@ describe('Connection', function() {
})
})
it('reconnect event on heartbeat failure', function(done) {
it('reconnect event on heartbeat failure', function (done) {
if (isBrowser) {
const phantomTest = /PhantomJS/
if (phantomTest.test(navigator.userAgent)) {
@@ -359,12 +359,12 @@ describe('Connection', function() {
// Hook up a listener for the reconnect event
this.api.connection.on('reconnect', () => done())
// Trigger a heartbeat
this.api.connection._heartbeat().catch(error => {
this.api.connection._heartbeat().catch((error) => {
/* ignore - test expects heartbeat failure */
})
})
it('heartbeat failure and reconnect failure', function(done) {
it('heartbeat failure and reconnect failure', function (done) {
if (isBrowser) {
const phantomTest = /PhantomJS/
if (phantomTest.test(navigator.userAgent)) {
@@ -392,19 +392,19 @@ describe('Connection', function() {
this.api.connection._heartbeat()
})
it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function(done) {
this.api.once('disconnected', code => {
it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) {
this.api.once('disconnected', (code) => {
assert.strictEqual(code, 1000)
done()
})
this.api.disconnect()
})
it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function(done) {
this.api.connection.once('error', error => {
it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) {
this.api.connection.once('error', (error) => {
done(new Error('should not throw error, got ' + String(error)))
})
this.api.connection.once('disconnected', code => {
this.api.connection.once('disconnected', (code) => {
assert.strictEqual(code, 1006)
done()
})
@@ -416,31 +416,31 @@ describe('Connection', function() {
.catch(ignoreWebSocketDisconnect)
})
it('should emit connected event on after reconnect', function(done) {
it('should emit connected event on after reconnect', function (done) {
this.api.once('connected', done)
this.api.connection._ws.close()
})
it('Multiply connect calls', function() {
it('Multiply connect calls', function () {
return this.api.connect().then(() => {
return this.api.connect()
})
})
it('hasLedgerVersion', function() {
return this.api.connection.hasLedgerVersion(8819951).then(result => {
it('hasLedgerVersion', function () {
return this.api.connection.hasLedgerVersion(8819951).then((result) => {
assert(result)
})
})
it('Cannot connect because no server', function() {
it('Cannot connect because no server', function () {
const connection = new utils.common.Connection(undefined as string)
return connection
.connect()
.then(() => {
assert(false, 'Should throw ConnectionError')
})
.catch(error => {
.catch((error) => {
assert(
error instanceof this.api.errors.ConnectionError,
'Should throw ConnectionError'
@@ -448,15 +448,15 @@ describe('Connection', function() {
})
})
it('connect multiserver error', function() {
assert.throws(function() {
it('connect multiserver error', function () {
assert.throws(function () {
new RippleAPI({
servers: ['wss://server1.com', 'wss://server2.com']
} as any)
}, this.api.errors.RippleError)
})
it('connect throws error', function(done) {
it('connect throws error', function (done) {
this.api.once('error', (type, info) => {
assert.strictEqual(type, 'type')
assert.strictEqual(info, 'info')
@@ -465,7 +465,7 @@ describe('Connection', function() {
this.api.connection.emit('error', 'type', 'info')
})
it('emit stream messages', function(done) {
it('emit stream messages', function (done) {
let transactionCount = 0
let pathFindCount = 0
this.api.connection.on('transaction', () => {
@@ -474,7 +474,7 @@ describe('Connection', function() {
this.api.connection.on('path_find', () => {
pathFindCount++
})
this.api.connection.on('response', message => {
this.api.connection.on('response', (message) => {
assert.strictEqual(message.id, 1)
assert.strictEqual(transactionCount, 1)
assert.strictEqual(pathFindCount, 1)
@@ -499,7 +499,7 @@ describe('Connection', function() {
)
})
it('invalid message id', function(done) {
it('invalid message id', function (done) {
this.api.on('error', (errorCode, errorMessage, message) => {
assert.strictEqual(errorCode, 'badMessage')
assert.strictEqual(errorMessage, 'valid id not found in response')
@@ -514,7 +514,7 @@ describe('Connection', function() {
)
})
it('propagates error message', function(done) {
it('propagates error message', function (done) {
this.api.on('error', (errorCode, errorMessage, data) => {
assert.strictEqual(errorCode, 'slowDown')
assert.strictEqual(errorMessage, 'slow down')
@@ -529,8 +529,8 @@ describe('Connection', function() {
)
})
it('propagates RippledError data', function(done) {
this.api.request('subscribe', {streams: 'validations'}).catch(error => {
it('propagates RippledError data', function (done) {
this.api.request('subscribe', {streams: 'validations'}).catch((error) => {
assert.strictEqual(error.name, 'RippledError')
assert.strictEqual(error.data.error, 'invalidParams')
assert.strictEqual(error.message, 'Invalid parameters.')
@@ -547,10 +547,10 @@ describe('Connection', function() {
})
})
it('unrecognized message type', function(done) {
it('unrecognized message type', function (done) {
// This enables us to automatically support any
// new messages added by rippled in the future.
this.api.connection.on('unknown', event => {
this.api.connection.on('unknown', (event) => {
assert.deepEqual(event, {type: 'unknown'})
done()
})
@@ -558,9 +558,9 @@ describe('Connection', function() {
this.api.connection._onMessage(JSON.stringify({type: 'unknown'}))
})
it('ledger close without validated_ledgers', function(done) {
it('ledger close without validated_ledgers', function (done) {
const message = _.omit(ledgerClose, 'validated_ledgers')
this.api.on('ledger', function(ledger) {
this.api.on('ledger', function (ledger) {
assert.strictEqual(ledger.ledgerVersion, 8819951)
done()
})
@@ -570,7 +570,7 @@ describe('Connection', function() {
it(
'should throw RippledNotInitializedError if server does not have ' +
'validated ledgers',
async function() {
async function () {
this.timeout(3000)
await this.api.connection.request({
@@ -583,7 +583,7 @@ describe('Connection', function() {
() => {
assert(false, 'Must have thrown!')
},
error => {
(error) => {
assert(
error instanceof this.api.errors.RippledNotInitializedError,
'Must throw RippledNotInitializedError, got instead ' +
@@ -594,7 +594,7 @@ describe('Connection', function() {
}
)
it('should clean up websocket connection if error after websocket is opened', async function() {
it('should clean up websocket connection if error after websocket is opened', async function () {
await this.api.disconnect()
// fail on connection
this.api.connection._subscribeToLedger = async () => {
@@ -612,9 +612,9 @@ describe('Connection', function() {
}
})
it('should try to reconnect on empty subscribe response on reconnect', function(done) {
it('should try to reconnect on empty subscribe response on reconnect', function (done) {
this.timeout(23000)
this.api.on('error', error => {
this.api.on('error', (error) => {
done(error || new Error('Should not emit error.'))
})
let disconnectedCount = 0

View File

@@ -6,7 +6,7 @@ import * as hashes from '../src/common/hashes'
* Expects a corresponding ledger dump in $repo/test/fixtures/rippled folder
*/
function createLedgerTest(ledgerIndex: number) {
describe(String(ledgerIndex), function() {
describe(String(ledgerIndex), function () {
var path =
__dirname + '/fixtures/rippled/ledger-full-' + ledgerIndex + '.json'
@@ -18,14 +18,14 @@ function createLedgerTest(ledgerIndex: number) {
ledgerJSON.accountState.length > 0
if (hasAccounts) {
it('has account_hash of ' + ledgerJSON.account_hash, function() {
it('has account_hash of ' + ledgerJSON.account_hash, function () {
assert.equal(
ledgerJSON.account_hash,
hashes.computeStateTreeHash(ledgerJSON.accountState)
)
})
}
it('has transaction_hash of ' + ledgerJSON.transaction_hash, function() {
it('has transaction_hash of ' + ledgerJSON.transaction_hash, function () {
assert.equal(
ledgerJSON.transaction_hash,
hashes.computeTransactionTreeHash(ledgerJSON.transactions)
@@ -34,7 +34,7 @@ function createLedgerTest(ledgerIndex: number) {
})
}
describe('Ledger', function() {
describe('Ledger', function () {
// This is the first recorded ledger with a non empty transaction set
createLedgerTest(38129)
// Because, why not.
@@ -42,8 +42,8 @@ describe('Ledger', function() {
// 1311 AffectedNodes, no accounts
createLedgerTest(7501326)
describe('calcAccountRootEntryHash', function() {
it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function() {
describe('calcAccountRootEntryHash', function () {
it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () {
var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'
var expectedEntryHash =
'2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8'
@@ -53,8 +53,8 @@ describe('Ledger', function() {
})
})
describe('calcRippleStateEntryHash', function() {
it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function() {
describe('calcRippleStateEntryHash', function () {
it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function () {
var account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'
var account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY'
var currency = 'USD'
@@ -76,7 +76,7 @@ describe('Ledger', function() {
assert.equal(actualEntryHash2, expectedEntryHash)
})
it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function() {
it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function () {
var account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV'
var account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj'
var currency = 'UAM'
@@ -99,8 +99,8 @@ describe('Ledger', function() {
})
})
describe('calcOfferEntryHash', function() {
it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function() {
describe('calcOfferEntryHash', function () {
it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function () {
var account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw'
var sequence = 137
var expectedEntryHash =
@@ -111,8 +111,8 @@ describe('Ledger', function() {
})
})
describe('computeSignerListLedgerObjectID', function() {
it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function() {
describe('computeSignerListLedgerObjectID', function () {
it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function () {
var account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'
var expectedEntryHash =
'778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF'
@@ -121,8 +121,8 @@ describe('Ledger', function() {
})
})
describe('calcEscrowEntryHash', function() {
it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function() {
describe('calcEscrowEntryHash', function () {
it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function () {
var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x'
var sequence = 84
var expectedEntryHash =
@@ -133,8 +133,8 @@ describe('Ledger', function() {
})
})
describe('calcPaymentChannelEntryHash', function() {
it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function() {
describe('calcPaymentChannelEntryHash', function () {
it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function () {
var account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x'
var dstAccount = 'rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso'
var sequence = 82

View File

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

View File

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

View File

@@ -22,7 +22,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) {
console.log('VERIFY...')
return testcase.api
.getTransaction(hash, options)
.then(data => {
.then((data) => {
assert(data && data.outcome)
assert.strictEqual(data.type, type)
assert.strictEqual(data.address, address)
@@ -32,7 +32,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) {
}
return {txJSON: JSON.stringify(txData), id: hash, tx: data}
})
.catch(error => {
.catch((error) => {
if (error instanceof errors.PendingLedgerVersionError) {
console.log('NOT VALIDATED YET...')
return new Promise((resolve, reject) => {
@@ -71,12 +71,12 @@ function testTransaction(
console.log('PREPARED...')
return testcase.api
.submit(signedData.signedTransaction)
.then(data =>
.then((data) =>
testcase.test.title.indexOf('multisign') !== -1
? acceptLedger(testcase.api).then(() => data)
: data
)
.then(data => {
.then((data) => {
console.log('SUBMITTED...')
assert.strictEqual(data.resultCode, 'tesSUCCESS')
const options = {
@@ -108,7 +108,7 @@ function setup(this: any, server = 'wss://s1.ripple.com') {
() => {
console.log('CONNECTED...')
},
error => {
(error) => {
console.log('ERROR:', error)
throw error
}
@@ -128,7 +128,7 @@ function makeTrustLine(testcase, address, secret) {
}
const trust = api
.prepareTrustline(address, specification, {})
.then(data => {
.then((data) => {
const signed = api.sign(data.txJSON, secret)
if (address === wallet.getAddress()) {
testcase.transactions.push(signed.id)
@@ -142,8 +142,8 @@ function makeTrustLine(testcase, address, secret) {
function makeOrder(api, address, specification, secret) {
return api
.prepareOrder(address, specification)
.then(data => api.sign(data.txJSON, secret))
.then(signed => api.submit(signed.signedTransaction))
.then((data) => api.sign(data.txJSON, secret))
.then((signed) => api.submit(signed.signedTransaction))
.then(() => ledgerAccept(api))
}
@@ -158,8 +158,8 @@ function setupAccounts(testcase) {
.then(() => {
return api
.prepareSettings(masterAccount, {defaultRipple: true})
.then(data => api.sign(data.txJSON, masterSecret))
.then(signed => api.submit(signed.signedTransaction))
.then((data) => api.sign(data.txJSON, masterSecret))
.then((signed) => api.submit(signed.signedTransaction))
.then(() => ledgerAccept(api))
})
.then(() =>
@@ -233,7 +233,7 @@ function suiteSetup(this: any) {
// so getLedgerVersion will return right value
.then(() => ledgerAccept(this.api))
.then(() => this.api.getLedgerVersion())
.then(ledgerVersion => {
.then((ledgerVersion) => {
this.startLedgerVersion = ledgerVersion
})
.then(() => setupAccounts(this))
@@ -241,7 +241,7 @@ function suiteSetup(this: any) {
)
}
describe('integration tests', function() {
describe('integration tests', function () {
const address = wallet.getAddress()
const instructions = {maxLedgerVersionOffset: 10}
this.timeout(TIMEOUT)
@@ -250,31 +250,31 @@ describe('integration tests', function() {
beforeEach(_.partial(setup, serverUrl))
afterEach(teardown)
it('settings', function() {
return this.api.getLedgerVersion().then(ledgerVersion => {
it('settings', function () {
return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api
.prepareSettings(address, requests.prepareSettings.domain, instructions)
.then(prepared =>
.then((prepared) =>
testTransaction(this, 'settings', ledgerVersion, prepared)
)
})
})
it('trustline', function() {
return this.api.getLedgerVersion().then(ledgerVersion => {
it('trustline', function () {
return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api
.prepareTrustline(
address,
requests.prepareTrustline.simple,
instructions
)
.then(prepared =>
.then((prepared) =>
testTransaction(this, 'trustline', ledgerVersion, prepared)
)
})
})
it('payment', function() {
it('payment', function () {
const amount = {currency: 'XRP', value: '0.000001'}
const paymentSpecification = {
source: {
@@ -286,16 +286,16 @@ describe('integration tests', function() {
amount: amount
}
}
return this.api.getLedgerVersion().then(ledgerVersion => {
return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api
.preparePayment(address, paymentSpecification, instructions)
.then(prepared =>
.then((prepared) =>
testTransaction(this, 'payment', ledgerVersion, prepared)
)
})
})
it('order', function() {
it('order', function () {
const orderSpecification = {
direction: 'buy',
quantity: {
@@ -308,18 +308,18 @@ describe('integration tests', function() {
value: '0.0002'
}
}
return this.api.getLedgerVersion().then(ledgerVersion => {
return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api
.prepareOrder(address, orderSpecification, instructions)
.then(prepared =>
.then((prepared) =>
testTransaction(this, 'order', ledgerVersion, prepared)
)
.then(result => {
.then((result) => {
const txData = JSON.parse(result.txJSON)
return this.api.getOrders(address).then(orders => {
return this.api.getOrders(address).then((orders) => {
assert(orders && orders.length > 0)
const createdOrder = _.first(
_.filter(orders, order => {
_.filter(orders, (order) => {
return order.properties.sequence === txData.Sequence
})
)
@@ -329,14 +329,14 @@ describe('integration tests', function() {
return txData
})
})
.then(txData =>
.then((txData) =>
this.api
.prepareOrderCancellation(
address,
{orderSequence: txData.Sequence},
instructions
)
.then(prepared =>
.then((prepared) =>
testTransaction(
this,
'orderCancellation',
@@ -348,56 +348,58 @@ describe('integration tests', function() {
})
})
it('ticket', function() {
return this.api.getLedgerVersion().then(ledgerVersion => {
it('ticket', function () {
return this.api.getLedgerVersion().then((ledgerVersion) => {
return this.api
.prepareTicket(address, 1, instructions)
.then(prepared =>
.then((prepared) =>
testTransaction(this, 'ticket', ledgerVersion, prepared)
)
})
})
it('isConnected', function() {
it('isConnected', function () {
assert(this.api.isConnected())
})
it('getServerInfo', function() {
return this.api.getServerInfo().then(data => {
it('getServerInfo', function () {
return this.api.getServerInfo().then((data) => {
assert(data && data.pubkeyNode)
})
})
it('getFee', function() {
return this.api.getFee().then(fee => {
it('getFee', function () {
return this.api.getFee().then((fee) => {
assert.strictEqual(typeof fee, 'string')
assert(!isNaN(Number(fee)))
assert(parseFloat(fee) === Number(fee))
})
})
it('getLedgerVersion', function() {
return this.api.getLedgerVersion().then(ledgerVersion => {
it('getLedgerVersion', function () {
return this.api.getLedgerVersion().then((ledgerVersion) => {
assert.strictEqual(typeof ledgerVersion, 'number')
assert(ledgerVersion >= this.startLedgerVersion)
})
})
it('getTransactions', function() {
it('getTransactions', function () {
const options = {
initiated: true,
minLedgerVersion: this.startLedgerVersion
}
return this.api.getTransactions(address, options).then(transactionsData => {
assert(transactionsData)
assert.strictEqual(transactionsData.length, this.transactions.length)
})
return this.api
.getTransactions(address, options)
.then((transactionsData) => {
assert(transactionsData)
assert.strictEqual(transactionsData.length, this.transactions.length)
})
})
it('getTrustlines', function() {
it('getTrustlines', function () {
const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty'])
return this.api.getTrustlines(address, options).then(data => {
return this.api.getTrustlines(address, options).then((data) => {
assert(data && data.length > 0 && data[0] && data[0].specification)
const specification = data[0].specification
assert.strictEqual(Number(specification.limit), Number(fixture.limit))
@@ -406,24 +408,24 @@ describe('integration tests', function() {
})
})
it('getBalances', function() {
it('getBalances', function () {
const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty'])
return this.api.getBalances(address, options).then(data => {
return this.api.getBalances(address, options).then((data) => {
assert(data && data.length > 0 && data[0])
assert.strictEqual(data[0].currency, fixture.currency)
assert.strictEqual(data[0].counterparty, fixture.counterparty)
})
})
it('getSettings', function() {
return this.api.getSettings(address).then(data => {
it('getSettings', function () {
return this.api.getSettings(address).then((data) => {
assert(data)
assert.strictEqual(data.domain, requests.prepareSettings.domain.domain)
})
})
it('getOrderbook', function() {
it('getOrderbook', function () {
const orderbook = {
base: {
currency: 'XRP'
@@ -433,7 +435,7 @@ describe('integration tests', function() {
counterparty: masterAccount
}
}
return this.api.getOrderbook(address, orderbook).then(book => {
return this.api.getOrderbook(address, orderbook).then((book) => {
assert(book && book.bids && book.bids.length > 0)
assert(book.asks && book.asks.length > 0)
const bid = book.bids[0]
@@ -451,7 +453,7 @@ describe('integration tests', function() {
})
})
it('getPaths', function() {
it('getPaths', function () {
const pathfind = {
source: {
address: address
@@ -465,7 +467,7 @@ describe('integration tests', function() {
}
}
}
return this.api.getPaths(pathfind).then(data => {
return this.api.getPaths(pathfind).then((data) => {
assert(data && data.length > 0)
const path = data[0]
assert(path && path.source)
@@ -474,7 +476,7 @@ describe('integration tests', function() {
})
})
it('getPaths - send all', function() {
it('getPaths - send all', function () {
const pathfind = {
source: {
address: address,
@@ -491,10 +493,10 @@ describe('integration tests', function() {
}
}
return this.api.getPaths(pathfind).then(data => {
return this.api.getPaths(pathfind).then((data) => {
assert(data && data.length > 0)
assert(
_.every(data, path => {
_.every(data, (path) => {
return (
parseFloat(path.source.amount.value) <=
parseFloat(pathfind.source.amount.value)
@@ -508,7 +510,7 @@ describe('integration tests', function() {
})
})
it('generateWallet', function() {
it('generateWallet', function () {
const newWallet = this.api.generateAddress()
assert(newWallet && newWallet.address && newWallet.secret)
assert(isValidAddress(newWallet.address))
@@ -516,7 +518,7 @@ describe('integration tests', function() {
})
})
describe('integration tests - standalone rippled', function() {
describe('integration tests - standalone rippled', function () {
const instructions = {maxLedgerVersionOffset: 10}
this.timeout(TIMEOUT)
@@ -529,7 +531,7 @@ describe('integration tests - standalone rippled', function() {
const signer2address = 'r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud'
const signer2secret = 'shUHQnL4EH27V4EiBrj6EfhWvZngF'
it('submit multisigned transaction', function() {
it('submit multisigned transaction', function () {
const signers = {
threshold: 2,
weights: [
@@ -540,11 +542,11 @@ describe('integration tests - standalone rippled', function() {
let minLedgerVersion = null
return payTo(this.api, address)
.then(() => {
return this.api.getLedgerVersion().then(ledgerVersion => {
return this.api.getLedgerVersion().then((ledgerVersion) => {
minLedgerVersion = ledgerVersion
return this.api
.prepareSettings(address, {signers}, instructions)
.then(prepared => {
.then((prepared) => {
return testTransaction(
this,
'settings',
@@ -566,7 +568,7 @@ describe('integration tests - standalone rippled', function() {
{domain: 'example.com'},
multisignInstructions
)
.then(prepared => {
.then((prepared) => {
const signed1 = this.api.sign(prepared.txJSON, signer1secret, {
signAs: signer1address
})
@@ -579,8 +581,8 @@ describe('integration tests - standalone rippled', function() {
])
return this.api
.submit(combined.signedTransaction)
.then(response => acceptLedger(this.api).then(() => response))
.then(response => {
.then((response) => acceptLedger(this.api).then(() => response))
.then((response) => {
assert.strictEqual(response.resultCode, 'tesSUCCESS')
const options = {minLedgerVersion}
return verifyTransaction(
@@ -592,7 +594,7 @@ describe('integration tests - standalone rippled', function() {
address
)
})
.catch(error => {
.catch((error) => {
console.log(error.message)
throw error
})

View File

@@ -59,9 +59,11 @@ export function createMockRippled(port) {
_.assign(mock, EventEmitter2.prototype)
const close = mock.close
mock.close = function() {
mock.close = function () {
if (mock.expectedRequests !== undefined) {
const allRequestsMade = _.every(mock.expectedRequests, function(counter) {
const allRequestsMade = _.every(mock.expectedRequests, function (
counter
) {
return counter === 0
})
if (!allRequestsMade) {
@@ -74,11 +76,11 @@ export function createMockRippled(port) {
close.call(mock)
}
mock.expect = function(expectedRequests) {
mock.expect = function (expectedRequests) {
mock.expectedRequests = expectedRequests
}
mock.on('connection', function(this: MockedWebSocketServer, conn: any) {
mock.on('connection', function (this: MockedWebSocketServer, conn: any) {
if (mock.config.breakNextConnection) {
mock.config.breakNextConnection = false
conn.terminate()
@@ -86,7 +88,7 @@ export function createMockRippled(port) {
}
this.socket = conn
conn.config = {}
conn.on('message', function(requestJSON) {
conn.on('message', function (requestJSON) {
try {
const request = JSON.parse(requestJSON)
mock.emit('request_' + request.command, request, conn)
@@ -99,7 +101,7 @@ export function createMockRippled(port) {
mock.config = {}
mock.onAny(function(this: MockedWebSocketServer) {
mock.onAny(function (this: MockedWebSocketServer) {
if (this.event.indexOf('request_') !== 0) {
return
}
@@ -116,7 +118,7 @@ export function createMockRippled(port) {
mock.expectedRequests[this.event] -= 1
})
mock.on('request_config', function(request, conn) {
mock.on('request_config', function (request, conn) {
assert.strictEqual(request.command, 'config')
conn.config = _.assign(conn.config, request.data)
conn.send(
@@ -128,7 +130,7 @@ export function createMockRippled(port) {
)
})
mock.on('request_test_command', function(request, conn) {
mock.on('request_test_command', function (request, conn) {
assert.strictEqual(request.command, 'test_command')
if (request.data.disconnectIn) {
setTimeout(conn.terminate.bind(conn), request.data.disconnectIn)
@@ -140,7 +142,7 @@ export function createMockRippled(port) {
})
)
} else if (request.data.openOnOtherPort) {
getFreePort().then(newPort => {
getFreePort().then((newPort) => {
createMockRippled(newPort)
conn.send(
createResponse(request, {
@@ -170,7 +172,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_global_config', function(request, conn) {
mock.on('request_global_config', function (request, conn) {
assert.strictEqual(request.command, 'global_config')
mock.config = _.assign(conn.config, request.data)
conn.send(
@@ -182,12 +184,12 @@ export function createMockRippled(port) {
)
})
mock.on('request_echo', function(request, conn) {
mock.on('request_echo', function (request, conn) {
assert.strictEqual(request.command, 'echo')
conn.send(JSON.stringify(request.data))
})
mock.on('request_server_info', function(request, conn) {
mock.on('request_server_info', function (request, conn) {
assert.strictEqual(request.command, 'server_info')
if (conn.config.highLoadFactor || conn.config.loadFactor) {
const response = {
@@ -236,7 +238,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_subscribe', function(request, conn) {
mock.on('request_subscribe', function (request, conn) {
assert.strictEqual(request.command, 'subscribe')
if (request && request.streams === 'validations') {
conn.send(createResponse(request, fixtures.subscribe_error))
@@ -249,7 +251,7 @@ export function createMockRippled(port) {
conn.send(createResponse(request, fixtures.subscribe))
})
mock.on('request_unsubscribe', function(request, conn) {
mock.on('request_unsubscribe', function (request, conn) {
assert.strictEqual(request.command, 'unsubscribe')
if (request.accounts) {
assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1)
@@ -259,7 +261,7 @@ export function createMockRippled(port) {
conn.send(createResponse(request, fixtures.unsubscribe))
})
mock.on('request_account_objects', function(request, conn) {
mock.on('request_account_objects', function (request, conn) {
assert.strictEqual(request.command, 'account_objects')
if (request.account === addresses.ACCOUNT) {
conn.send(accountObjectsResponse(request))
@@ -268,7 +270,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_account_info', function(request, conn) {
mock.on('request_account_info', function (request, conn) {
assert.strictEqual(request.command, 'account_info')
if (request.account === addresses.ACCOUNT) {
conn.send(createResponse(request, fixtures.account_info.normal))
@@ -319,7 +321,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_ledger', function(request, conn) {
mock.on('request_ledger', function (request, conn) {
assert.strictEqual(request.command, 'ledger')
if (request.ledger_index === 34) {
conn.send(createLedgerResponse(request, fixtures.ledger.notFound))
@@ -362,7 +364,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_ledger_data', function(request, conn) {
mock.on('request_ledger_data', function (request, conn) {
assert.strictEqual(request.command, 'ledger_data')
if (request.marker) {
conn.send(createResponse(request, fixtures.ledger_data.last_page))
@@ -371,7 +373,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_ledger_entry', function(request, conn) {
mock.on('request_ledger_entry', function (request, conn) {
assert.strictEqual(request.command, 'ledger_entry')
if (
request.index ===
@@ -393,7 +395,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_ping', function(request, conn) {
mock.on('request_ping', function (request, conn) {
// NOTE: We give the response a timeout of 2 second, so that tests can
// set their timeout threshold to greater than or less than this number
// to test timeouts.
@@ -408,7 +410,7 @@ export function createMockRippled(port) {
}, 1000 * 2)
})
mock.on('request_tx', function(request, conn) {
mock.on('request_tx', function (request, conn) {
assert.strictEqual(request.command, 'tx')
if (request.transaction === hashes.VALID_TRANSACTION_HASH) {
conn.send(createResponse(request, fixtures.tx.Payment))
@@ -588,7 +590,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_submit', function(request, conn) {
mock.on('request_submit', function (request, conn) {
assert.strictEqual(request.command, 'submit')
if (request.tx_blob === 'BAD') {
conn.send(createResponse(request, fixtures.submit.failure))
@@ -597,12 +599,12 @@ export function createMockRippled(port) {
}
})
mock.on('request_submit_multisigned', function(request, conn) {
mock.on('request_submit_multisigned', function (request, conn) {
assert.strictEqual(request.command, 'submit_multisigned')
conn.send(createResponse(request, fixtures.submit.success))
})
mock.on('request_account_lines', function(request, conn) {
mock.on('request_account_lines', function (request, conn) {
if (request.account === addresses.ACCOUNT) {
conn.send(accountLinesResponse.normal(request))
} else if (request.account === addresses.OTHER_ACCOUNT) {
@@ -616,7 +618,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_account_tx', function(request, conn) {
mock.on('request_account_tx', function (request, conn) {
if (request.account === addresses.ACCOUNT) {
conn.send(transactionsResponse(request))
} else if (request.account === addresses.OTHER_ACCOUNT) {
@@ -626,7 +628,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_account_offers', function(request, conn) {
mock.on('request_account_offers', function (request, conn) {
if (request.account === addresses.ACCOUNT) {
conn.send(fixtures.account_offers(request))
} else {
@@ -636,7 +638,7 @@ export function createMockRippled(port) {
let requestsCache = undefined
mock.on('request_book_offers', function(request, conn) {
mock.on('request_book_offers', function (request, conn) {
if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') {
conn.send(createResponse(request, fixtures.book_offers.xrp_usd))
} else if (
@@ -687,7 +689,7 @@ export function createMockRippled(port) {
}
})
mock.on('request_ripple_path_find', function(request, conn) {
mock.on('request_ripple_path_find', function (request, conn) {
let response = null
if (request.subcommand === 'close') {
// for path_find command
@@ -775,7 +777,7 @@ export function createMockRippled(port) {
conn.send(response)
})
mock.on('request_gateway_balances', function(request, conn) {
mock.on('request_gateway_balances', function (request, conn) {
if (request.ledger_index === 123456) {
conn.send(createResponse(request, fixtures.unsubscribe))
} else {

View File

@@ -2,8 +2,8 @@ import assert from 'assert'
import {RippleAPI} from 'ripple-api'
const RangeSet = RippleAPI._PRIVATE.RangeSet
describe('RangeSet', function() {
it('addRange()/addValue()', function() {
describe('RangeSet', function () {
it('addRange()/addValue()', function () {
const r = new RangeSet()
r.addRange(4, 5)
@@ -14,19 +14,19 @@ describe('RangeSet', function() {
assert.deepEqual(r.serialize(), '1-5,7-10')
})
it('addValue()/addRange() -- malformed', function() {
it('addValue()/addRange() -- malformed', function () {
const r = new RangeSet()
assert.throws(function() {
assert.throws(function () {
r.addRange(2, 1)
})
})
it('parseAndAddRanges()', function() {
it('parseAndAddRanges()', function () {
const r = new RangeSet()
r.parseAndAddRanges('4-5,7-10,1-2,3-3')
assert.deepEqual(r.serialize(), '1-5,7-10')
})
it('parseAndAddRanges() -- single ledger', function() {
it('parseAndAddRanges() -- single ledger', function () {
const r = new RangeSet()
r.parseAndAddRanges('3')
@@ -52,7 +52,7 @@ describe('RangeSet', function() {
assert(!r.containsRange(0, 3))
})
it('containsValue()', function() {
it('containsValue()', function () {
const r = new RangeSet()
r.addRange(32570, 11005146)
@@ -68,7 +68,7 @@ describe('RangeSet', function() {
assert.strictEqual(r.containsValue(12000000), false)
})
it('reset()', function() {
it('reset()', function () {
const r = new RangeSet()
r.addRange(4, 5)

View File

@@ -15,46 +15,46 @@ assert.options.strict = true
// how long before each test case times out
const TIMEOUT = 20000
describe('RippleAPI', function() {
describe('RippleAPI', function () {
this.timeout(TIMEOUT)
beforeEach(setupAPI.setup)
afterEach(setupAPI.teardown)
it('RippleAPI - implicit server port', function() {
it('RippleAPI - implicit server port', function () {
new RippleAPI({server: 'wss://s1.ripple.com'})
})
it('RippleAPI invalid options', function() {
it('RippleAPI invalid options', function () {
// @ts-ignore - This is intentionally invalid
assert.throws(() => new RippleAPI({invalid: true}))
})
it('RippleAPI valid options', function() {
it('RippleAPI valid options', function () {
const api = new RippleAPI({server: 'wss://s:1'})
const privateConnectionUrl = (api.connection as any)._url
assert.deepEqual(privateConnectionUrl, 'wss://s:1')
})
it('RippleAPI invalid server uri', function() {
it('RippleAPI invalid server uri', function () {
assert.throws(() => new RippleAPI({server: 'wss//s:1'}))
})
xit('RippleAPI connect() times out after 2 seconds', function() {
xit('RippleAPI connect() times out after 2 seconds', function () {
// TODO: Use a timer mock like https://jestjs.io/docs/en/timer-mocks
// to test that connect() times out after 2 seconds.
})
it('ledger closed event', function(done) {
this.api.on('ledger', message => {
it('ledger closed event', function (done) {
this.api.on('ledger', (message) => {
assertResultMatch(message, responses.ledgerEvent, 'ledgerEvent')
done()
})
this.api.connection._ws.emit('message', JSON.stringify(ledgerClosed))
})
describe('[private] schema-validator', function() {
it('valid', function() {
assert.doesNotThrow(function() {
describe('[private] schema-validator', function () {
it('valid', function () {
assert.doesNotThrow(function () {
schemaValidator.schemaValidate(
'hash256',
'0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A0F'
@@ -62,27 +62,27 @@ describe('RippleAPI', function() {
})
})
it('invalid', function() {
assert.throws(function() {
it('invalid', function () {
assert.throws(function () {
schemaValidator.schemaValidate('hash256', 'invalid')
}, this.api.errors.ValidationError)
})
it('invalid - empty value', function() {
assert.throws(function() {
it('invalid - empty value', function () {
assert.throws(function () {
schemaValidator.schemaValidate('hash256', '')
}, this.api.errors.ValidationError)
})
it('schema not found error', function() {
assert.throws(function() {
it('schema not found error', function () {
assert.throws(function () {
schemaValidator.schemaValidate('unexisting', 'anything')
}, /no schema/)
})
})
describe('[private] validator', function() {
it('validateLedgerRange', function() {
describe('[private] validator', function () {
it('validateLedgerRange', function () {
const options = {
minLedgerVersion: 20000,
maxLedgerVersion: 10000
@@ -95,7 +95,7 @@ describe('RippleAPI', function() {
)
})
it('secret', function() {
it('secret', function () {
function validateSecret(secret) {
validate.sign({txJSON: '', secret})
}

View File

@@ -21,7 +21,7 @@ import {getAllPublicMethods, loadTestSuites} from './utils'
* - Type the API object under test and catch typing issues (currently untyped).
* - Sets the stage for more cleanup, like moving test-specific fixtures closer to their tests.
*/
describe('RippleAPI [Test Runner]', function() {
describe('RippleAPI [Test Runner]', function () {
beforeEach(setupAPI.setup)
afterEach(setupAPI.teardown)
@@ -35,7 +35,7 @@ describe('RippleAPI [Test Runner]', function() {
// Run each test that does not use an address.
for (const [testName, fn] of tests) {
if (fn.length === 1) {
it(testName, function() {
it(testName, function () {
return fn(this.api, addresses.ACCOUNT)
})
}
@@ -44,7 +44,7 @@ describe('RippleAPI [Test Runner]', function() {
describe(`[Classic Address]`, () => {
for (const [testName, fn] of tests) {
if (fn.length === 2) {
it(testName, function() {
it(testName, function () {
return fn(this.api, addresses.ACCOUNT)
})
}
@@ -55,7 +55,7 @@ describe('RippleAPI [Test Runner]', function() {
describe(`[X-address]`, () => {
for (const [testName, fn] of tests) {
if (fn.length === 2) {
it(testName, function() {
it(testName, function () {
return fn(this.api, addresses.ACCOUNT_X)
})
}
@@ -66,7 +66,7 @@ describe('RippleAPI [Test Runner]', function() {
}
// Report any missing tests.
const allTestedMethods = new Set(allTestSuites.map(s => s.name))
const allTestedMethods = new Set(allTestSuites.map((s) => s.name))
for (const methodName of allPublicMethods) {
if (!allTestedMethods.has(methodName)) {
// TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures.

View File

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

View File

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

View File

@@ -26,9 +26,9 @@ function fillShamapTest(shamap: any, keys: string[], hashes: string[]) {
}
}
describe('SHAMap', function() {
describe('#addItem', function() {
it('will add new nodes to v1', function() {
describe('SHAMap', function () {
describe('#addItem', function () {
it('will add new nodes to v1', function () {
var keys = [
'b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8',
'b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8',

View File

@@ -98,14 +98,14 @@ export function getFreePort() {
return new Promise((resolve, reject) => {
const server = net.createServer()
let port
server.on('listening', function() {
server.on('listening', function () {
port = (server.address() as any).port
server.close()
})
server.on('close', function() {
server.on('close', function () {
resolve(port)
})
server.on('error', function(error) {
server.on('error', function (error) {
reject(error)
})
server.listen(0)
@@ -118,7 +118,7 @@ export function getAllPublicMethods(api: RippleAPI) {
...Object.getOwnPropertyNames(api),
...Object.getOwnPropertyNames(RippleAPI.prototype)
])
).filter(key => !key.startsWith('_'))
).filter((key) => !key.startsWith('_'))
}
export function loadTestSuites(): LoadedTestSuite[] {
@@ -126,7 +126,7 @@ export function loadTestSuites(): LoadedTestSuite[] {
encoding: 'utf8'
})
return allTests
.map(methodName => {
.map((methodName) => {
if (methodName.startsWith('.DS_Store')) {
return null
}