Reduce dependencies on lodash (#1467)

* assign -> Object.assign

* replace isundefined

* remove forEach

* remove some

* remove reduce

* remove keys

* remove map

* remove includes

* remove filter

* remove last

* remove isstring

* remove every

* remove rearg

* remove indexOf

* remove values

* remove startswith

* remove first and pick

* build smaller lodash

* remove lodash.isequal package

* add lodash-cli dev dependency

* add lodash script

* test fix

* Revert "build smaller lodash" This reverts commit 979446e57f60b29cb5d377b54efe91cfbeae0707.

* upgrade npm

* change ===/!== undefined to ==/!= null
This commit is contained in:
Mayukha Vadari
2021-07-29 20:18:08 -04:00
committed by GitHub
parent 4e49b6a99c
commit 6e0fff2ad6
52 changed files with 3348 additions and 3271 deletions

View File

@@ -26,7 +26,6 @@
"https-proxy-agent": "^5.0.0",
"jsonschema": "1.2.2",
"lodash": "^4.17.4",
"lodash.isequal": "^4.5.0",
"ripple-address-codec": "^4.1.1",
"ripple-binary-codec": "^1.1.3",
"ripple-keypairs": "^1.0.3",

View File

@@ -150,7 +150,7 @@ class RippleAPI extends EventEmitter {
this._feeCushion = options.feeCushion || 1.2
this._maxFeeXRP = options.maxFeeXRP || '2'
const serverURL = options.server
if (serverURL !== undefined) {
if (serverURL != null) {
this.connection = new Connection(serverURL, options)
this.connection.on('ledgerClosed', (message) => {
this.emit('ledger', formatLedgerClose(message))
@@ -320,7 +320,7 @@ class RippleAPI extends EventEmitter {
}
// If limit is not provided, fetches all data over multiple requests.
// NOTE: This may return much more than needed. Set limit when possible.
const countTo: number = params.limit !== undefined ? params.limit : Infinity
const countTo: number = params.limit != null ? params.limit : Infinity
let count: number = 0
let marker: string = params.marker
let lastBatchLength: number

View File

@@ -1,4 +1,3 @@
import * as _ from 'lodash'
import {RippleAPI, APIOptions} from './api'
class RippleAPIBroadcast extends RippleAPI {
@@ -9,7 +8,7 @@ class RippleAPIBroadcast extends RippleAPI {
super(options)
const apis: RippleAPI[] = servers.map(
(server) => new RippleAPI(_.assign({}, options, {server}))
(server) => new RippleAPI(Object.assign({}, options, {server}))
)
// exposed for testing
@@ -51,7 +50,7 @@ class RippleAPIBroadcast extends RippleAPI {
onLedgerEvent(ledger) {
if (
ledger.ledgerVersion > this.ledgerVersion ||
this.ledgerVersion === undefined
this.ledgerVersion == null
) {
this.ledgerVersion = ledger.ledgerVersion
this.emit('ledger', ledger)

View File

@@ -68,7 +68,7 @@ const INTENTIONAL_DISCONNECT_CODE = 4000
*/
function createWebSocket(url: string, config: ConnectionOptions): WebSocket {
const options: WebSocket.ClientOptions = {}
if (config.proxy !== undefined) {
if (config.proxy != null) {
const parsedURL = parseUrl(url)
const parsedProxyURL = parseUrl(config.proxy)
const proxyOverrides = _.omitBy(
@@ -81,9 +81,9 @@ function createWebSocket(url: string, config: ConnectionOptions): WebSocket {
passphrase: config.passphrase,
cert: config.certificate
},
_.isUndefined
value => value == null
)
const proxyOptions = _.assign({}, parsedProxyURL, proxyOverrides)
const proxyOptions = Object.assign({}, parsedProxyURL, proxyOverrides)
let HttpsProxyAgent
try {
HttpsProxyAgent = require('https-proxy-agent')
@@ -92,7 +92,7 @@ function createWebSocket(url: string, config: ConnectionOptions): WebSocket {
}
options.agent = new HttpsProxyAgent(proxyOptions)
}
if (config.authorization !== undefined) {
if (config.authorization != null) {
const base64 = Buffer.from(config.authorization).toString('base64')
options.headers = {Authorization: `Basic ${base64}`}
}
@@ -103,9 +103,9 @@ function createWebSocket(url: string, config: ConnectionOptions): WebSocket {
passphrase: config.passphrase,
cert: config.certificate
},
_.isUndefined
value => value == null
)
const websocketOptions = _.assign({}, options, optionsOverrides)
const websocketOptions = Object.assign({}, options, optionsOverrides)
const websocket = new WebSocket(url, null, websocketOptions)
// we will have a listener for each outstanding request,
// so we have to raise the limit (the default is 10)
@@ -345,7 +345,7 @@ export class Connection extends EventEmitter {
this.emit('error', 'badMessage', error.message, message)
return
}
if (data.type === undefined && data.error) {
if (data.type == null && data.error) {
this.emit('error', data.error, data.error_message, data) // e.g. slowDown
return
}

View File

@@ -45,14 +45,14 @@ class RangeSet {
parseAndAddRanges(rangesString: string) {
const rangeStrings = rangesString.split(',')
_.forEach(rangeStrings, (rangeString) => {
rangeStrings.forEach((rangeString) => {
const range = rangeString.split('-').map(Number)
this.addRange(range[0], range.length === 1 ? range[0] : range[1])
})
}
containsRange(start: number, end: number) {
return _.some(this.ranges, (range) => range[0] <= start && range[1] >= end)
return this.ranges.some((range) => range[0] <= start && range[1] >= end)
}
containsValue(value: number) {

View File

@@ -126,7 +126,7 @@ function loadSchemas() {
require('./schemas/input/combine.json')
]
const titles = schemas.map((schema) => schema.title)
const duplicates = _.keys(_.pickBy(_.countBy(titles), (count) => count > 1))
const duplicates = Object.keys(_.pickBy(_.countBy(titles), (count) => count > 1))
assert.ok(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates)
const validator = new Validator()
// Register custom format validators that ignore undefined instances
@@ -135,7 +135,7 @@ function loadSchemas() {
// This relies on "format": "xAddress" in `x-address.json`!
validator.customFormats.xAddress = function (instance) {
if (instance === undefined) {
if (instance == null) {
return true
}
return isValidXAddress(instance)
@@ -143,21 +143,21 @@ function loadSchemas() {
// This relies on "format": "classicAddress" in `classic-address.json`!
validator.customFormats.classicAddress = function (instance) {
if (instance === undefined) {
if (instance == null) {
return true
}
return isValidAddress(instance)
}
validator.customFormats.secret = function (instance) {
if (instance === undefined) {
if (instance == null) {
return true
}
return isValidSecret(instance)
}
// Register under the root URI '/'
_.forEach(schemas, (schema) =>
schemas.forEach((schema) =>
validator.addSchema(schema, '/' + schema.title)
)
return validator
@@ -168,7 +168,7 @@ const schemaValidator = loadSchemas()
function schemaValidate(schemaName: string, object: any): void {
// Lookup under the root URI '/'
const schema = schemaValidator.getSchema('/' + schemaName)
if (schema === undefined) {
if (schema == null) {
throw new ValidationError('no schema for ' + schemaName)
}
const result = schemaValidator.validate(object, schema)

View File

@@ -33,8 +33,9 @@ export type GetServerInfoResponse = {
networkLedger?: string
}
function renameKeys(object, mapping) {
_.forEach(mapping, (to, from) => {
function renameKeys(object: Record<string, any>, mapping: Record<string, any>) {
Object.entries(mapping).forEach(entry => {
const [from, to] = entry;
object[to] = object[from]
delete object[from]
})
@@ -62,16 +63,16 @@ function getServerInfo(this: RippleAPI): Promise<GetServerInfoResponse> {
// This is a public API that can be called directly.
// This is not used by the `prepare*` methods. See `src/transaction/utils.ts`
async function getFee(this: RippleAPI, cushion?: number): Promise<string> {
if (cushion === undefined) {
if (cushion == null) {
cushion = this._feeCushion
}
if (cushion === undefined) {
if (cushion == null) {
cushion = 1.2
}
const serverInfo = (await this.request('server_info')).info
const baseFeeXrp = new BigNumber(serverInfo.validated_ledger.base_fee_xrp)
if (serverInfo.load_factor === undefined) {
if (serverInfo.load_factor == null) {
// https://github.com/ripple/rippled/issues/3812#issuecomment-816871100
serverInfo.load_factor = 1
}

View File

@@ -127,9 +127,8 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
if (typeof obj === 'object') {
const accumulator = Array.isArray(obj) ? [] : {}
let newKey
return _.reduce(
obj,
(result, value, key) => {
return Object.entries(obj).reduce(
(result, [key, value]) => {
newKey = key
// taking this out of function leads to error in PhantomJS
const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g
@@ -146,7 +145,7 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
}
function removeUndefined<T extends object>(obj: T): T {
return _.omitBy(obj, _.isUndefined) as T
return _.omitBy(obj, value => value == null) as T
}
/**

View File

@@ -8,9 +8,9 @@ function error(text) {
function validateLedgerRange(options) {
if (
!_.isUndefined(options) &&
!_.isUndefined(options.minLedgerVersion) &&
!_.isUndefined(options.maxLedgerVersion)
options != null &&
options.minLedgerVersion != null &&
options.maxLedgerVersion != null
) {
if (Number(options.minLedgerVersion) > Number(options.maxLedgerVersion)) {
throw error('minLedgerVersion must not be greater than maxLedgerVersion')

View File

@@ -18,29 +18,38 @@ export type GetBalanceSheet = {
}>
}
function formatBalanceSheet(balanceSheet): GetBalanceSheet {
type BalanceSheet = {
account: string,
assets?: Record<string, any>,
balances?: Record<string, any>,
obligations?: Record<string, string>,
ledger_current_index?: number,
validated?: boolean
}
function formatBalanceSheet(balanceSheet: BalanceSheet): GetBalanceSheet {
const result: GetBalanceSheet = {}
if (!_.isUndefined(balanceSheet.balances)) {
if (balanceSheet.balances != null) {
result.balances = []
_.forEach(balanceSheet.balances, (balances, counterparty) => {
_.forEach(balances, (balance) => {
Object.entries(balanceSheet.balances).forEach(entry => {
const [counterparty, balances] = entry;
balances.forEach((balance) => {
result.balances.push(Object.assign({counterparty}, balance))
})
})
}
if (!_.isUndefined(balanceSheet.assets)) {
if (balanceSheet.assets != null) {
result.assets = []
_.forEach(balanceSheet.assets, (assets, counterparty) => {
_.forEach(assets, (balance) => {
Object.entries(balanceSheet.assets).forEach(([counterparty, assets]) => {
assets.forEach((balance) => {
result.assets.push(Object.assign({counterparty}, balance))
})
})
}
if (!_.isUndefined(balanceSheet.obligations)) {
result.obligations = _.map(
balanceSheet.obligations as {[key: string]: string},
(value, currency) => ({currency, value})
if (balanceSheet.obligations != null) {
result.obligations = Object.entries(balanceSheet.obligations as {[key: string]: string}).map(
([currency, value]) => ({currency, value})
)
}

View File

@@ -43,7 +43,7 @@ function getLedgerVersionHelper(
connection: Connection,
optionValue?: number
): Promise<number> {
if (optionValue !== undefined && optionValue !== null) {
if (optionValue != null && optionValue !== null) {
return Promise.resolve(optionValue)
}
return connection.getLedgerVersion()

View File

@@ -27,7 +27,7 @@ function parseAccountDelete(tx: any): FormattedAccountDelete {
destinationTag: tx.DestinationTag,
destinationXAddress: classicAddressToXAddress(
tx.Destination,
tx.DestinationTag === undefined ? false : tx.DestinationTag,
tx.DestinationTag == null ? false : tx.DestinationTag,
false
)
})

View File

@@ -18,7 +18,7 @@ function parseFields(data: any): object {
const settings: any = {}
for (const fieldName in AccountFields) {
const fieldValue = data[fieldName]
if (fieldValue !== undefined) {
if (fieldValue != null) {
const info = AccountFields[fieldName]
settings[info.name] = parseField(info, fieldValue)
}
@@ -36,8 +36,7 @@ function parseFields(data: any): object {
settings.signers.threshold = data.signer_lists[0].SignerQuorum
}
if (data.signer_lists[0].SignerEntries) {
settings.signers.weights = _.map(
data.signer_lists[0].SignerEntries,
settings.signers.weights = data.signer_lists[0].SignerEntries.map(
(entry: any) => {
return {
address: entry.SignerEntry.Account,

View File

@@ -24,7 +24,7 @@ export type FormattedLedger = {
function parseTransactionWrapper(ledgerVersion, tx) {
// renames metaData to meta and adds ledger_index
const transaction = _.assign({}, _.omit(tx, 'metaData'), {
const transaction = Object.assign({}, _.omit(tx, 'metaData'), {
meta: tx.metaData,
ledger_index: ledgerVersion
})
@@ -39,12 +39,11 @@ function parseTransactions(transactions, ledgerVersion) {
if (_.isEmpty(transactions)) {
return {}
}
if (_.isString(transactions[0])) {
if (typeof transactions[0] === 'string') {
return {transactionHashes: transactions}
}
return {
transactions: _.map(
transactions,
transactions: transactions.map(
_.partial(parseTransactionWrapper, ledgerVersion)
)
}
@@ -54,7 +53,7 @@ function parseState(state) {
if (_.isEmpty(state)) {
return {}
}
if (_.isString(state[0])) {
if (typeof state[0] === 'string') {
return {stateHashes: state}
}
return {rawState: JSON.stringify(state)}

View File

@@ -19,7 +19,7 @@ function createAdjustment(
address: string,
adjustmentWithoutAddress: object
): any {
const amountKey = _.keys(adjustmentWithoutAddress)[0]
const amountKey = Object.keys(adjustmentWithoutAddress)[0]
const amount = adjustmentWithoutAddress[amountKey]
return _.set(
{address: address},
@@ -37,7 +37,7 @@ function parseAlternative(
// we use "maxAmount"/"minAmount" here so that the result can be passed
// directly to preparePayment
const amounts =
alternative.destination_amount !== undefined
alternative.destination_amount != null
? {
source: {amount: parseAmount(alternative.source_amount)},
destination: {minAmount: parseAmount(alternative.destination_amount)}

View File

@@ -22,11 +22,12 @@ function parseFlags(tx: any): any {
const oldFlags = _.get(node.PreviousFields, 'Flags')
const newFlags = _.get(node.FinalFields, 'Flags')
if (oldFlags !== undefined && newFlags !== undefined) {
if (oldFlags != null && newFlags != null) {
const changedFlags = oldFlags ^ newFlags
const setFlags = newFlags & changedFlags
const clearedFlags = oldFlags & changedFlags
_.forEach(AccountFlags, (flagValue, flagName) => {
Object.entries(AccountFlags).forEach(entry => {
const [flagName, flagValue] = entry;
if (setFlags & flagValue) {
settings[flagName] = true
} else if (clearedFlags & flagValue) {
@@ -58,7 +59,7 @@ function parseSettings(tx: any) {
txType === 'SignerListSet'
)
return _.assign({}, parseFlags(tx), parseFields(tx))
return Object.assign({}, parseFlags(tx), parseFields(tx))
}
export default parseSettings

View File

@@ -1,4 +1,3 @@
import * as _ from 'lodash'
import transactionParser from 'ripple-lib-transactionparser'
import BigNumber from 'bignumber.js'
import * as common from '../../common'
@@ -6,6 +5,29 @@ import parseAmount from './amount'
import {Amount, Memo} from '../../common/types/objects'
type OfferDescription = {
direction: string,
quantity: any,
totalPrice: any,
sequence: number,
status: string,
makerExchangeRate: string
}
type Orderbook = {
[key: string]: OfferDescription[]
}
type BalanceSheetItem = {
counterparty: string,
currency: string,
value: string
}
type BalanceSheet = {
[key: string]: BalanceSheetItem[]
}
function adjustQualityForXRP(
quality: string,
takerGetsCurrency: string,
@@ -41,16 +63,16 @@ function removeEmptyCounterparty(amount) {
}
}
function removeEmptyCounterpartyInBalanceChanges(balanceChanges) {
_.forEach(balanceChanges, (changes) => {
_.forEach(changes, removeEmptyCounterparty)
function removeEmptyCounterpartyInBalanceChanges(balanceChanges: BalanceSheet) {
Object.entries(balanceChanges).forEach(([_, changes]) => {
changes.forEach(removeEmptyCounterparty)
})
}
function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) {
_.forEach(orderbookChanges, (changes) => {
_.forEach(changes, (change) => {
_.forEach(change, removeEmptyCounterparty)
function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges: Orderbook) {
Object.entries(orderbookChanges).forEach(([_, changes]) => {
changes.forEach((change) => {
Object.entries(change).forEach(removeEmptyCounterparty)
})
})
}

View File

@@ -26,7 +26,7 @@ function addParams(
result: RippledPathsResponse
): RippledPathsResponse {
return _.defaults(
_.assign({}, result, {
Object.assign({}, result, {
source_account: request.source_account,
source_currencies: request.source_currencies
}),
@@ -38,7 +38,7 @@ function requestPathFind(
connection: Connection,
pathfind: PathFind
): Promise<RippledPathsResponse> {
const destinationAmount: Amount = _.assign(
const destinationAmount: Amount = Object.assign(
{
// This is converted back to drops by toRippledAmount()
value:
@@ -67,7 +67,7 @@ function requestPathFind(
)
}
if (pathfind.source.amount) {
if (pathfind.destination.amount.value !== undefined) {
if (pathfind.destination.amount.value != null) {
throw new ValidationError(
'Cannot specify both source.amount' +
' and destination.amount.value in getPaths'
@@ -112,7 +112,7 @@ function conditionallyAddDirectXRPPath(
): Promise<RippledPathsResponse> {
if (
isRippledIOUAmount(paths.destination_amount) ||
!_.includes(paths.destination_currencies, 'XRP')
!paths.destination_currencies.includes('XRP')
) {
return Promise.resolve(paths)
}
@@ -127,10 +127,10 @@ function filterSourceFundsLowPaths(
): RippledPathsResponse {
if (
pathfind.source.amount &&
pathfind.destination.amount.value === undefined &&
pathfind.destination.amount.value == null &&
paths.alternatives
) {
paths.alternatives = _.filter(paths.alternatives, (alt) => {
paths.alternatives = paths.alternatives.filter((alt) => {
if (!alt.source_amount) {
return false
}
@@ -155,9 +155,8 @@ function formatResponse(pathfind: PathFind, paths: RippledPathsResponse) {
return parsePathfind(paths)
}
if (
paths.destination_currencies !== undefined &&
!_.includes(
paths.destination_currencies,
paths.destination_currencies != null &&
!paths.destination_currencies.includes(
pathfind.destination.amount.currency
)
) {

View File

@@ -11,7 +11,7 @@ function formatResponse(
response: LedgerEntryResponse
): FormattedPaymentChannel {
if (
response.node === undefined ||
response.node == null ||
response.node.LedgerEntryType !== 'PayChannel'
) {
throw new NotFoundError('Payment channel ledger entry not found')

View File

@@ -1,4 +1,3 @@
import * as _ from 'lodash'
import parseFields from './parse/fields'
import {validate, constants, ensureClassicAddress} from '../common'
import {FormattedSettings} from '../common/types/objects'
@@ -33,7 +32,7 @@ function formatSettings(response: AccountInfoResponse) {
const data = response.account_data
const parsedFlags = parseAccountFlags(data.Flags, {excludeFalse: true})
const parsedFields = parseFields(data)
return _.assign({}, parsedFlags, parsedFields)
return Object.assign({}, parsedFlags, parsedFields)
}
export async function getSettings(

View File

@@ -1,4 +1,3 @@
import * as _ from 'lodash'
import * as utils from './utils'
import parseTransaction from './parse/transaction'
import {validate, errors} from '../common'
@@ -50,7 +49,7 @@ function attachTransactionDate(
.request(request)
.then((data) => {
if (typeof data.ledger.close_time === 'number') {
return _.assign({date: data.ledger.close_time}, tx)
return Object.assign({date: data.ledger.close_time}, tx)
}
throw new errors.UnexpectedError('Ledger missing close_time')
})

View File

@@ -40,7 +40,7 @@ function parseAccountTxTransaction(tx, includeRawTransaction: boolean) {
const _tx = tx.tx_blob ? parseBinaryTransaction(tx) : tx
// rippled uses a different response format for 'account_tx' than 'tx'
return parseTransaction(
_.assign({}, _tx.tx, {meta: _tx.meta, validated: _tx.validated}),
Object.assign({}, _tx.tx, {meta: _tx.meta, validated: _tx.validated}),
includeRawTransaction
)
}
@@ -69,7 +69,7 @@ function transactionFilter(
if (filters.excludeFailures && tx.outcome.result !== 'tesSUCCESS') {
return false
}
if (filters.types && !_.includes(filters.types, tx.type)) {
if (filters.types && !filters.types.includes(tx.type)) {
return false
}
if (filters.initiated === true && tx.address !== address) {
@@ -150,9 +150,9 @@ function checkForLedgerGaps(
// the range of ledgers spanned by those transactions
if (options.limit && transactions.length === options.limit) {
if (options.earliestFirst) {
maxLedgerVersion = _.last(transactions)!.outcome.ledgerVersion
maxLedgerVersion = transactions[transactions.length-1]!.outcome.ledgerVersion
} else {
minLedgerVersion = _.last(transactions)!.outcome.ledgerVersion
minLedgerVersion = transactions[transactions.length-1]!.outcome.ledgerVersion
}
}
@@ -170,10 +170,9 @@ function formatResponse(
options: TransactionsOptions,
transactions: GetTransactionsResponse
) {
const compare = options.earliestFirst
? utils.compareTransactions
: _.rearg(utils.compareTransactions, 1, 0)
const sortedTransactions = transactions.sort(compare)
const sortedTransactions = options.earliestFirst
? transactions.sort(utils.compareTransactions)
: transactions.sort(utils.compareTransactions).reverse()
return checkForLedgerGaps(connection, options, sortedTransactions).then(
() => sortedTransactions
)
@@ -209,11 +208,11 @@ function getTransactions(
const bound = options.earliestFirst
? {minLedgerVersion: ledgerVersion}
: {maxLedgerVersion: ledgerVersion}
const startOptions = _.assign({}, defaults, options, {startTx: tx}, bound)
const startOptions = Object.assign({}, defaults, options, {startTx: tx}, bound)
return getTransactionsInternal(this.connection, address, startOptions)
})
}
const newOptions = _.assign({}, defaults, options)
const newOptions = Object.assign({}, defaults, options)
return getTransactionsInternal(this.connection, address, newOptions)
}

View File

@@ -41,7 +41,7 @@ function getRecursiveRecur(
): Promise<Array<any>> {
return getter(marker, limit).then((data) => {
const remaining = limit - data.results.length
if (remaining > 0 && data.marker !== undefined) {
if (remaining > 0 && data.marker != null) {
return getRecursiveRecur(getter, data.marker, remaining).then((results) =>
data.results.concat(results)
)
@@ -58,9 +58,9 @@ function renameCounterpartyToIssuer<T>(
obj: T & {counterparty?: string; issuer?: string}
): T & {issuer?: string} {
const issuer =
obj.counterparty !== undefined
obj.counterparty != null
? obj.counterparty
: obj.issuer !== undefined
: obj.issuer != null
? obj.issuer
: undefined
const withIssuer = Object.assign({}, obj, {issuer})
@@ -74,7 +74,7 @@ function renameCounterpartyToIssuerInOrder(order: RequestBookOffersArgs) {
const taker_gets = renameCounterpartyToIssuer(order.taker_gets)
const taker_pays = renameCounterpartyToIssuer(order.taker_pays)
const changes = {taker_gets, taker_pays}
return _.assign({}, order, _.omitBy(changes, _.isUndefined))
return Object.assign({}, order, _.omitBy(changes, value => value == null))
}
function signum(num) {
@@ -124,13 +124,13 @@ function isPendingLedgerVersion(
function ensureLedgerVersion(this: RippleAPI, options: any): Promise<object> {
if (
Boolean(options) &&
options.ledgerVersion !== undefined &&
options.ledgerVersion != null &&
options.ledgerVersion !== null
) {
return Promise.resolve(options)
}
return this.getLedgerVersion().then((ledgerVersion) =>
_.assign({}, options, {ledgerVersion})
Object.assign({}, options, {ledgerVersion})
)
}

View File

@@ -58,10 +58,10 @@ function computeTransactionHash(
}
return ledger.transactionHash
}
const txs = _.map(transactions, (tx) => {
const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {})
const txs = transactions.map((tx) => {
const mergeTx = Object.assign({}, _.omit(tx, 'tx'), tx.tx || {})
// rename `meta` back to `metaData`
const renameMeta = _.assign(
const renameMeta = Object.assign(
{},
_.omit(mergeTx, 'meta'),
tx.meta ? {metaData: tx.meta} : {}
@@ -70,7 +70,7 @@ function computeTransactionHash(
})
const transactionHash = computeTransactionTreeHash(txs)
if (
ledger.transactionHash !== undefined &&
ledger.transactionHash != null &&
ledger.transactionHash !== transactionHash
) {
throw new common.errors.ValidationError(
@@ -86,7 +86,7 @@ function computeTransactionHash(
}
function computeStateHash(ledger, options: ComputeLedgerHeaderHashOptions) {
if (ledger.rawState === undefined) {
if (ledger.rawState == null) {
if (options.computeTreeHashes) {
throw new common.errors.ValidationError(
'rawState' + ' property is missing from the ledger'
@@ -96,7 +96,7 @@ function computeStateHash(ledger, options: ComputeLedgerHeaderHashOptions) {
}
const state = JSON.parse(ledger.rawState)
const stateHash = computeStateTreeHash(state)
if (ledger.stateHash !== undefined && ledger.stateHash !== stateHash) {
if (ledger.stateHash != null && ledger.stateHash !== stateHash) {
throw new common.errors.ValidationError(
'stateHash in header' + ' does not match computed hash of state'
)
@@ -116,7 +116,7 @@ function computeLedgerHeaderHash(
transactionHash: computeTransactionHash(ledger, options),
stateHash: computeStateHash(ledger, options)
}
return hashLedgerHeader(_.assign({}, ledger, subhashes))
return hashLedgerHeader(Object.assign({}, ledger, subhashes))
}
export default computeLedgerHeaderHash

View File

@@ -29,11 +29,11 @@ function createCheckCashTransaction(
CheckID: checkCash.checkID
}
if (checkCash.amount !== undefined) {
if (checkCash.amount != null) {
txJSON.Amount = toRippledAmount(checkCash.amount)
}
if (checkCash.deliverMin !== undefined) {
if (checkCash.deliverMin != null) {
txJSON.DeliverMin = toRippledAmount(checkCash.deliverMin)
}

View File

@@ -24,15 +24,15 @@ function createCheckCreateTransaction(
SendMax: toRippledAmount(check.sendMax)
}
if (check.destinationTag !== undefined) {
if (check.destinationTag != null) {
txJSON.DestinationTag = check.destinationTag
}
if (check.expiration !== undefined) {
if (check.expiration != null) {
txJSON.Expiration = iso8601ToRippleTime(check.expiration)
}
if (check.invoiceID !== undefined) {
if (check.invoiceID != null) {
txJSON.InvoiceID = check.invoiceID
}

View File

@@ -22,20 +22,19 @@ function combine(signedTransactions: Array<string>): object {
// TODO: signedTransactions is an array of strings in the documentation, but
// tests and this code handle it as an array of objects. Fix!
const txs: any[] = _.map(signedTransactions, binary.decode)
const txs: any[] = signedTransactions.map(binary.decode)
const tx = _.omit(txs[0], 'Signers')
if (!_.every(txs, (_tx) => _.isEqual(tx, _.omit(_tx, 'Signers')))) {
if (!txs.every((_tx) => _.isEqual(tx, _.omit(_tx, 'Signers')))) {
throw new utils.common.errors.ValidationError(
'txJSON is not the same for all signedTransactions'
)
}
const unsortedSigners = _.reduce(
txs,
const unsortedSigners = txs.reduce(
(accumulator, _tx) => accumulator.concat(_tx.Signers || []),
[]
)
const signers = unsortedSigners.sort(compareSigners)
const signedTx = _.assign({}, tx, {Signers: signers})
const signedTx = Object.assign({}, tx, {Signers: signers})
const signedTransaction = binary.encode(signedTx)
const id = computeBinaryTransactionHash(signedTransaction)
return {signedTransaction, id}

View File

@@ -23,7 +23,7 @@ function createEscrowCancellationTransaction(
Owner: payment.owner,
OfferSequence: payment.escrowSequence
}
if (payment.memos !== undefined) {
if (payment.memos != null) {
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
return txJSON

View File

@@ -27,22 +27,22 @@ function createEscrowCreationTransaction(
Amount: xrpToDrops(payment.amount)
}
if (payment.condition !== undefined) {
if (payment.condition != null) {
txJSON.Condition = payment.condition
}
if (payment.allowCancelAfter !== undefined) {
if (payment.allowCancelAfter != null) {
txJSON.CancelAfter = iso8601ToRippleTime(payment.allowCancelAfter)
}
if (payment.allowExecuteAfter !== undefined) {
if (payment.allowExecuteAfter != null) {
txJSON.FinishAfter = iso8601ToRippleTime(payment.allowExecuteAfter)
}
if (payment.sourceTag !== undefined) {
if (payment.sourceTag != null) {
txJSON.SourceTag = payment.sourceTag
}
if (payment.destinationTag !== undefined) {
if (payment.destinationTag != null) {
txJSON.DestinationTag = payment.destinationTag
}
if (payment.memos !== undefined) {
if (payment.memos != null) {
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
if (

View File

@@ -31,13 +31,13 @@ function createEscrowExecutionTransaction(
)
}
if (payment.condition !== undefined) {
if (payment.condition != null) {
txJSON.Condition = payment.condition
}
if (payment.fulfillment !== undefined) {
if (payment.fulfillment != null) {
txJSON.Fulfillment = payment.fulfillment
}
if (payment.memos !== undefined) {
if (payment.memos != null) {
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
return txJSON

View File

@@ -35,13 +35,13 @@ function createOrderTransaction(
if (order.fillOrKill === true) {
txJSON.Flags |= offerFlags.FillOrKill
}
if (order.expirationTime !== undefined) {
if (order.expirationTime != null) {
txJSON.Expiration = iso8601ToRippleTime(order.expirationTime)
}
if (order.orderToReplace !== undefined) {
if (order.orderToReplace != null) {
txJSON.OfferSequence = order.orderToReplace
}
if (order.memos !== undefined) {
if (order.memos != null) {
txJSON.Memos = order.memos.map(utils.convertMemo)
}
return txJSON as OfferCreateTransaction

View File

@@ -12,7 +12,7 @@ function createOrderCancellationTransaction(
Account: account,
OfferSequence: orderCancellation.orderSequence
}
if (orderCancellation.memos !== undefined) {
if (orderCancellation.memos != null) {
txJSON.Memos = orderCancellation.memos.map(utils.convertMemo)
}
return txJSON

View File

@@ -26,10 +26,10 @@ function createPaymentChannelClaimTransaction(
Flags: 0
}
if (claim.balance !== undefined) {
if (claim.balance != null) {
txJSON.Balance = xrpToDrops(claim.balance)
}
if (claim.amount !== undefined) {
if (claim.amount != null) {
txJSON.Amount = xrpToDrops(claim.amount)
}
@@ -40,10 +40,10 @@ function createPaymentChannelClaimTransaction(
)
}
if (claim.signature !== undefined) {
if (claim.signature != null) {
txJSON.Signature = claim.signature
}
if (claim.publicKey !== undefined) {
if (claim.publicKey != null) {
txJSON.PublicKey = claim.publicKey
}

View File

@@ -26,13 +26,13 @@ function createPaymentChannelCreateTransaction(
PublicKey: paymentChannel.publicKey.toUpperCase()
}
if (paymentChannel.cancelAfter !== undefined) {
if (paymentChannel.cancelAfter != null) {
txJSON.CancelAfter = iso8601ToRippleTime(paymentChannel.cancelAfter)
}
if (paymentChannel.sourceTag !== undefined) {
if (paymentChannel.sourceTag != null) {
txJSON.SourceTag = paymentChannel.sourceTag
}
if (paymentChannel.destinationTag !== undefined) {
if (paymentChannel.destinationTag != null) {
txJSON.DestinationTag = paymentChannel.destinationTag
}

View File

@@ -20,7 +20,7 @@ function createPaymentChannelFundTransaction(
Amount: xrpToDrops(fund.amount)
}
if (fund.expiration !== undefined) {
if (fund.expiration != null) {
txJSON.Expiration = iso8601ToRippleTime(fund.expiration)
}

View File

@@ -40,13 +40,13 @@ export interface Payment {
function isMaxAdjustment(
source: Adjustment | MaxAdjustment
): source is MaxAdjustment {
return (source as MaxAdjustment).maxAmount !== undefined
return (source as MaxAdjustment).maxAmount != null
}
function isMinAdjustment(
destination: Adjustment | MinAdjustment
): destination is MinAdjustment {
return (destination as MinAdjustment).minAmount !== undefined
return (destination as MinAdjustment).minAmount != null
}
function isXRPToXRPPayment(payment: Payment): boolean {
@@ -68,7 +68,7 @@ function isIOUWithoutCounterparty(amount: Amount): boolean {
amount &&
amount.currency !== 'XRP' &&
amount.currency !== 'drops' &&
amount.counterparty === undefined
amount.counterparty == null
)
}
@@ -76,8 +76,8 @@ function applyAnyCounterpartyEncoding(payment: Payment): void {
// Convert blank counterparty to sender or receiver's address
// (Ripple convention for 'any counterparty')
// https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount
_.forEach([payment.source, payment.destination], (adjustment) => {
_.forEach(['amount', 'minAmount', 'maxAmount'], (key) => {
[payment.source, payment.destination].forEach((adjustment) => {
['amount', 'minAmount', 'maxAmount'].forEach((key) => {
if (isIOUWithoutCounterparty(adjustment[key])) {
adjustment[key].counterparty = adjustment.address
}
@@ -102,7 +102,7 @@ function createMaximalAmount(amount: Amount): Amount {
} else {
maxValue = maxIOUValue
}
return _.assign({}, amount, {value: maxValue})
return Object.assign({}, amount, {value: maxValue})
}
/**
@@ -151,8 +151,8 @@ function createPaymentTransaction(
}
if (
addressToVerifyAgainst.tag !== undefined &&
sourceAddressAndTag.tag !== undefined &&
addressToVerifyAgainst.tag != null &&
sourceAddressAndTag.tag != null &&
addressToVerifyAgainst.tag !== sourceAddressAndTag.tag
) {
throw new ValidationError(
@@ -201,17 +201,17 @@ function createPaymentTransaction(
Flags: 0
}
if (payment.invoiceID !== undefined) {
if (payment.invoiceID != null) {
txJSON.InvoiceID = payment.invoiceID
}
if (sourceAddressAndTag.tag !== undefined) {
if (sourceAddressAndTag.tag != null) {
txJSON.SourceTag = sourceAddressAndTag.tag
}
if (destinationAddressAndTag.tag !== undefined) {
if (destinationAddressAndTag.tag != null) {
txJSON.DestinationTag = destinationAddressAndTag.tag
}
if (payment.memos !== undefined) {
txJSON.Memos = _.map(payment.memos, utils.convertMemo)
if (payment.memos != null) {
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
if (payment.noDirectRipple === true) {
txJSON.Flags |= paymentFlags.NoRippleDirect
@@ -234,7 +234,7 @@ function createPaymentTransaction(
txJSON.DeliverMin = toRippledAmount(destinationAmount)
}
if (payment.paths !== undefined) {
if (payment.paths != null) {
txJSON.Paths = JSON.parse(payment.paths)
}
} else if (payment.allowPartialPayment === true) {

View File

@@ -17,7 +17,7 @@ function setTransactionFlags(
txJSON: TransactionJSON,
values: FormattedSettings
) {
const keys = Object.keys(values).filter((key) => AccountFlagIndices[key] !== undefined)
const keys = Object.keys(values).filter((key) => AccountFlagIndices[key] != null)
assert.ok(
keys.length <= 1,
'ERROR: can only set one setting per transaction'
@@ -25,7 +25,7 @@ function setTransactionFlags(
const flagName = keys[0]
const value = values[flagName]
const index = AccountFlagIndices[flagName]
if (index !== undefined) {
if (index != null) {
if (value) {
txJSON.SetFlag = index
} else {
@@ -105,7 +105,7 @@ function createSettingsTransactionWithoutMemos(
})
}
if (settings.signers !== undefined) {
if (settings.signers != null) {
const setSignerList = {
TransactionType: 'SignerListSet',
Account: account,
@@ -113,7 +113,7 @@ function createSettingsTransactionWithoutMemos(
SignerQuorum: settings.signers.threshold
}
if (settings.signers.weights !== undefined) {
if (settings.signers.weights != null) {
setSignerList.SignerEntries = settings.signers.weights.map(
formatSignerEntry
)
@@ -131,7 +131,7 @@ function createSettingsTransactionWithoutMemos(
setTransactionFlags(txJSON, settingsWithoutMemos)
setTransactionFields(txJSON, settings) // Sets `null` fields to their `default`.
if (txJSON.TransferRate !== undefined) {
if (txJSON.TransferRate != null) {
txJSON.TransferRate = convertTransferRate(txJSON.TransferRate)
}
return txJSON
@@ -142,7 +142,7 @@ function createSettingsTransaction(
settings: FormattedSettings
): SettingsTransaction {
const txJSON = createSettingsTransactionWithoutMemos(account, settings)
if (settings.memos !== undefined) {
if (settings.memos != null) {
txJSON.Memos = settings.memos.map(utils.convertMemo)
}
return txJSON

View File

@@ -1,4 +1,4 @@
import isEqual from 'lodash.isequal'
import _ from 'lodash'
import * as utils from './utils'
import keypairs from 'ripple-keypairs'
import binaryCodec from 'ripple-binary-codec'
@@ -95,7 +95,7 @@ function objectDiff(a: object, b: object): object {
return
}
if (type1 === '[object Array]') {
if (!isEqual(i1, i2)) {
if (!_.isEqual(i1, i2)) {
diffs[k] = i2 // If arrays do not match, add second item to diffs
}
return
@@ -179,7 +179,7 @@ function checkTxSerialization(serialized: string, tx: TransactionJSON): void {
return memo
})
if (!isEqual(decoded, tx)) {
if (!_.isEqual(decoded, tx)) {
const error = new utils.common.errors.ValidationError(
'Serialized transaction does not match original txJSON. See `error.data`'
)

View File

@@ -4,7 +4,6 @@
// fail_hard: failHard
// });
import * as _ from 'lodash'
import * as utils from './utils'
import {validate} from '../common'
import {RippleAPI} from '..'
@@ -21,7 +20,7 @@ function isImmediateRejection(engineResult: string): boolean {
// if the required fee changes (this does not occur at the time of
// this writing, but it could change in the future)
// all other error classes can potentially result in transaction validation
return _.startsWith(engineResult, 'tem')
return engineResult.startsWith('tem')
}
function formatSubmitResponse(response): FormattedSubmitResponse {

View File

@@ -29,26 +29,26 @@ function createTrustlineTransaction(
LimitAmount: limit,
Flags: 0
}
if (trustline.qualityIn !== undefined) {
if (trustline.qualityIn != null) {
txJSON.QualityIn = convertQuality(trustline.qualityIn)
}
if (trustline.qualityOut !== undefined) {
if (trustline.qualityOut != null) {
txJSON.QualityOut = convertQuality(trustline.qualityOut)
}
if (trustline.authorized === true) {
txJSON.Flags |= trustlineFlags.SetAuth
}
if (trustline.ripplingDisabled !== undefined) {
if (trustline.ripplingDisabled != null) {
txJSON.Flags |= trustline.ripplingDisabled
? trustlineFlags.NoRipple
: trustlineFlags.ClearNoRipple
}
if (trustline.frozen !== undefined) {
if (trustline.frozen != null) {
txJSON.Flags |= trustline.frozen
? trustlineFlags.SetFreeze
: trustlineFlags.ClearFreeze
}
if (trustline.memos !== undefined) {
if (trustline.memos != null) {
txJSON.Memos = trustline.memos.map(utils.convertMemo)
}
return txJSON

View File

@@ -24,9 +24,9 @@ function formatPrepareResponse(txJSON: any): Prepare {
const instructions = {
fee: common.dropsToXrp(txJSON.Fee),
maxLedgerVersion:
txJSON.LastLedgerSequence === undefined ? null : txJSON.LastLedgerSequence
txJSON.LastLedgerSequence == null ? null : txJSON.LastLedgerSequence
}
if (txJSON.TicketSequence !== undefined) {
if (txJSON.TicketSequence != null) {
instructions['ticketSequence'] = txJSON.TicketSequence
} else {
instructions['sequence'] = txJSON.Sequence
@@ -90,7 +90,7 @@ function getClassicAccountAndTag(
): ClassicAccountAndTag {
if (isValidXAddress(Account)) {
const classic = xAddressToClassicAddress(Account)
if (expectedTag !== undefined && classic.tag !== expectedTag) {
if (expectedTag != null && classic.tag !== expectedTag) {
throw new ValidationError(
'address includes a tag that does not match the tag specified in the transaction'
)
@@ -118,7 +118,7 @@ function prepareTransaction(
// We allow 0 values in the Sequence schema to support the Tickets feature
// When a ticketSequence is used, sequence has to be 0
// We validate that a sequence with value 0 is not passed even if the json schema allows it
if (instructions.sequence !== undefined && instructions.sequence === 0) {
if (instructions.sequence != null && instructions.sequence === 0) {
return Promise.reject(new ValidationError('`sequence` cannot be 0'))
}
@@ -152,7 +152,7 @@ function prepareTransaction(
txJSON.Account
)
newTxJSON.Account = classicAccount
if (sourceTag !== undefined) {
if (sourceTag != null) {
if (txJSON.SourceTag && txJSON.SourceTag !== sourceTag) {
return Promise.reject(
new ValidationError(
@@ -172,7 +172,7 @@ function prepareTransaction(
tag: destinationTag
} = getClassicAccountAndTag(txJSON.Destination)
newTxJSON.Destination = destinationAccount
if (destinationTag !== undefined) {
if (destinationTag != null) {
if (
TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD.includes(
txJSON.TransactionType
@@ -243,7 +243,7 @@ function prepareTransaction(
return Promise.resolve()
}
const offset =
instructions.maxLedgerVersionOffset !== undefined
instructions.maxLedgerVersionOffset != null
? instructions.maxLedgerVersionOffset
: 3
return api.connection.getLedgerVersion().then((ledgerVersion) => {
@@ -270,10 +270,10 @@ function prepareTransaction(
return Promise.resolve()
}
const multiplier =
instructions.signersCount === undefined
instructions.signersCount == null
? 1
: instructions.signersCount + 1
if (instructions.fee !== undefined) {
if (instructions.fee != null) {
const fee = new BigNumber(instructions.fee)
if (fee.isGreaterThan(api._maxFeeXRP)) {
return Promise.reject(
@@ -296,7 +296,7 @@ function prepareTransaction(
// feeRef is the reference transaction cost in "fee units"
const extraFee =
newTxJSON.TransactionType !== 'EscrowFinish' ||
newTxJSON.Fulfillment === undefined
newTxJSON.Fulfillment == null
? 0
: cushion *
feeRef *
@@ -318,9 +318,9 @@ function prepareTransaction(
}
async function prepareSequence(): Promise<void> {
if (instructions.sequence !== undefined) {
if (instructions.sequence != null) {
if (
newTxJSON.Sequence === undefined ||
newTxJSON.Sequence == null ||
instructions.sequence === newTxJSON.Sequence
) {
newTxJSON.Sequence = instructions.sequence
@@ -335,12 +335,12 @@ function prepareTransaction(
}
}
if (newTxJSON.Sequence !== undefined) {
if (newTxJSON.Sequence != null) {
return Promise.resolve()
}
// Ticket Sequence
if (instructions.ticketSequence !== undefined) {
if (instructions.ticketSequence != null) {
newTxJSON.Sequence = 0
newTxJSON.TicketSequence = instructions.ticketSequence
return Promise.resolve()

View File

@@ -203,7 +203,7 @@ export default <TestSuite>{
}
const decoded = binary.decode(result.signedTransaction)
assert(
decoded.Flags === undefined,
decoded.Flags == null,
`Flags = ${decoded.Flags}, should be undefined`
)
assert.deepEqual(result, expectedResult)

View File

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

View File

@@ -31,8 +31,8 @@ describe('Connection', function () {
it('default options', function () {
const connection: any = new utils.common.Connection('url')
assert.strictEqual(connection._url, 'url')
assert(_.isUndefined(connection._config.proxy))
assert(_.isUndefined(connection._config.authorization))
assert(connection._config.proxy == null)
assert(connection._config.authorization == null)
})
describe('trace', () => {

View File

@@ -44,7 +44,7 @@ module.exports.normal = function(request, options = {}) {
marker: options.marker,
limit: request.limit,
ledger_index: options.ledger,
lines: _.filter([{
lines: [{
account: 'r3vi7mWxru9rJCxETCyA1CHvzL96eZWx5z',
balance: '0',
currency: 'ASP',
@@ -279,7 +279,7 @@ module.exports.normal = function(request, options = {}) {
quality_out: 0,
freeze: true
}
], item => !request.peer || item.account === request.peer)
].filter(item => !request.peer || item.account === request.peer)
}
});
};

View File

@@ -217,7 +217,7 @@ module.exports = function(request, options = {}) {
tx.Destination = addresses.ACCOUNT;
}
if (request.limit === 13) {
const res = _.assign({}, NotFound, {id: request.id});
const res = Object.assign({}, NotFound, {id: request.id});
return JSON.stringify(res);
}
return JSON.stringify({
@@ -225,7 +225,7 @@ module.exports = function(request, options = {}) {
status: 'success',
type: 'response',
result: {
marker: marker === undefined ? undefined : String(marker),
marker: marker == null ? undefined : String(marker),
transactions: [
{
ledger_index: 348860 - Number(marker || 100),

View File

@@ -29,7 +29,7 @@ function verifyTransaction(testcase, hash, type, options, txData, address) {
assert.strictEqual(data.type, type)
assert.strictEqual(data.address, address)
assert.strictEqual(data.outcome.result, 'tesSUCCESS')
if (testcase.transactions !== undefined) {
if (testcase.transactions != null) {
testcase.transactions.push(hash)
}
return {txJSON: JSON.stringify(txData), id: hash, tx: data}
@@ -320,11 +320,11 @@ describe('integration tests', function () {
const txData = JSON.parse(result.txJSON)
return this.api.getOrders(address).then((orders) => {
assert(orders && orders.length > 0)
const createdOrder = _.first(
_.filter(orders, (order) => {
const createdOrder = (
orders.filter((order) => {
return order.properties.sequence === txData.Sequence
})
)
)[0]
assert(createdOrder)
assert.strictEqual(createdOrder.properties.maker, address)
assert.deepEqual(createdOrder.specification, orderSpecification)
@@ -390,7 +390,8 @@ describe('integration tests', function () {
it('getTrustlines', function () {
const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty'])
const { currency, counterparty } = fixture
const options = { currency, counterparty }
return this.api.getTrustlines(address, options).then((data) => {
assert(data && data.length > 0 && data[0] && data[0].specification)
const specification = data[0].specification
@@ -402,7 +403,8 @@ describe('integration tests', function () {
it('getBalances', function () {
const fixture = requests.prepareTrustline.simple
const options = _.pick(fixture, ['currency', 'counterparty'])
const { currency, counterparty } = fixture
const options = { currency, counterparty }
return this.api.getBalances(address, options).then((data) => {
assert(data && data.length > 0 && data[0])
assert.strictEqual(data[0].currency, fixture.currency)
@@ -488,7 +490,7 @@ describe('integration tests', function () {
return this.api.getPaths(pathfind).then((data) => {
assert(data && data.length > 0)
assert(
_.every(data, (path) => {
data.every((path) => {
return (
parseFloat(path.source.amount.value) <=
parseFloat(pathfind.source.amount.value)
@@ -551,7 +553,7 @@ describe('integration tests - standalone rippled', function () {
})
})
.then(() => {
const multisignInstructions = _.assign({}, instructions, {
const multisignInstructions = Object.assign({}, instructions, {
signersCount: 2
})
return this.api

View File

@@ -26,7 +26,7 @@ function pay(api, from, to, amount, secret, currency = 'XRP', counterparty) {
}
};
if (counterparty !== undefined) {
if (counterparty != null) {
paymentSpecification.source.maxAmount.counterparty = counterparty;
paymentSpecification.destination.amount.counterparty = counterparty;
}

View File

@@ -21,12 +21,12 @@ function isBTC(json) {
}
function createResponse(request, response, overrides = {}) {
const result = _.assign({}, response.result, overrides)
const result = Object.assign({}, response.result, overrides)
const change =
response.result && !_.isEmpty(overrides)
? {id: request.id, result: result}
: {id: request.id}
return JSON.stringify(_.assign({}, response, change))
return JSON.stringify(Object.assign({}, response, change))
}
function createLedgerResponse(request, response) {
@@ -39,10 +39,10 @@ function createLedgerResponse(request, response) {
delete newResponse.result.ledger.accountState
}
// the following fields were not in the ledger response in the past
if (newResponse.result.ledger.close_flags === undefined) {
if (newResponse.result.ledger.close_flags == null) {
newResponse.result.ledger.close_flags = 0
}
if (newResponse.result.ledger.parent_close_time === undefined) {
if (newResponse.result.ledger.parent_close_time == null) {
newResponse.result.ledger.parent_close_time =
newResponse.result.ledger.close_time - 10
}
@@ -56,13 +56,13 @@ type MockedWebSocketServer = any
export function createMockRippled(port) {
const mock = new WebSocketServer({port: port}) as MockedWebSocketServer
_.assign(mock, EventEmitter2.prototype)
Object.assign(mock, EventEmitter2.prototype)
const close = mock.close
mock.close = function () {
if (mock.expectedRequests !== undefined) {
const allRequestsMade = _.every(mock.expectedRequests, function (
counter
if (mock.expectedRequests != null) {
const allRequestsMade = Object.entries(mock.expectedRequests).every(function (
_, counter
) {
return counter === 0
})
@@ -108,11 +108,11 @@ export function createMockRippled(port) {
if (mock.listeners(this.event).length === 0) {
throw new Error('No event handler registered for ' + this.event)
}
if (mock.expectedRequests === undefined) {
if (mock.expectedRequests == null) {
return // TODO: fail here to require expectedRequests
}
const expectedCount = mock.expectedRequests[this.event]
if (expectedCount === undefined || expectedCount === 0) {
if (expectedCount == null || expectedCount === 0) {
throw new Error('Unexpected request: ' + this.event)
}
mock.expectedRequests[this.event] -= 1
@@ -120,7 +120,7 @@ export function createMockRippled(port) {
mock.on('request_config', function (request, conn) {
assert.strictEqual(request.command, 'config')
conn.config = _.assign(conn.config, request.data)
conn.config = Object.assign(conn.config, request.data)
conn.send(
createResponse(request, {
status: 'success',
@@ -174,7 +174,7 @@ export function createMockRippled(port) {
mock.on('request_global_config', function (request, conn) {
assert.strictEqual(request.command, 'global_config')
mock.config = _.assign(conn.config, request.data)
mock.config = Object.assign(conn.config, request.data)
conn.send(
createResponse(request, {
status: 'success',
@@ -248,7 +248,7 @@ export function createMockRippled(port) {
mock.config.returnEmptySubscribeRequest--
conn.send(createResponse(request, fixtures.empty))
} else if (request.accounts) {
assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1)
assert(Object.values(addresses).indexOf(request.accounts[0]) !== -1)
}
conn.send(createResponse(request, fixtures.subscribe))
})
@@ -256,7 +256,7 @@ export function createMockRippled(port) {
mock.on('request_unsubscribe', function (request, conn) {
assert.strictEqual(request.command, 'unsubscribe')
if (request.accounts) {
assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1)
assert(Object.values(addresses).indexOf(request.accounts[0]) !== -1)
} else {
assert.deepEqual(request.streams, ['ledger', 'server'])
}
@@ -282,7 +282,7 @@ export function createMockRippled(port) {
const response = Object.assign({}, fixtures.account_info.normal)
response.Account = addresses.THIRD_ACCOUNT
conn.send(createResponse(request, response))
} else if (request.account === undefined) {
} else if (request.account == null) {
const response = Object.assign(
{},
{
@@ -346,7 +346,7 @@ export function createMockRippled(port) {
createLedgerResponse(request, fixtures.ledger.pre2014withPartial)
)
} else if (request.ledger_index === 38129) {
const response = _.assign({}, fixtures.ledger.normal, {
const response = Object.assign({}, fixtures.ledger.normal, {
result: {ledger: fullLedger}
})
conn.send(createLedgerResponse(request, response))

View File

@@ -172,7 +172,7 @@ describe('RippleAPI', function () {
it('ledger utils - getRecursive', async () => {
function getter(marker) {
return new Promise<RecursiveData>((resolve, reject) => {
if (marker !== undefined) {
if (marker != null) {
reject(new Error())
return
}

View File

@@ -52,7 +52,7 @@ function teardown(this: any, done) {
this.api
.disconnect()
.then(() => {
if (this.mockRippled !== undefined) {
if (this.mockRippled != null) {
this.mockRippled.close()
} else {
this.mocks.forEach((mock) => mock.close())

6163
yarn.lock

File diff suppressed because it is too large Load Diff