From e200de3073170794094bc353d0c8f831197d11f6 Mon Sep 17 00:00:00 2001 From: Nathan Nichols Date: Fri, 3 Sep 2021 15:41:20 -0700 Subject: [PATCH] Adds @xrplf prettier config (#1598) * build: new prettier config --- package-lock.json | 13 + package.json | 2 + src/client/backoff.ts | 30 +- src/client/broadcastClient.ts | 50 +- src/client/connection.ts | 346 ++--- src/client/connectionManager.ts | 18 +- src/client/index.ts | 448 +++--- src/client/requestManager.ts | 104 +- src/client/wsWrapper.ts | 72 +- src/common/constants.ts | 46 +- src/common/ecdsa.ts | 6 +- src/common/errors.ts | 42 +- src/common/fee.ts | 30 +- src/common/index.ts | 23 +- src/common/txflags.ts | 6 +- src/common/types/commands/account_info.ts | 26 +- src/common/types/commands/account_lines.ts | 26 +- src/common/types/commands/account_objects.ts | 54 +- src/common/types/commands/account_offers.ts | 36 +- src/common/types/commands/book_offers.ts | 38 +- src/common/types/commands/gateway_balances.ts | 26 +- src/common/types/commands/index.ts | 20 +- src/common/types/commands/ledger.ts | 28 +- src/common/types/commands/ledger_data.ts | 16 +- src/common/types/commands/ledger_entry.ts | 42 +- src/common/types/commands/server_info.ts | 78 +- src/common/types/objects/adjustments.ts | 20 +- src/common/types/objects/amounts.ts | 14 +- src/common/types/objects/index.ts | 24 +- src/common/types/objects/ledger.ts | 50 +- src/common/types/objects/ledger_data.ts | 10 +- src/common/types/objects/ledger_entries.ts | 260 ++-- src/common/types/objects/memos.ts | 6 +- src/common/types/objects/orders.ts | 22 +- src/common/types/objects/queue_data.ts | 22 +- src/common/types/objects/settings.ts | 48 +- src/common/types/objects/signers.ts | 6 +- src/common/types/objects/transactions.ts | 42 +- src/common/types/objects/trustlines.ts | 62 +- src/index.ts | 16 +- src/ledger/balances.ts | 61 +- src/ledger/orderbook.ts | 88 +- src/ledger/parse/account-delete.ts | 22 +- src/ledger/parse/account-order.ts | 48 +- src/ledger/parse/account-trustline.ts | 16 +- src/ledger/parse/amendment.ts | 4 +- src/ledger/parse/amount.ts | 14 +- src/ledger/parse/cancellation.ts | 10 +- src/ledger/parse/check-cancel.ts | 14 +- src/ledger/parse/check-cash.ts | 22 +- src/ledger/parse/check-create.ts | 26 +- src/ledger/parse/deposit-preauth.ts | 16 +- src/ledger/parse/escrow-cancellation.ts | 12 +- src/ledger/parse/escrow-creation.ts | 14 +- src/ledger/parse/escrow-execution.ts | 12 +- src/ledger/parse/fee-update.ts | 12 +- src/ledger/parse/fields.ts | 40 +- src/ledger/parse/flags.ts | 6 +- src/ledger/parse/ledger.ts | 74 +- src/ledger/parse/order.ts | 30 +- src/ledger/parse/orderbook-order.ts | 63 +- src/ledger/parse/pathfind.ts | 44 +- src/ledger/parse/payment-channel-claim.ts | 18 +- src/ledger/parse/payment-channel-create.ts | 14 +- src/ledger/parse/payment-channel-fund.ts | 14 +- src/ledger/parse/payment-channel.ts | 32 +- src/ledger/parse/payment.ts | 36 +- src/ledger/parse/settings.ts | 68 +- src/ledger/parse/ticket-create.ts | 12 +- src/ledger/parse/transaction.ts | 108 +- src/ledger/parse/trustline.ts | 24 +- src/ledger/parse/utils.ts | 120 +- src/ledger/pathfind-types.ts | 74 +- src/ledger/pathfind.ts | 146 +- src/ledger/trustlines.ts | 40 +- src/ledger/utils.ts | 117 +- src/models/common/index.ts | 66 +- src/models/ledger/accountRoot.ts | 34 +- src/models/ledger/amendments.ts | 16 +- src/models/ledger/baseLedgerEntry.ts | 2 +- src/models/ledger/check.ts | 32 +- src/models/ledger/depositPreauth.ts | 16 +- src/models/ledger/directoryNode.ts | 24 +- src/models/ledger/escrow.ts | 30 +- src/models/ledger/feeSettings.ts | 14 +- src/models/ledger/index.ts | 34 +- src/models/ledger/ledger.ts | 32 +- src/models/ledger/ledgerEntry.ts | 32 +- src/models/ledger/ledgerHashes.ts | 10 +- src/models/ledger/negativeUNL.ts | 14 +- src/models/ledger/offer.ts | 28 +- src/models/ledger/payChannel.ts | 34 +- src/models/ledger/rippleState.ts | 30 +- src/models/ledger/signerList.ts | 24 +- src/models/ledger/ticket.ts | 16 +- src/models/methods/accountChannels.ts | 58 +- src/models/methods/accountCurrencies.ts | 28 +- src/models/methods/accountInfo.ts | 56 +- src/models/methods/accountLines.ts | 58 +- src/models/methods/accountObjects.ts | 42 +- src/models/methods/accountOffers.ts | 44 +- src/models/methods/accountTx.ts | 54 +- src/models/methods/baseMethod.ts | 36 +- src/models/methods/bookOffers.ts | 42 +- src/models/methods/channelVerify.ts | 16 +- src/models/methods/depositAuthorized.ts | 30 +- src/models/methods/fee.ts | 36 +- src/models/methods/gatewayBalances.ts | 36 +- src/models/methods/index.ts | 74 +- src/models/methods/ledger.ts | 72 +- src/models/methods/ledgerClosed.ts | 10 +- src/models/methods/ledgerCurrent.ts | 8 +- src/models/methods/ledgerData.ts | 34 +- src/models/methods/ledgerEntry.ts | 70 +- src/models/methods/manifest.ts | 22 +- src/models/methods/norippleCheck.ts | 26 +- src/models/methods/pathFind.ts | 48 +- src/models/methods/ping.ts | 6 +- src/models/methods/random.ts | 8 +- src/models/methods/ripplePathFind.ts | 36 +- src/models/methods/serverInfo.ts | 124 +- src/models/methods/serverState.ts | 92 +- src/models/methods/submit.ts | 40 +- src/models/methods/submitMultisigned.ts | 22 +- src/models/methods/subscribe.ts | 158 ++- src/models/methods/transactionEntry.ts | 26 +- src/models/methods/tx.ts | 28 +- src/models/methods/unsubscribe.ts | 22 +- src/models/transactions/accountDelete.ts | 22 +- src/models/transactions/accountSet.ts | 60 +- src/models/transactions/checkCancel.ts | 14 +- src/models/transactions/checkCash.ts | 32 +- src/models/transactions/checkCreate.ts | 44 +- src/models/transactions/common.ts | 172 +-- src/models/transactions/depositPreauth.ts | 36 +- src/models/transactions/escrowCancel.ts | 24 +- src/models/transactions/escrowCreate.ts | 56 +- src/models/transactions/escrowFinish.ts | 36 +- src/models/transactions/index.ts | 40 +- src/models/transactions/metadata.ts | 44 +- src/models/transactions/offerCancel.ts | 16 +- src/models/transactions/offerCreate.ts | 48 +- src/models/transactions/payment.ts | 104 +- .../transactions/paymentChannelClaim.ts | 50 +- .../transactions/paymentChannelCreate.ts | 62 +- src/models/transactions/paymentChannelFund.ts | 32 +- src/models/transactions/setRegularKey.ts | 14 +- src/models/transactions/signerListSet.ts | 34 +- src/models/transactions/ticketCreate.ts | 24 +- src/models/transactions/transaction.ts | 46 +- src/models/transactions/trustSet.ts | 42 +- src/models/utils/index.ts | 6 +- src/transaction/check-cancel.ts | 26 +- src/transaction/check-cash.ts | 44 +- src/transaction/check-create.ts | 44 +- src/transaction/combine.ts | 46 +- src/transaction/escrow-cancellation.ts | 36 +- src/transaction/escrow-creation.ts | 64 +- src/transaction/escrow-execution.ts | 48 +- src/transaction/order.ts | 56 +- src/transaction/ordercancellation.ts | 32 +- src/transaction/payment-channel-claim.ts | 68 +- src/transaction/payment-channel-create.ts | 48 +- src/transaction/payment-channel-fund.ts | 40 +- src/transaction/payment.ts | 171 ++- src/transaction/settings.ts | 115 +- src/transaction/sign.ts | 162 +-- src/transaction/ticket.ts | 36 +- src/transaction/trustline.ts | 46 +- src/transaction/types.ts | 194 +-- src/transaction/utils.ts | 279 ++-- src/utils/derive.ts | 16 +- src/utils/generateAddress.ts | 58 +- src/utils/hashes/hashPrefix.ts | 2 +- src/utils/hashes/index.ts | 184 +-- src/utils/hashes/ledgerSpaces.ts | 36 +- src/utils/hashes/sha512Half.ts | 14 +- src/utils/hashes/shamap.ts | 104 +- src/utils/index.ts | 148 +- src/utils/ledgerHash.ts | 82 +- src/utils/signPaymentChannelClaim.ts | 14 +- src/utils/verifyPaymentChannelClaim.ts | 14 +- src/utils/xrpConversion.ts | 115 ++ src/wallet/generateFaucetWallet.ts | 168 +-- src/wallet/index.ts | 98 +- test/backoff.ts | 64 +- test/broadcastClient.ts | 72 +- test/browser/browserIntegration.ts | 44 +- test/client.ts | 132 +- test/client/combine.ts | 48 +- test/client/constructor.ts | 36 +- test/client/deriveXAddress.ts | 24 +- test/client/errors.ts | 28 +- test/client/formatBidsAndAsks.ts | 4 +- test/client/getBalances.ts | 132 +- test/client/getFee.ts | 106 +- test/client/getOrderbook.ts | 166 +-- test/client/getPaths.ts | 84 +- test/client/getTrustlines.ts | 80 +- test/client/hasNextPage.ts | 50 +- test/client/isConnected.ts | 22 +- test/client/prepareCheckCancel.ts | 96 +- test/client/prepareCheckCash.ts | 124 +- test/client/prepareCheckCreate.ts | 102 +- test/client/prepareEscrowCancellation.ts | 100 +- test/client/prepareEscrowCreation.ts | 94 +- test/client/prepareEscrowExecution.ts | 144 +- test/client/prepareOrder.ts | 124 +- test/client/prepareOrderCancellation.ts | 132 +- test/client/preparePayment.ts | 632 +++++---- test/client/preparePaymentChannelClaim.ts | 198 +-- test/client/preparePaymentChannelCreate.ts | 92 +- test/client/preparePaymentChannelFund.ts | 104 +- test/client/prepareSettings.ts | 478 ++++--- test/client/prepareTicket.ts | 72 +- test/client/prepareTransaction.ts | 1202 ++++++++--------- test/client/prepareTrustline.ts | 144 +- test/client/request.ts | 56 +- test/client/requestNextPage.ts | 66 +- test/client/sign.ts | 478 +++---- test/connection.ts | 731 +++++----- test/fixtures/requests/index.ts | 82 +- test/fixtures/responses/index.ts | 150 +- test/fixtures/rippled/index.ts | 202 +-- test/integration/integration.ts | 536 ++++---- test/mockRippled.ts | 166 +-- test/mockRippledTest.ts | 56 +- test/mockedServer.ts | 16 +- test/models/accountDelete.ts | 70 +- test/models/accountSet.ts | 94 +- test/models/baseTransaction.ts | 200 +-- test/models/checkCancel.ts | 34 +- test/models/checkCash.ts | 84 +- test/models/checkCreate.ts | 126 +- test/models/depositPreauth.ts | 96 +- test/models/escrowCancel.ts | 58 +- test/models/escrowCreate.ts | 114 +- test/models/escrowFinish.ts | 70 +- test/models/offerCancel.ts | 54 +- test/models/offerCreate.ts | 186 +-- test/models/payment.ts | 132 +- test/models/paymentChannelClaim.ts | 94 +- test/models/paymentChannelCreate.ts | 120 +- test/models/paymentChannelFund.ts | 74 +- test/models/setRegularKey.ts | 42 +- test/models/signerListSet.ts | 56 +- test/models/ticketCreate.ts | 76 +- test/models/trustSet.ts | 72 +- test/models/utils.ts | 38 +- test/runClientTests.ts | 50 +- test/setupClient.ts | 56 +- test/setupClientWeb.ts | 48 +- test/shamap.ts | 76 +- test/testUtils.ts | 84 +- test/utils/computeLedgerHash.ts | 170 +-- test/utils/dropsToXrp.ts | 166 +-- test/utils/generateAddress.ts | 202 +-- test/utils/hashes.ts | 189 ++- test/utils/signPaymentChannelClaim.ts | 26 +- test/utils/verifyPaymentChannelClaim.ts | 36 +- test/utils/xrpToDrops.ts | 162 +-- test/wallet/index.ts | 326 ++--- test/walletGeneration.ts | 53 +- 263 files changed, 10185 insertions(+), 10133 deletions(-) create mode 100644 src/utils/xrpConversion.ts diff --git a/package-lock.json b/package-lock.json index 39d36eba..9dfa7b47 100644 --- a/package-lock.json +++ b/package-lock.json @@ -29,6 +29,7 @@ "@typescript-eslint/eslint-plugin": "^4.30.0", "@typescript-eslint/parser": "^4.0.0", "@xrplf/eslint-config": "^1.2.2", + "@xrplf/prettier-config": "^1.2.0", "assert": "^2.0.0", "buffer": "^6.0.2", "chai": "^4.3.4", @@ -1341,6 +1342,12 @@ "typescript": "^3.9.3" } }, + "node_modules/@xrplf/prettier-config": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xrplf/prettier-config/-/prettier-config-1.2.0.tgz", + "integrity": "sha512-dVGcbxcmtCRogsLYkdjczm01g+nDCtrJHQsTEWsOl+EemNGOQFCjiiorVsvg6EClkU6yxjqJOh0IqYfH/GAOfw==", + "dev": true + }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", @@ -9983,6 +9990,12 @@ "eslint-config-prettier": "8.3.0" } }, + "@xrplf/prettier-config": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xrplf/prettier-config/-/prettier-config-1.2.0.tgz", + "integrity": "sha512-dVGcbxcmtCRogsLYkdjczm01g+nDCtrJHQsTEWsOl+EemNGOQFCjiiorVsvg6EClkU6yxjqJOh0IqYfH/GAOfw==", + "dev": true + }, "@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", diff --git a/package.json b/package.json index 995d2332..26c00302 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "@typescript-eslint/eslint-plugin": "^4.30.0", "@typescript-eslint/parser": "^4.0.0", "@xrplf/eslint-config": "^1.2.2", + "@xrplf/prettier-config": "^1.2.0", "assert": "^2.0.0", "buffer": "^6.0.2", "chai": "^4.3.4", @@ -96,6 +97,7 @@ "start:snippet": "npm run compile:snippets && node ./snippets/dist/start.js", "inspect:snippet": "npm run compile:snippets && node inspect ./snippets/dist/start.js" }, + "prettier": "@xrplf/prettier-config", "repository": { "type": "git", "url": "git@github.com:XRPLF/xrpl.js.git" diff --git a/src/client/backoff.ts b/src/client/backoff.ts index 29bda546..064e03ac 100644 --- a/src/client/backoff.ts +++ b/src/client/backoff.ts @@ -12,23 +12,23 @@ interface ExponentialBackoffOptions { // The min backoff duration. - min?: number; + min?: number // The max backoff duration. - max?: number; + max?: number } -const DEFAULT_MIN = 100; -const DEFAULT_MAX = 1000; +const DEFAULT_MIN = 100 +const DEFAULT_MAX = 1000 /** * A Back off strategy that increases exponentially. Useful with repeated * setTimeout calls over a network (where the destination may be down). */ export default class ExponentialBackoff { - private readonly ms: number; - private readonly max: number; - private readonly factor: number = 2; - private numAttempts = 0; + private readonly ms: number + private readonly max: number + private readonly factor: number = 2 + private numAttempts = 0 /** * Constructs an ExponentialBackoff object. @@ -36,8 +36,8 @@ export default class ExponentialBackoff { * @param opts - The options for the object. */ public constructor(opts: ExponentialBackoffOptions = {}) { - this.ms = opts.min ?? DEFAULT_MIN; - this.max = opts.max ?? DEFAULT_MAX; + this.ms = opts.min ?? DEFAULT_MIN + this.max = opts.max ?? DEFAULT_MAX } /** @@ -46,7 +46,7 @@ export default class ExponentialBackoff { * @returns Number of attempts. */ public get attempts(): number { - return this.numAttempts; + return this.numAttempts } /** @@ -55,15 +55,15 @@ export default class ExponentialBackoff { * @returns The backoff duration in milliseconds. */ public duration(): number { - const ms = this.ms * this.factor ** this.numAttempts; - this.numAttempts += 1; - return Math.floor(Math.min(ms, this.max)); + const ms = this.ms * this.factor ** this.numAttempts + this.numAttempts += 1 + return Math.floor(Math.min(ms, this.max)) } /** * Reset the number of attempts. */ public reset(): void { - this.numAttempts = 0; + this.numAttempts = 0 } } diff --git a/src/client/broadcastClient.ts b/src/client/broadcastClient.ts index afa70b51..18633382 100644 --- a/src/client/broadcastClient.ts +++ b/src/client/broadcastClient.ts @@ -1,10 +1,10 @@ -import { Client, ClientOptions } from "."; +import { Client, ClientOptions } from '.' /** * Client that can rely on multiple different servers. */ export default class BroadcastClient extends Client { - private readonly clients: Client[]; + private readonly clients: Client[] /** * Creates a new BroadcastClient. @@ -13,36 +13,36 @@ export default class BroadcastClient extends Client { * @param options - Options for the clients. */ public constructor(servers: string[], options: ClientOptions = {}) { - super(servers[0], options); + super(servers[0], options) const clients: Client[] = servers.map( - (server) => new Client(server, options) - ); + (server) => new Client(server, options), + ) // exposed for testing - this.clients = clients; + this.clients = clients this.getMethodNames().forEach((name: string) => { this[name] = async (...args): Promise => // eslint-disable-next-line max-len -- Need a long comment, TODO: figure out how to avoid this weirdness /* eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call -- Types are outlined in Client class */ - Promise.race(clients.map(async (client) => client[name](...args))); - }); + Promise.race(clients.map(async (client) => client[name](...args))) + }) // connection methods must be overridden to apply to all client instances this.connect = async (): Promise => { - await Promise.all(clients.map(async (client) => client.connect())); - }; + await Promise.all(clients.map(async (client) => client.connect())) + } this.disconnect = async (): Promise => { - await Promise.all(clients.map(async (client) => client.disconnect())); - }; + await Promise.all(clients.map(async (client) => client.disconnect())) + } this.isConnected = (): boolean => - clients.map((client) => client.isConnected()).every(Boolean); + clients.map((client) => client.isConnected()).every(Boolean) clients.forEach((client) => { - client.on("error", (errorCode, errorMessage, data) => - this.emit("error", errorCode, errorMessage, data) - ); - }); + client.on('error', (errorCode, errorMessage, data) => + this.emit('error', errorCode, errorMessage, data), + ) + }) } /** @@ -51,17 +51,17 @@ export default class BroadcastClient extends Client { * @returns A list of the names of all the methods of the client. */ private getMethodNames(): string[] { - const methodNames: string[] = []; - const firstClient = this.clients[0]; - const methods = Object.getOwnPropertyNames(firstClient); + const methodNames: string[] = [] + const firstClient = this.clients[0] + const methods = Object.getOwnPropertyNames(firstClient) methods.push( - ...Object.getOwnPropertyNames(Object.getPrototypeOf(firstClient)) - ); + ...Object.getOwnPropertyNames(Object.getPrototypeOf(firstClient)), + ) for (const name of methods) { - if (typeof firstClient[name] === "function" && name !== "constructor") { - methodNames.push(name); + if (typeof firstClient[name] === 'function' && name !== 'constructor') { + methodNames.push(name) } } - return methodNames; + return methodNames } } diff --git a/src/client/connection.ts b/src/client/connection.ts index b8576dee..69ad4f86 100644 --- a/src/client/connection.ts +++ b/src/client/connection.ts @@ -1,43 +1,43 @@ /* eslint-disable max-lines -- Connection is a big class */ -import { EventEmitter } from "events"; -import { Agent } from "http"; +import { EventEmitter } from 'events' +import { Agent } from 'http' // eslint-disable-next-line node/no-deprecated-api -- TODO: resolve this -import { parse as parseURL } from "url"; +import { parse as parseURL } from 'url' -import _ from "lodash"; -import WebSocket from "ws"; +import _ from 'lodash' +import WebSocket from 'ws' import { DisconnectedError, NotConnectedError, ConnectionError, RippleError, -} from "../common/errors"; -import { BaseRequest } from "../models/methods/baseMethod"; +} from '../common/errors' +import { BaseRequest } from '../models/methods/baseMethod' -import ExponentialBackoff from "./backoff"; -import ConnectionManager from "./connectionManager"; -import RequestManager from "./requestManager"; +import ExponentialBackoff from './backoff' +import ConnectionManager from './connectionManager' +import RequestManager from './requestManager' -const SECONDS_PER_MINUTE = 60; -const TIMEOUT = 20; -const CONNECTION_TIMEOUT = 5; +const SECONDS_PER_MINUTE = 60 +const TIMEOUT = 20 +const CONNECTION_TIMEOUT = 5 /** * ConnectionOptions is the configuration for the Connection class. */ interface ConnectionOptions { - trace?: boolean | ((id: string, message: string) => void); - proxy?: string; - proxyAuthorization?: string; - authorization?: string; - trustedCertificates?: string[]; - key?: string; - passphrase?: string; - certificate?: string; + trace?: boolean | ((id: string, message: string) => void) + proxy?: string + proxyAuthorization?: string + authorization?: string + trustedCertificates?: string[] + key?: string + passphrase?: string + certificate?: string // request timeout - timeout: number; - connectionTimeout: number; + timeout: number + connectionTimeout: number } /** @@ -45,47 +45,47 @@ interface ConnectionOptions { * is optional, so any ConnectionOptions configuration that has a default value is * still optional at the point that the user provides it. */ -export type ConnectionUserOptions = Partial; +export type ConnectionUserOptions = Partial // // Represents an intentionally triggered web-socket disconnect code. // WebSocket spec allows 4xxx codes for app/library specific codes. // See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent // -export const INTENTIONAL_DISCONNECT_CODE = 4000; +export const INTENTIONAL_DISCONNECT_CODE = 4000 -type WebsocketState = 0 | 1 | 2 | 3; +type WebsocketState = 0 | 1 | 2 | 3 function getAgent(url: string, config: ConnectionOptions): Agent | undefined { // TODO: replace deprecated method if (config.proxy != null) { - const parsedURL = parseURL(url); - const parsedProxyURL = parseURL(config.proxy); + const parsedURL = parseURL(url) + const parsedProxyURL = parseURL(config.proxy) const proxyOverrides = _.omitBy( { - secureEndpoint: parsedURL.protocol === "wss:", - secureProxy: parsedProxyURL.protocol === "https:", + secureEndpoint: parsedURL.protocol === 'wss:', + secureProxy: parsedProxyURL.protocol === 'https:', auth: config.proxyAuthorization, ca: config.trustedCertificates, key: config.key, passphrase: config.passphrase, cert: config.certificate, }, - (value) => value == null - ); - const proxyOptions = { ...parsedProxyURL, ...proxyOverrides }; - let HttpsProxyAgent; + (value) => value == null, + ) + const proxyOptions = { ...parsedProxyURL, ...proxyOverrides } + let HttpsProxyAgent try { // eslint-disable-next-line max-len -- Long eslint-disable-next-line TODO: figure out how to make this nicer // eslint-disable-next-line import/max-dependencies, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-require-imports, node/global-require, global-require, -- Necessary for the `require` - HttpsProxyAgent = require("https-proxy-agent"); + HttpsProxyAgent = require('https-proxy-agent') } catch (_error) { - throw new Error('"proxy" option is not supported in the browser'); + throw new Error('"proxy" option is not supported in the browser') } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-call -- Necessary - return new HttpsProxyAgent(proxyOptions) as unknown as Agent; + return new HttpsProxyAgent(proxyOptions) as unknown as Agent } - return undefined; + return undefined } /** @@ -98,13 +98,13 @@ function getAgent(url: string, config: ConnectionOptions): Agent | undefined { */ function createWebSocket( url: string, - config: ConnectionOptions + config: ConnectionOptions, ): WebSocket | null { - const options: WebSocket.ClientOptions = {}; - options.agent = getAgent(url, config); + const options: WebSocket.ClientOptions = {} + options.agent = getAgent(url, config) if (config.authorization != null) { - const base64 = Buffer.from(config.authorization).toString("base64"); - options.headers = { Authorization: `Basic ${base64}` }; + const base64 = Buffer.from(config.authorization).toString('base64') + options.headers = { Authorization: `Basic ${base64}` } } const optionsOverrides = _.omitBy( { @@ -113,16 +113,16 @@ function createWebSocket( passphrase: config.passphrase, cert: config.certificate, }, - (value) => value == null - ); - const websocketOptions = { ...options, ...optionsOverrides }; - const websocket = new WebSocket(url, websocketOptions); + (value) => value == null, + ) + const websocketOptions = { ...options, ...optionsOverrides } + const websocket = new WebSocket(url, websocketOptions) // we will have a listener for each outstanding request, // so we have to raise the limit (the default is 10) - if (typeof websocket.setMaxListeners === "function") { - websocket.setMaxListeners(Infinity); + if (typeof websocket.setMaxListeners === 'function') { + websocket.setMaxListeners(Infinity) } - return websocket; + return websocket } /** @@ -134,17 +134,17 @@ function createWebSocket( */ async function websocketSendAsync( ws: WebSocket, - message: string + message: string, ): Promise { return new Promise((resolve, reject) => { ws.send(message, (error) => { if (error) { - reject(new DisconnectedError(error.message, error)); + reject(new DisconnectedError(error.message, error)) } else { - resolve(); + resolve() } - }); - }); + }) + }) } /** @@ -152,18 +152,18 @@ async function websocketSendAsync( * an active WebSocket connection to a XRPL node. */ export class Connection extends EventEmitter { - private readonly url: string | undefined; - private ws: WebSocket | null = null; - private reconnectTimeoutID: null | NodeJS.Timeout = null; - private heartbeatIntervalID: null | NodeJS.Timeout = null; + private readonly url: string | undefined + private ws: WebSocket | null = null + private reconnectTimeoutID: null | NodeJS.Timeout = null + private heartbeatIntervalID: null | NodeJS.Timeout = null private readonly retryConnectionBackoff = new ExponentialBackoff({ min: 100, max: SECONDS_PER_MINUTE * 1000, - }); + }) - private readonly config: ConnectionOptions; - private readonly requestManager = new RequestManager(); - private readonly connectionManager = new ConnectionManager(); + private readonly config: ConnectionOptions + private readonly requestManager = new RequestManager() + private readonly connectionManager = new ConnectionManager() /** * Creates a new Connection object. @@ -172,19 +172,19 @@ export class Connection extends EventEmitter { * @param options - Options for the Connection object. */ public constructor(url?: string, options: ConnectionUserOptions = {}) { - super(); - this.setMaxListeners(Infinity); - this.url = url; + super() + this.setMaxListeners(Infinity) + this.url = url this.config = { timeout: TIMEOUT * 1000, connectionTimeout: CONNECTION_TIMEOUT * 1000, ...options, - }; - if (typeof options.trace === "function") { - this.trace = options.trace; + } + if (typeof options.trace === 'function') { + this.trace = options.trace } else if (options.trace) { // eslint-disable-next-line no-console -- Used for tracing only - this.trace = console.log; + this.trace = console.log } } @@ -194,7 +194,7 @@ export class Connection extends EventEmitter { * @returns Whether the websocket connection is open. */ public isConnected(): boolean { - return this.state === WebSocket.OPEN; + return this.state === WebSocket.OPEN } /** @@ -205,22 +205,22 @@ export class Connection extends EventEmitter { */ public async connect(): Promise { if (this.isConnected()) { - return Promise.resolve(); + return Promise.resolve() } if (this.state === WebSocket.CONNECTING) { - return this.connectionManager.awaitConnection(); + return this.connectionManager.awaitConnection() } if (!this.url) { return Promise.reject( - new ConnectionError("Cannot connect because no server was specified") - ); + new ConnectionError('Cannot connect because no server was specified'), + ) } if (this.ws != null) { return Promise.reject( - new RippleError("Websocket connection never cleaned up.", { + new RippleError('Websocket connection never cleaned up.', { state: this.state, - }) - ); + }), + ) } // Create the connection timeout, in case the connection hangs longer than expected. @@ -229,24 +229,24 @@ export class Connection extends EventEmitter { new ConnectionError( `Error: connect() timed out after ${this.config.connectionTimeout} ms. ` + `If your internet connection is working, the rippled server may be blocked or inaccessible. ` + - `You can also try setting the 'connectionTimeout' option in the Client constructor.` - ) - ); - }, this.config.connectionTimeout); + `You can also try setting the 'connectionTimeout' option in the Client constructor.`, + ), + ) + }, this.config.connectionTimeout) // Connection listeners: these stay attached only until a connection is done/open. - this.ws = createWebSocket(this.url, this.config); + this.ws = createWebSocket(this.url, this.config) if (this.ws == null) { - throw new Error("Connect: created null websocket"); + throw new Error('Connect: created null websocket') } - this.ws.on("error", (error) => this.onConnectionFailed(error)); - this.ws.on("error", () => clearTimeout(connectionTimeoutID)); - this.ws.on("close", (reason) => this.onConnectionFailed(reason)); - this.ws.on("close", () => clearTimeout(connectionTimeoutID)); + this.ws.on('error', (error) => this.onConnectionFailed(error)) + this.ws.on('error', () => clearTimeout(connectionTimeoutID)) + this.ws.on('close', (reason) => this.onConnectionFailed(reason)) + this.ws.on('close', () => clearTimeout(connectionTimeoutID)) // eslint-disable-next-line @typescript-eslint/no-misused-promises -- TODO: resolve this - this.ws.once("open", async () => this.onceOpen(connectionTimeoutID)); - return this.connectionManager.awaitConnection(); + this.ws.once('open', async () => this.onceOpen(connectionTimeoutID)) + return this.connectionManager.awaitConnection() } /** @@ -260,30 +260,30 @@ export class Connection extends EventEmitter { */ public async disconnect(): Promise { if (this.reconnectTimeoutID !== null) { - clearTimeout(this.reconnectTimeoutID); - this.reconnectTimeoutID = null; + clearTimeout(this.reconnectTimeoutID) + this.reconnectTimeoutID = null } if (this.state === WebSocket.CLOSED) { - return Promise.resolve(undefined); + return Promise.resolve(undefined) } if (this.ws == null) { - return Promise.resolve(undefined); + return Promise.resolve(undefined) } return new Promise((resolve) => { if (this.ws == null) { - resolve(undefined); + resolve(undefined) } if (this.ws != null) { - this.ws.once("close", (code) => resolve(code)); + this.ws.once('close', (code) => resolve(code)) } // Connection already has a disconnect handler for the disconnect logic. // Just close the websocket manually (with our "intentional" code) to // trigger that. if (this.ws != null && this.state !== WebSocket.CLOSING) { - this.ws.close(INTENTIONAL_DISCONNECT_CODE); + this.ws.close(INTENTIONAL_DISCONNECT_CODE) } - }); + }) } /** @@ -293,9 +293,9 @@ export class Connection extends EventEmitter { // NOTE: We currently have a "reconnecting" event, but that only triggers // through an unexpected connection retry logic. // See: https://github.com/ripple/ripple-lib/pull/1101#issuecomment-565360423 - this.emit("reconnect"); - await this.disconnect(); - await this.connect(); + this.emit('reconnect') + await this.disconnect() + await this.connect() } /** @@ -308,21 +308,21 @@ export class Connection extends EventEmitter { */ public async request( request: T, - timeout?: number + timeout?: number, ): Promise { if (!this.shouldBeConnected || this.ws == null) { - throw new NotConnectedError(); + throw new NotConnectedError() } const [id, message, responsePromise] = this.requestManager.createRequest( request, - timeout ?? this.config.timeout - ); - this.trace("send", message); + timeout ?? this.config.timeout, + ) + this.trace('send', message) websocketSendAsync(this.ws, message).catch((error) => { - this.requestManager.reject(id, error); - }); + this.requestManager.reject(id, error) + }) - return responsePromise; + return responsePromise } /** @@ -331,11 +331,11 @@ export class Connection extends EventEmitter { * @returns The Websocket connection URL. */ public getUrl(): string { - return this.url ?? ""; + return this.url ?? '' } // eslint-disable-next-line @typescript-eslint/no-empty-function -- Does nothing on default - private readonly trace: (id: string, message: string) => void = () => {}; + private readonly trace: (id: string, message: string) => void = () => {} /** * Handler for when messages are received from the server. @@ -343,31 +343,31 @@ export class Connection extends EventEmitter { * @param message - The message received from the server. */ private onMessage(message): void { - this.trace("receive", message); - let data: Record; + this.trace('receive', message) + let data: Record try { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Must be a JSON dictionary - data = JSON.parse(message); + data = JSON.parse(message) } catch (error) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Errors have messages - this.emit("error", "badMessage", error.message, message); - return; + this.emit('error', 'badMessage', error.message, message) + return } if (data.type == null && data.error) { // e.g. slowDown - this.emit("error", data.error, data.error_message, data); - return; + this.emit('error', data.error, data.error_message, data) + return } if (data.type) { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true - this.emit(data.type as string, data); + this.emit(data.type as string, data) } - if (data.type === "response") { + if (data.type === 'response') { try { - this.requestManager.handleResponse(data); + this.requestManager.handleResponse(data) } catch (error) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access -- Errors have messages - this.emit("error", "badMessage", error.message, message); + this.emit('error', 'badMessage', error.message, message) } } } @@ -378,7 +378,7 @@ export class Connection extends EventEmitter { * @returns The Websocket's ready state. */ private get state(): WebsocketState { - return this.ws ? this.ws.readyState : WebSocket.CLOSED; + return this.ws ? this.ws.readyState : WebSocket.CLOSED } /** @@ -387,7 +387,7 @@ export class Connection extends EventEmitter { * @returns Whether the server should be connected. */ private get shouldBeConnected(): boolean { - return this.ws !== null; + return this.ws !== null } /** @@ -399,60 +399,60 @@ export class Connection extends EventEmitter { */ private async onceOpen(connectionTimeoutID: NodeJS.Timeout): Promise { if (this.ws == null) { - throw new Error("onceOpen: ws is null"); + throw new Error('onceOpen: ws is null') } // Once the connection completes successfully, remove all old listeners - this.ws.removeAllListeners(); - clearTimeout(connectionTimeoutID); + this.ws.removeAllListeners() + clearTimeout(connectionTimeoutID) // Add new, long-term connected listeners for messages and errors - this.ws.on("message", (message: string) => this.onMessage(message)); - this.ws.on("error", (error) => - this.emit("error", "websocket", error.message, error) - ); + this.ws.on('message', (message: string) => this.onMessage(message)) + this.ws.on('error', (error) => + this.emit('error', 'websocket', error.message, error), + ) // Handle a closed connection: reconnect if it was unexpected - this.ws.once("close", (code, reason) => { + this.ws.once('close', (code, reason) => { if (this.ws == null) { - throw new Error("onceClose: ws is null"); + throw new Error('onceClose: ws is null') } - this.clearHeartbeatInterval(); + this.clearHeartbeatInterval() this.requestManager.rejectAll( - new DisconnectedError(`websocket was closed, ${reason}`) - ); - this.ws.removeAllListeners(); - this.ws = null; - this.emit("disconnected", code); + new DisconnectedError(`websocket was closed, ${reason}`), + ) + this.ws.removeAllListeners() + this.ws = null + this.emit('disconnected', code) // If this wasn't a manual disconnect, then lets reconnect ASAP. if (code !== INTENTIONAL_DISCONNECT_CODE) { - this.intentionalDisconnect(); + this.intentionalDisconnect() } - }); + }) // Finalize the connection and resolve all awaiting connect() requests try { - this.retryConnectionBackoff.reset(); - this.startHeartbeatInterval(); - this.connectionManager.resolveAllAwaiting(); - this.emit("connected"); + this.retryConnectionBackoff.reset() + this.startHeartbeatInterval() + this.connectionManager.resolveAllAwaiting() + this.emit('connected') } catch (error) { - this.connectionManager.rejectAllAwaiting(error); + this.connectionManager.rejectAllAwaiting(error) // Ignore this error, propagate the root cause. // eslint-disable-next-line @typescript-eslint/no-empty-function -- Need empty catch - await this.disconnect().catch(() => {}); + await this.disconnect().catch(() => {}) } } private intentionalDisconnect(): void { - const retryTimeout = this.retryConnectionBackoff.duration(); - this.trace("reconnect", `Retrying connection in ${retryTimeout}ms.`); - this.emit("reconnecting", this.retryConnectionBackoff.attempts); + const retryTimeout = this.retryConnectionBackoff.duration() + this.trace('reconnect', `Retrying connection in ${retryTimeout}ms.`) + this.emit('reconnecting', this.retryConnectionBackoff.attempts) // Start the reconnect timeout, but set it to `this.reconnectTimeoutID` // so that we can cancel one in-progress on disconnect. this.reconnectTimeoutID = setTimeout(() => { this.reconnect().catch((error: Error) => { - this.emit("error", "reconnect", error.message, error); - }); - }, retryTimeout); + this.emit('error', 'reconnect', error.message, error) + }) + }, retryTimeout) } /** @@ -460,7 +460,7 @@ export class Connection extends EventEmitter { */ private clearHeartbeatInterval(): void { if (this.heartbeatIntervalID) { - clearInterval(this.heartbeatIntervalID); + clearInterval(this.heartbeatIntervalID) } } @@ -468,12 +468,12 @@ export class Connection extends EventEmitter { * Starts a heartbeat to check the connection with the server. */ private startHeartbeatInterval(): void { - this.clearHeartbeatInterval(); + this.clearHeartbeatInterval() this.heartbeatIntervalID = setInterval( // eslint-disable-next-line @typescript-eslint/no-misused-promises -- TODO: resolve this async () => this.heartbeat(), - this.config.timeout - ); + this.config.timeout, + ) } /** @@ -483,11 +483,11 @@ export class Connection extends EventEmitter { * @returns A Promise that resolves to void when the heartbeat returns successfully. */ private async heartbeat(): Promise { - this.request({ command: "ping" }).catch(async () => { + this.request({ command: 'ping' }).catch(async () => { return this.reconnect().catch((error: Error) => { - this.emit("error", "reconnect", error.message, error); - }); - }); + this.emit('error', 'reconnect', error.message, error) + }) + }) } /** @@ -497,28 +497,28 @@ export class Connection extends EventEmitter { */ private onConnectionFailed(errorOrCode: Error | number | null): void { if (this.ws) { - this.ws.removeAllListeners(); - this.ws.on("error", () => { + this.ws.removeAllListeners() + this.ws.on('error', () => { // Correctly listen for -- but ignore -- any future errors: If you // don't have a listener on "error" node would log a warning on error. - }); - this.ws.close(); - this.ws = null; + }) + this.ws.close() + this.ws = null } - if (typeof errorOrCode === "number") { + if (typeof errorOrCode === 'number') { this.connectionManager.rejectAllAwaiting( new NotConnectedError(`Connection failed with code ${errorOrCode}.`, { code: errorOrCode, - }) - ); + }), + ) } else if (errorOrCode?.message) { this.connectionManager.rejectAllAwaiting( - new NotConnectedError(errorOrCode.message, errorOrCode) - ); + new NotConnectedError(errorOrCode.message, errorOrCode), + ) } else { this.connectionManager.rejectAllAwaiting( - new NotConnectedError("Connection failed.") - ); + new NotConnectedError('Connection failed.'), + ) } } } diff --git a/src/client/connectionManager.ts b/src/client/connectionManager.ts index 50136e8c..017af5e4 100644 --- a/src/client/connectionManager.ts +++ b/src/client/connectionManager.ts @@ -5,16 +5,16 @@ */ export default class ConnectionManager { private promisesAwaitingConnection: Array<{ - resolve: (value?: void | PromiseLike) => void; - reject: (value?: Error) => void; - }> = []; + resolve: (value?: void | PromiseLike) => void + reject: (value?: Error) => void + }> = [] /** * Resolves all awaiting connections. */ public resolveAllAwaiting(): void { - this.promisesAwaitingConnection.map(({ resolve }) => resolve()); - this.promisesAwaitingConnection = []; + this.promisesAwaitingConnection.map(({ resolve }) => resolve()) + this.promisesAwaitingConnection = [] } /** @@ -23,8 +23,8 @@ export default class ConnectionManager { * @param error - Error to throw in the rejection. */ public rejectAllAwaiting(error: Error): void { - this.promisesAwaitingConnection.map(({ reject }) => reject(error)); - this.promisesAwaitingConnection = []; + this.promisesAwaitingConnection.map(({ reject }) => reject(error)) + this.promisesAwaitingConnection = [] } /** @@ -34,7 +34,7 @@ export default class ConnectionManager { */ public async awaitConnection(): Promise { return new Promise((resolve, reject) => { - this.promisesAwaitingConnection.push({ resolve, reject }); - }); + this.promisesAwaitingConnection.push({ resolve, reject }) + }) } } diff --git a/src/client/index.ts b/src/client/index.ts index e44d8c9a..dc06ee30 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -1,7 +1,7 @@ /* eslint-disable import/max-dependencies -- Client needs a lot of dependencies by definition */ /* eslint-disable @typescript-eslint/member-ordering -- TODO: remove when instance methods aren't members */ /* eslint-disable max-lines -- This might not be necessary later, but this file needs to be big right now */ -import { EventEmitter } from "events"; +import { EventEmitter } from 'events' import { classicAddressToXAddress, @@ -18,16 +18,16 @@ import { decodeAccountPublic, encodeXAddress, decodeXAddress, -} from "ripple-address-codec"; +} from 'ripple-address-codec' -import { constants, errors, txFlags, ensureClassicAddress } from "../common"; -import { RippledError, ValidationError } from "../common/errors"; -import { getFee } from "../common/fee"; -import getBalances from "../ledger/balances"; -import { getOrderbook, formatBidsAndAsks } from "../ledger/orderbook"; -import getPaths from "../ledger/pathfind"; -import getTrustlines from "../ledger/trustlines"; -import { clamp } from "../ledger/utils"; +import { constants, errors, txFlags, ensureClassicAddress } from '../common' +import { RippledError, ValidationError } from '../common/errors' +import { getFee } from '../common/fee' +import getBalances from '../ledger/balances' +import { getOrderbook, formatBidsAndAsks } from '../ledger/orderbook' +import getPaths from '../ledger/pathfind' +import getTrustlines from '../ledger/trustlines' +import { clamp } from '../ledger/utils' import { // account methods AccountChannelsRequest, @@ -94,41 +94,41 @@ import { PingResponse, RandomRequest, RandomResponse, -} from "../models/methods"; -import { BaseRequest, BaseResponse } from "../models/methods/baseMethod"; -import prepareCheckCancel from "../transaction/check-cancel"; -import prepareCheckCash from "../transaction/check-cash"; -import prepareCheckCreate from "../transaction/check-create"; -import combine from "../transaction/combine"; -import prepareEscrowCancellation from "../transaction/escrow-cancellation"; -import prepareEscrowCreation from "../transaction/escrow-creation"; -import prepareEscrowExecution from "../transaction/escrow-execution"; -import prepareOrder from "../transaction/order"; -import prepareOrderCancellation from "../transaction/ordercancellation"; -import preparePayment from "../transaction/payment"; -import preparePaymentChannelClaim from "../transaction/payment-channel-claim"; -import preparePaymentChannelCreate from "../transaction/payment-channel-create"; -import preparePaymentChannelFund from "../transaction/payment-channel-fund"; -import prepareSettings from "../transaction/settings"; -import { sign } from "../transaction/sign"; -import prepareTicketCreate from "../transaction/ticket"; -import prepareTrustline from "../transaction/trustline"; -import { TransactionJSON, Instructions, Prepare } from "../transaction/types"; -import * as transactionUtils from "../transaction/utils"; -import { deriveAddress, deriveXAddress } from "../utils/derive"; -import generateFaucetWallet from "../wallet/generateFaucetWallet"; +} from '../models/methods' +import { BaseRequest, BaseResponse } from '../models/methods/baseMethod' +import prepareCheckCancel from '../transaction/check-cancel' +import prepareCheckCash from '../transaction/check-cash' +import prepareCheckCreate from '../transaction/check-create' +import combine from '../transaction/combine' +import prepareEscrowCancellation from '../transaction/escrow-cancellation' +import prepareEscrowCreation from '../transaction/escrow-creation' +import prepareEscrowExecution from '../transaction/escrow-execution' +import prepareOrder from '../transaction/order' +import prepareOrderCancellation from '../transaction/ordercancellation' +import preparePayment from '../transaction/payment' +import preparePaymentChannelClaim from '../transaction/payment-channel-claim' +import preparePaymentChannelCreate from '../transaction/payment-channel-create' +import preparePaymentChannelFund from '../transaction/payment-channel-fund' +import prepareSettings from '../transaction/settings' +import { sign } from '../transaction/sign' +import prepareTicketCreate from '../transaction/ticket' +import prepareTrustline from '../transaction/trustline' +import { TransactionJSON, Instructions, Prepare } from '../transaction/types' +import * as transactionUtils from '../transaction/utils' +import { deriveAddress, deriveXAddress } from '../utils/derive' +import generateFaucetWallet from '../wallet/generateFaucetWallet' import { Connection, ConnectionUserOptions, INTENTIONAL_DISCONNECT_CODE, -} from "./connection"; +} from './connection' export interface ClientOptions extends ConnectionUserOptions { - feeCushion?: number; - maxFeeXRP?: string; - proxy?: string; - timeout?: number; + feeCushion?: number + maxFeeXRP?: string + proxy?: string + timeout?: number } /** @@ -141,52 +141,52 @@ export interface ClientOptions extends ConnectionUserOptions { */ function getCollectKeyFromCommand(command: string): string | null { switch (command) { - case "account_channels": - return "channels"; - case "account_lines": - return "lines"; - case "account_objects": - return "account_objects"; - case "account_tx": - return "transactions"; - case "account_offers": - case "book_offers": - return "offers"; - case "ledger_data": - return "state"; + case 'account_channels': + return 'channels' + case 'account_lines': + return 'lines' + case 'account_objects': + return 'account_objects' + case 'account_tx': + return 'transactions' + case 'account_offers': + case 'book_offers': + return 'offers' + case 'ledger_data': + return 'state' default: - return null; + return null } } interface MarkerRequest extends BaseRequest { - limit?: number; - marker?: unknown; + limit?: number + marker?: unknown } interface MarkerResponse extends BaseResponse { result: { - marker?: unknown; - }; + marker?: unknown + } } -const DEFAULT_FEE_CUSHION = 1.2; -const DEFAULT_MAX_FEE_XRP = "2"; +const DEFAULT_FEE_CUSHION = 1.2 +const DEFAULT_MAX_FEE_XRP = '2' -const MIN_LIMIT = 10; -const MAX_LIMIT = 400; +const MIN_LIMIT = 10 +const MAX_LIMIT = 400 class Client extends EventEmitter { // New in > 0.21.0 // non-validated ledger versions are allowed, and passed to rippled as-is. - public readonly connection: Connection; + public readonly connection: Connection // Factor to multiply estimated fee by to provide a cushion in case the // required fee rises during submission of a transaction. Defaults to 1.2. - public readonly feeCushion: number; + public readonly feeCushion: number // Maximum fee to use with transactions, in XRP. Must be a string-encoded // number. Defaults to '2'. - public readonly maxFeeXRP: string; + public readonly maxFeeXRP: string /** * Creates a new Client with a websocket connection to a rippled server. @@ -195,35 +195,35 @@ class Client extends EventEmitter { * @param options - Options for client settings. */ public constructor(server: string, options: ClientOptions = {}) { - super(); - if (typeof server !== "string" || !/wss?(?:\+unix)?:\/\//u.exec(server)) { + super() + if (typeof server !== 'string' || !/wss?(?:\+unix)?:\/\//u.exec(server)) { throw new ValidationError( - "server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`." - ); + 'server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.', + ) } - this.feeCushion = options.feeCushion ?? DEFAULT_FEE_CUSHION; - this.maxFeeXRP = options.maxFeeXRP ?? DEFAULT_MAX_FEE_XRP; + this.feeCushion = options.feeCushion ?? DEFAULT_FEE_CUSHION + this.maxFeeXRP = options.maxFeeXRP ?? DEFAULT_MAX_FEE_XRP - this.connection = new Connection(server, options); + this.connection = new Connection(server, options) - this.connection.on("error", (errorCode, errorMessage, data) => { - this.emit("error", errorCode, errorMessage, data); - }); + this.connection.on('error', (errorCode, errorMessage, data) => { + this.emit('error', errorCode, errorMessage, data) + }) - this.connection.on("connected", () => { - this.emit("connected"); - }); + this.connection.on('connected', () => { + this.emit('connected') + }) - this.connection.on("disconnected", (code: number) => { - let finalCode = code; + this.connection.on('disconnected', (code: number) => { + let finalCode = code // 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close // Since 4000 is a normal disconnect reason, we convert this to the standard exit code 1000 if (finalCode === INTENTIONAL_DISCONNECT_CODE) { - finalCode = 1000; + finalCode = 1000 } - this.emit("disconnected", finalCode); - }); + this.emit('disconnected', finalCode) + }) } /** @@ -238,54 +238,54 @@ class Client extends EventEmitter { * @returns Whether the response has more pages of data. */ public static hasNextPage(response: MarkerResponse): boolean { - return Boolean(response.result.marker); + return Boolean(response.result.marker) } public async request( - r: AccountChannelsRequest - ): Promise; + r: AccountChannelsRequest, + ): Promise public async request( - r: AccountCurrenciesRequest - ): Promise; - public async request(r: AccountInfoRequest): Promise; - public async request(r: AccountLinesRequest): Promise; + r: AccountCurrenciesRequest, + ): Promise + public async request(r: AccountInfoRequest): Promise + public async request(r: AccountLinesRequest): Promise public async request( - r: AccountObjectsRequest - ): Promise; - public async request(r: AccountOffersRequest): Promise; - public async request(r: AccountTxRequest): Promise; - public async request(r: BookOffersRequest): Promise; - public async request(r: ChannelVerifyRequest): Promise; + r: AccountObjectsRequest, + ): Promise + public async request(r: AccountOffersRequest): Promise + public async request(r: AccountTxRequest): Promise + public async request(r: BookOffersRequest): Promise + public async request(r: ChannelVerifyRequest): Promise public async request( - r: DepositAuthorizedRequest - ): Promise; - public async request(r: FeeRequest): Promise; + r: DepositAuthorizedRequest, + ): Promise + public async request(r: FeeRequest): Promise public async request( - r: GatewayBalancesRequest - ): Promise; - public async request(r: LedgerRequest): Promise; - public async request(r: LedgerClosedRequest): Promise; - public async request(r: LedgerCurrentRequest): Promise; - public async request(r: LedgerDataRequest): Promise; - public async request(r: LedgerEntryRequest): Promise; - public async request(r: ManifestRequest): Promise; - public async request(r: NoRippleCheckRequest): Promise; - public async request(r: PathFindRequest): Promise; - public async request(r: PingRequest): Promise; - public async request(r: RandomRequest): Promise; + r: GatewayBalancesRequest, + ): Promise + public async request(r: LedgerRequest): Promise + public async request(r: LedgerClosedRequest): Promise + public async request(r: LedgerCurrentRequest): Promise + public async request(r: LedgerDataRequest): Promise + public async request(r: LedgerEntryRequest): Promise + public async request(r: ManifestRequest): Promise + public async request(r: NoRippleCheckRequest): Promise + public async request(r: PathFindRequest): Promise + public async request(r: PingRequest): Promise + public async request(r: RandomRequest): Promise public async request( - r: RipplePathFindRequest - ): Promise; - public async request(r: ServerInfoRequest): Promise; - public async request(r: ServerStateRequest): Promise; - public async request(r: SubmitRequest): Promise; + r: RipplePathFindRequest, + ): Promise + public async request(r: ServerInfoRequest): Promise + public async request(r: ServerStateRequest): Promise + public async request(r: SubmitRequest): Promise public async request( - r: SubmitMultisignedRequest - ): Promise; + r: SubmitMultisignedRequest, + ): Promise public async request( - r: TransactionEntryRequest - ): Promise; - public async request(r: TxRequest): Promise; + r: TransactionEntryRequest, + ): Promise + public async request(r: TxRequest): Promise /** * Makes a request to the client with the given command and * additional request body parameters. @@ -294,7 +294,7 @@ class Client extends EventEmitter { * @returns The response from the server. */ public async request( - req: R + req: R, ): Promise { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Necessary for overloading return this.connection.request({ @@ -303,33 +303,33 @@ class Client extends EventEmitter { ? // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Must be string ensureClassicAddress(req.account as string) : undefined, - }) as unknown as T; + }) as unknown as T } public async requestNextPage( req: AccountChannelsRequest, - resp: AccountChannelsResponse - ): Promise; + resp: AccountChannelsResponse, + ): Promise public async requestNextPage( req: AccountLinesRequest, - resp: AccountLinesResponse - ): Promise; + resp: AccountLinesResponse, + ): Promise public async requestNextPage( req: AccountObjectsRequest, - resp: AccountObjectsResponse - ): Promise; + resp: AccountObjectsResponse, + ): Promise public async requestNextPage( req: AccountOffersRequest, - resp: AccountOffersResponse - ): Promise; + resp: AccountOffersResponse, + ): Promise public async requestNextPage( req: AccountTxRequest, - resp: AccountTxResponse - ): Promise; + resp: AccountTxResponse, + ): Promise public async requestNextPage( req: LedgerDataRequest, - resp: LedgerDataResponse - ): Promise; + resp: LedgerDataResponse, + ): Promise /** * Requests the next page of data. * @@ -339,16 +339,16 @@ class Client extends EventEmitter { */ public async requestNextPage< T extends MarkerRequest, - U extends MarkerResponse + U extends MarkerResponse, >(req: T, resp: U): Promise { if (!resp.result.marker) { return Promise.reject( - new errors.NotFoundError("response does not have a next page") - ); + new errors.NotFoundError('response does not have a next page'), + ) } - const nextPageRequest = { ...req, marker: resp.result.marker }; + const nextPageRequest = { ...req, marker: resp.result.marker } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Necessary for overloading - return this.connection.request(nextPageRequest) as unknown as U; + return this.connection.request(nextPageRequest) as unknown as U } /** @@ -362,30 +362,26 @@ class Client extends EventEmitter { */ public async prepareTransaction( txJSON: TransactionJSON, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { - return transactionUtils.prepareTransaction(txJSON, this, instructions); + return transactionUtils.prepareTransaction(txJSON, this, instructions) } public async requestAll( - req: AccountChannelsRequest - ): Promise; + req: AccountChannelsRequest, + ): Promise public async requestAll( - req: AccountLinesRequest - ): Promise; + req: AccountLinesRequest, + ): Promise public async requestAll( - req: AccountObjectsRequest - ): Promise; + req: AccountObjectsRequest, + ): Promise public async requestAll( - req: AccountOffersRequest - ): Promise; - public async requestAll(req: AccountTxRequest): Promise; - public async requestAll( - req: BookOffersRequest - ): Promise; - public async requestAll( - req: LedgerDataRequest - ): Promise; + req: AccountOffersRequest, + ): Promise + public async requestAll(req: AccountTxRequest): Promise + public async requestAll(req: BookOffersRequest): Promise + public async requestAll(req: LedgerDataRequest): Promise /** * Makes multiple paged requests to the client to return a given number of * resources. Multiple paged requests will be made until the `limit` @@ -406,51 +402,49 @@ class Client extends EventEmitter { */ public async requestAll( request: T, - collect?: string + collect?: string, ): Promise { // The data under collection is keyed based on the command. Fail if command // not recognized and collection key not provided. - const collectKey = collect ?? getCollectKeyFromCommand(request.command); + const collectKey = collect ?? getCollectKeyFromCommand(request.command) if (!collectKey) { - throw new ValidationError( - `no collect key for command ${request.command}` - ); + throw new ValidationError(`no collect key for command ${request.command}`) } // 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 = request.limit == null ? Infinity : request.limit; - let count = 0; - let marker: unknown = request.marker; - let lastBatchLength: number; - const results: U[] = []; + const countTo: number = request.limit == null ? Infinity : request.limit + let count = 0 + let marker: unknown = request.marker + let lastBatchLength: number + const results: U[] = [] do { - const countRemaining = clamp(countTo - count, MIN_LIMIT, MAX_LIMIT); + const countRemaining = clamp(countTo - count, MIN_LIMIT, MAX_LIMIT) const repeatProps = { ...request, limit: countRemaining, marker, - }; + } // eslint-disable-next-line no-await-in-loop -- Necessary for this, it really has to wait - const singleResponse = await this.connection.request(repeatProps); + const singleResponse = await this.connection.request(repeatProps) // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true - const singleResult = (singleResponse as U).result; + const singleResult = (singleResponse as U).result if (!(collectKey in singleResult)) { - throw new RippledError(`${collectKey} not in result`); + throw new RippledError(`${collectKey} not in result`) } // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Should be true - const collectedData = singleResult[collectKey]; - marker = singleResult.marker; + const collectedData = singleResult[collectKey] + marker = singleResult.marker // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true - results.push(singleResponse as U); + results.push(singleResponse as U) // Make sure we handle when no data (not even an empty array) is returned. if (Array.isArray(collectedData)) { - count += collectedData.length; - lastBatchLength = collectedData.length; + count += collectedData.length + lastBatchLength = collectedData.length } else { - lastBatchLength = 0; + lastBatchLength = 0 } - } while (Boolean(marker) && count < countTo && lastBatchLength !== 0); - return results; + } while (Boolean(marker) && count < countTo && lastBatchLength !== 0) + return results } /** @@ -459,7 +453,7 @@ class Client extends EventEmitter { * @returns A promise that resolves with a void value when a connection is established. */ public async connect(): Promise { - return this.connection.connect(); + return this.connection.connect() } /** @@ -470,7 +464,7 @@ class Client extends EventEmitter { public async disconnect(): Promise { // backwards compatibility: connection.disconnect() can return a number, but // this method returns nothing. SO we await but don't return any result. - await this.connection.disconnect(); + await this.connection.disconnect() } /** @@ -479,67 +473,67 @@ class Client extends EventEmitter { * @returns Whether the client instance is connected. */ public isConnected(): boolean { - return this.connection.isConnected(); + return this.connection.isConnected() } - public getFee = getFee; + public getFee = getFee - public getTrustlines = getTrustlines; - public getBalances = getBalances; - public getPaths = getPaths; - public getOrderbook = getOrderbook; + public getTrustlines = getTrustlines + public getBalances = getBalances + public getPaths = getPaths + public getOrderbook = getOrderbook - public preparePayment = preparePayment; - public prepareTrustline = prepareTrustline; - public prepareOrder = prepareOrder; - public prepareOrderCancellation = prepareOrderCancellation; - public prepareEscrowCreation = prepareEscrowCreation; - public prepareEscrowExecution = prepareEscrowExecution; - public prepareEscrowCancellation = prepareEscrowCancellation; - public preparePaymentChannelCreate = preparePaymentChannelCreate; - public preparePaymentChannelFund = preparePaymentChannelFund; - public preparePaymentChannelClaim = preparePaymentChannelClaim; - public prepareCheckCreate = prepareCheckCreate; - public prepareCheckCash = prepareCheckCash; - public prepareCheckCancel = prepareCheckCancel; - public prepareTicketCreate = prepareTicketCreate; - public prepareSettings = prepareSettings; - public sign = sign; - public combine = combine; + public preparePayment = preparePayment + public prepareTrustline = prepareTrustline + public prepareOrder = prepareOrder + public prepareOrderCancellation = prepareOrderCancellation + public prepareEscrowCreation = prepareEscrowCreation + public prepareEscrowExecution = prepareEscrowExecution + public prepareEscrowCancellation = prepareEscrowCancellation + public preparePaymentChannelCreate = preparePaymentChannelCreate + public preparePaymentChannelFund = preparePaymentChannelFund + public preparePaymentChannelClaim = preparePaymentChannelClaim + public prepareCheckCreate = prepareCheckCreate + public prepareCheckCash = prepareCheckCash + public prepareCheckCancel = prepareCheckCancel + public prepareTicketCreate = prepareTicketCreate + public prepareSettings = prepareSettings + public sign = sign + public combine = combine - public generateFaucetWallet = generateFaucetWallet; + public generateFaucetWallet = generateFaucetWallet - public errors = errors; + public errors = errors - public static deriveXAddress = deriveXAddress; + public static deriveXAddress = deriveXAddress // Client.deriveClassicAddress (static) is a new name for client.deriveAddress - public static deriveClassicAddress = deriveAddress; + public static deriveClassicAddress = deriveAddress - public static formatBidsAndAsks = formatBidsAndAsks; + public static formatBidsAndAsks = formatBidsAndAsks /** * Static methods to expose ripple-address-codec methods. */ - public static classicAddressToXAddress = classicAddressToXAddress; - public static xAddressToClassicAddress = xAddressToClassicAddress; - public static isValidXAddress = isValidXAddress; - public static isValidClassicAddress = isValidClassicAddress; - public static encodeSeed = encodeSeed; - public static decodeSeed = decodeSeed; - public static encodeAccountID = encodeAccountID; - public static decodeAccountID = decodeAccountID; - public static encodeNodePublic = encodeNodePublic; - public static decodeNodePublic = decodeNodePublic; - public static encodeAccountPublic = encodeAccountPublic; - public static decodeAccountPublic = decodeAccountPublic; - public static encodeXAddress = encodeXAddress; - public static decodeXAddress = decodeXAddress; + public static classicAddressToXAddress = classicAddressToXAddress + public static xAddressToClassicAddress = xAddressToClassicAddress + public static isValidXAddress = isValidXAddress + public static isValidClassicAddress = isValidClassicAddress + public static encodeSeed = encodeSeed + public static decodeSeed = decodeSeed + public static encodeAccountID = encodeAccountID + public static decodeAccountID = decodeAccountID + public static encodeNodePublic = encodeNodePublic + public static decodeNodePublic = decodeNodePublic + public static encodeAccountPublic = encodeAccountPublic + public static decodeAccountPublic = decodeAccountPublic + public static encodeXAddress = encodeXAddress + public static decodeXAddress = decodeXAddress - public txFlags = txFlags; - public static txFlags = txFlags; - public accountSetFlags = constants.AccountSetFlags; - public static accountSetFlags = constants.AccountSetFlags; + public txFlags = txFlags + public static txFlags = txFlags + public accountSetFlags = constants.AccountSetFlags + public static accountSetFlags = constants.AccountSetFlags } -export { Client, Connection }; +export { Client, Connection } diff --git a/src/client/requestManager.ts b/src/client/requestManager.ts index ffaa3151..4e73426c 100644 --- a/src/client/requestManager.ts +++ b/src/client/requestManager.ts @@ -2,9 +2,9 @@ import { ResponseFormatError, RippledError, TimeoutError, -} from "../common/errors"; -import { Response } from "../models/methods"; -import { BaseRequest } from "../models/methods/baseMethod"; +} from '../common/errors' +import { Response } from '../models/methods' +import { BaseRequest } from '../models/methods/baseMethod' /** * Manage all the requests made to the websocket, and their async responses @@ -13,15 +13,15 @@ import { BaseRequest } from "../models/methods/baseMethod"; * original request. */ export default class RequestManager { - private nextId = 0; + private nextId = 0 private readonly promisesAwaitingResponse = new Map< string | number, { - resolve: (value?: Response | PromiseLike) => void; - reject: (value?: Error) => void; - timer: NodeJS.Timeout; + resolve: (value?: Response | PromiseLike) => void + reject: (value?: Error) => void + timer: NodeJS.Timeout } - >(); + >() /** * Cancels a request. @@ -30,12 +30,12 @@ export default class RequestManager { * @throws Error if no existing promise with the given ID. */ public cancel(id: string | number): void { - const promise = this.promisesAwaitingResponse.get(id); + const promise = this.promisesAwaitingResponse.get(id) if (promise == null) { - throw new Error(`No existing promise with id ${id}`); + throw new Error(`No existing promise with id ${id}`) } - clearTimeout(promise.timer); - this.deletePromise(id); + clearTimeout(promise.timer) + this.deletePromise(id) } /** @@ -46,13 +46,13 @@ export default class RequestManager { * @throws Error if no existing promise with the given ID. */ public resolve(id: string | number, response: Response): void { - const promise = this.promisesAwaitingResponse.get(id); + const promise = this.promisesAwaitingResponse.get(id) if (promise == null) { - throw new Error(`No existing promise with id ${id}`); + throw new Error(`No existing promise with id ${id}`) } - clearTimeout(promise.timer); - promise.resolve(response); - this.deletePromise(id); + clearTimeout(promise.timer) + promise.resolve(response) + this.deletePromise(id) } /** @@ -63,13 +63,13 @@ export default class RequestManager { * @throws Error if no existing promise with the given ID. */ public reject(id: string | number, error: Error): void { - const promise = this.promisesAwaitingResponse.get(id); + const promise = this.promisesAwaitingResponse.get(id) if (promise == null) { - throw new Error(`No existing promise with id ${id}`); + throw new Error(`No existing promise with id ${id}`) } - clearTimeout(promise.timer); - promise.reject(error); - this.deletePromise(id); + clearTimeout(promise.timer) + promise.reject(error) + this.deletePromise(id) } /** @@ -79,8 +79,8 @@ export default class RequestManager { */ public rejectAll(error: Error): void { this.promisesAwaitingResponse.forEach((_promise, id, _map) => { - this.reject(id, error); - }); + this.reject(id, error) + }) } /** @@ -94,27 +94,27 @@ export default class RequestManager { */ public createRequest( request: T, - timeout: number + timeout: number, ): [string | number, string, Promise] { - const newId = request.id ? request.id : this.nextId; - this.nextId += 1; - const newRequest = JSON.stringify({ ...request, id: newId }); + const newId = request.id ? request.id : this.nextId + this.nextId += 1 + const newRequest = JSON.stringify({ ...request, id: newId }) const timer = setTimeout( () => this.reject(newId, new TimeoutError()), - timeout - ); + timeout, + ) // Node.js won't exit if a timer is still running, so we tell Node to ignore. // (Node will still wait for the request to complete). // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Reason above. if (timer.unref) { - timer.unref(); + timer.unref() } const newPromise = new Promise( (resolve: (value?: Response | PromiseLike) => void, reject) => { - this.promisesAwaitingResponse.set(newId, { resolve, reject, timer }); - } - ); - return [newId, newRequest, newPromise]; + this.promisesAwaitingResponse.set(newId, { resolve, reject, timer }) + }, + ) + return [newId, newRequest, newPromise] } /** @@ -130,33 +130,33 @@ export default class RequestManager { !Number.isInteger(response.id) || response.id < 0 ) { - throw new ResponseFormatError("valid id not found in response", response); + throw new ResponseFormatError('valid id not found in response', response) } if (!this.promisesAwaitingResponse.has(response.id)) { - return; + return } if (response.status == null) { - const error = new ResponseFormatError("Response has no status"); - this.reject(response.id, error); + const error = new ResponseFormatError('Response has no status') + this.reject(response.id, error) } - if (response.status === "error") { + if (response.status === 'error') { const error = new RippledError( response.error_message ?? response.error, - response - ); - this.reject(response.id, error); - return; + response, + ) + this.reject(response.id, error) + return } - if (response.status !== "success") { + if (response.status !== 'success') { const error = new ResponseFormatError( - `unrecognized response.status: ${response.status ?? ""}`, - response - ); - this.reject(response.id, error); - return; + `unrecognized response.status: ${response.status ?? ''}`, + response, + ) + this.reject(response.id, error) + return } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Must be a valid Response here - this.resolve(response.id, response as unknown as Response); + this.resolve(response.id, response as unknown as Response) } /** @@ -166,6 +166,6 @@ export default class RequestManager { */ private deletePromise(id: string | number): void { // eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- Needs to delete promise after request has been fulfilled. - delete this.promisesAwaitingResponse[id]; + delete this.promisesAwaitingResponse[id] } } diff --git a/src/client/wsWrapper.ts b/src/client/wsWrapper.ts index b40417a2..1c50d9db 100644 --- a/src/client/wsWrapper.ts +++ b/src/client/wsWrapper.ts @@ -1,27 +1,27 @@ /* eslint-disable import/no-unused-modules -- This is used by webpack */ /* eslint-disable max-classes-per-file -- Needs to be a wrapper for ws */ -import { EventEmitter } from "events"; +import { EventEmitter } from 'events' // Define the global WebSocket class found on the native browser declare class WebSocket { - public onclose?: () => void; - public onopen?: () => void; - public onerror?: (error: Error) => void; - public onmessage?: (message: MessageEvent) => void; - public readyState: number; - public constructor(url: string); - public close(code?: number): void; - public send(message: string): void; + public onclose?: () => void + public onopen?: () => void + public onerror?: (error: Error) => void + public onmessage?: (message: MessageEvent) => void + public readyState: number + public constructor(url: string) + public close(code?: number): void + public send(message: string): void } interface WSWrapperOptions { - perMessageDeflate: boolean; - handshakeTimeout: number; - protocolVersion: number; - origin: string; - maxPayload: number; - followRedirects: boolean; - maxRedirects: number; + perMessageDeflate: boolean + handshakeTimeout: number + protocolVersion: number + origin: string + maxPayload: number + followRedirects: boolean + maxRedirects: number } /** @@ -29,12 +29,12 @@ interface WSWrapperOptions { * same, as `ws` package provides. */ export default class WSWrapper extends EventEmitter { - public static CONNECTING = 0; - public static OPEN = 1; - public static CLOSING = 2; + public static CONNECTING = 0 + public static OPEN = 1 + public static CLOSING = 2 // eslint-disable-next-line @typescript-eslint/no-magic-numbers -- magic number is being defined here - public static CLOSED = 3; - private readonly ws: WebSocket; + public static CLOSED = 3 + private readonly ws: WebSocket /** * Constructs a browser-safe websocket. @@ -46,28 +46,28 @@ export default class WSWrapper extends EventEmitter { public constructor( url: string, _protocols: string | string[] | WSWrapperOptions | undefined, - _websocketOptions: WSWrapperOptions + _websocketOptions: WSWrapperOptions, ) { - super(); - this.setMaxListeners(Infinity); + super() + this.setMaxListeners(Infinity) - this.ws = new WebSocket(url); + this.ws = new WebSocket(url) this.ws.onclose = (): void => { - this.emit("close"); - }; + this.emit('close') + } this.ws.onopen = (): void => { - this.emit("open"); - }; + this.emit('open') + } this.ws.onerror = (error): void => { - this.emit("error", error); - }; + this.emit('error', error) + } this.ws.onmessage = (message: MessageEvent): void => { - this.emit("message", message.data); - }; + this.emit('message', message.data) + } } /** @@ -75,7 +75,7 @@ export default class WSWrapper extends EventEmitter { */ public close(): void { if (this.readyState === 1) { - this.ws.close(); + this.ws.close() } } @@ -85,7 +85,7 @@ export default class WSWrapper extends EventEmitter { * @param message - Message to send. */ public send(message: string): void { - this.ws.send(message); + this.ws.send(message) } /** @@ -94,6 +94,6 @@ export default class WSWrapper extends EventEmitter { * @returns The Websocket's ready state. */ public get readyState(): number { - return this.ws.readyState; + return this.ws.readyState } } diff --git a/src/common/constants.ts b/src/common/constants.ts index 0b04b0b0..3f10e2bf 100644 --- a/src/common/constants.ts +++ b/src/common/constants.ts @@ -1,4 +1,4 @@ -import { txFlagIndices } from "./txflags"; +import { txFlagIndices } from './txflags' // Ordering from https://developers.ripple.com/accountroot.html const accountRootFlags = { @@ -44,7 +44,7 @@ const accountRootFlags = { // lsfRequireDestTag: // Require a DestinationTag for incoming payments. RequireDestTag: 0x00020000, -}; +} const AccountFlags = { passwordSpent: accountRootFlags.PasswordSpent, @@ -56,18 +56,18 @@ const AccountFlags = { noFreeze: accountRootFlags.NoFreeze, globalFreeze: accountRootFlags.GlobalFreeze, defaultRipple: accountRootFlags.DefaultRipple, -}; +} export interface Settings { - passwordSpent?: boolean; - requireDestinationTag?: boolean; - requireAuthorization?: boolean; - depositAuth?: boolean; - disallowIncomingXRP?: boolean; - disableMasterKey?: boolean; - noFreeze?: boolean; - globalFreeze?: boolean; - defaultRipple?: boolean; + passwordSpent?: boolean + requireDestinationTag?: boolean + requireAuthorization?: boolean + depositAuth?: boolean + disallowIncomingXRP?: boolean + disableMasterKey?: boolean + noFreeze?: boolean + globalFreeze?: boolean + defaultRipple?: boolean } const AccountSetFlags = { @@ -80,20 +80,20 @@ const AccountSetFlags = { noFreeze: txFlagIndices.AccountSet.asfNoFreeze, globalFreeze: txFlagIndices.AccountSet.asfGlobalFreeze, defaultRipple: txFlagIndices.AccountSet.asfDefaultRipple, -}; +} const AccountFields = { EmailHash: { - name: "emailHash", - encoding: "hex", + name: 'emailHash', + encoding: 'hex', length: 32, - defaults: "00000000000000000000000000000000", + defaults: '00000000000000000000000000000000', }, - WalletLocator: { name: "walletLocator" }, - MessageKey: { name: "messageKey" }, - Domain: { name: "domain", encoding: "hex" }, - TransferRate: { name: "transferRate", defaults: 0, shift: 9 }, - TickSize: { name: "tickSize", defaults: 0 }, -}; + WalletLocator: { name: 'walletLocator' }, + MessageKey: { name: 'messageKey' }, + Domain: { name: 'domain', encoding: 'hex' }, + TransferRate: { name: 'transferRate', defaults: 0, shift: 9 }, + TickSize: { name: 'tickSize', defaults: 0 }, +} -export { AccountFields, AccountSetFlags, AccountFlags }; +export { AccountFields, AccountSetFlags, AccountFlags } diff --git a/src/common/ecdsa.ts b/src/common/ecdsa.ts index 426a70a8..d166c2d1 100644 --- a/src/common/ecdsa.ts +++ b/src/common/ecdsa.ts @@ -1,6 +1,6 @@ enum ECDSA { - ed25519 = "ed25519", - secp256k1 = "ecdsa-secp256k1", + ed25519 = 'ed25519', + secp256k1 = 'ecdsa-secp256k1', } -export default ECDSA; +export default ECDSA diff --git a/src/common/errors.ts b/src/common/errors.ts index f8695abb..d582da70 100644 --- a/src/common/errors.ts +++ b/src/common/errors.ts @@ -1,35 +1,35 @@ -import { inspect } from "util"; +import { inspect } from 'util' class RippleError extends Error { - name: string; - message: string; - data?: any; + name: string + message: string + data?: any - constructor(message = "", data?: any) { - super(message); + constructor(message = '', data?: any) { + super(message) - this.name = this.constructor.name; - this.message = message; - this.data = data; + this.name = this.constructor.name + this.message = message + this.data = data if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + Error.captureStackTrace(this, this.constructor) } } toString() { - let result = `[${this.name}(${this.message}`; + let result = `[${this.name}(${this.message}` if (this.data) { - result += `, ${inspect(this.data)}`; + result += `, ${inspect(this.data)}` } - result += ")]"; - return result; + result += ')]' + return result } // console.log in node uses util.inspect on object, and util.inspect allows // us to customize its output: // https://nodejs.org/api/util.html#util_custom_inspect_function_on_objects inspect() { - return this.toString(); + return this.toString() } } @@ -56,14 +56,14 @@ class ValidationError extends RippleError {} class XRPLFaucetError extends RippleError {} class NotFoundError extends RippleError { - constructor(message = "Not found") { - super(message); + constructor(message = 'Not found') { + super(message) } } class MissingLedgerHistoryError extends RippleError { constructor(message?: string) { - super(message || "Server is missing ledger history in the specified range"); + super(message || 'Server is missing ledger history in the specified range') } } @@ -72,8 +72,8 @@ class PendingLedgerVersionError extends RippleError { super( message || "maxLedgerVersion is greater than server's most recent" + - " validated ledger" - ); + ' validated ledger', + ) } } @@ -93,4 +93,4 @@ export { MissingLedgerHistoryError, LedgerVersionError, XRPLFaucetError, -}; +} diff --git a/src/common/fee.ts b/src/common/fee.ts index a3b92072..d830ebe7 100644 --- a/src/common/fee.ts +++ b/src/common/fee.ts @@ -1,38 +1,38 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' -import type { Client } from ".."; +import type { Client } from '..' // 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: Client, cushion?: number): Promise { if (cushion == null) { - cushion = this.feeCushion; + cushion = this.feeCushion } if (cushion == null) { - cushion = 1.2; + cushion = 1.2 } - const serverInfo = (await this.request({ command: "server_info" })).result - .info; + const serverInfo = (await this.request({ command: 'server_info' })).result + .info - const baseFee = serverInfo.validated_ledger?.base_fee_xrp; + const baseFee = serverInfo.validated_ledger?.base_fee_xrp if (baseFee == null) { - throw new Error("getFee: Could not get base_fee_xrp from server_info"); + throw new Error('getFee: Could not get base_fee_xrp from server_info') } - const baseFeeXrp = new BigNumber(baseFee); + const baseFeeXrp = new BigNumber(baseFee) if (serverInfo.load_factor == null) { // https://github.com/ripple/rippled/issues/3812#issuecomment-816871100 - serverInfo.load_factor = 1; + serverInfo.load_factor = 1 } - let fee = baseFeeXrp.times(serverInfo.load_factor).times(cushion); + let fee = baseFeeXrp.times(serverInfo.load_factor).times(cushion) // Cap fee to `this.maxFeeXRP` - fee = BigNumber.min(fee, this.maxFeeXRP); + fee = BigNumber.min(fee, this.maxFeeXRP) // Round fee to 6 decimal places - return new BigNumber(fee.toFixed(6)).toString(10); + return new BigNumber(fee.toFixed(6)).toString(10) } -export { getFee }; +export { getFee } diff --git a/src/common/index.ts b/src/common/index.ts index fb9833c8..cb57b4d2 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -1,29 +1,26 @@ -import { - xAddressToClassicAddress, - isValidXAddress, -} from "ripple-address-codec"; +import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec' -import * as constants from "./constants"; -import * as errors from "./errors"; +import * as constants from './constants' +import * as errors from './errors' export function ensureClassicAddress(account: string): string { if (isValidXAddress(account)) { - const { classicAddress, tag } = xAddressToClassicAddress(account); + const { classicAddress, tag } = xAddressToClassicAddress(account) // Except for special cases, X-addresses used for requests // must not have an embedded tag. In other words, // `tag` should be `false`. if (tag !== false) { throw new Error( - "This command does not support the use of a tag. Use an address without a tag." - ); + 'This command does not support the use of a tag. Use an address without a tag.', + ) } // For rippled requests that use an account, always use a classic address. - return classicAddress; + return classicAddress } - return account; + return account } -export { constants, errors }; -export { txFlags } from "./txflags"; +export { constants, errors } +export { txFlags } from './txflags' diff --git a/src/common/txflags.ts b/src/common/txflags.ts index 1bb410cd..2dfc0894 100644 --- a/src/common/txflags.ts +++ b/src/common/txflags.ts @@ -39,7 +39,7 @@ const txFlags = { Renew: 0x00010000, Close: 0x00020000, }, -}; +} // The following are integer (as opposed to bit) flags // that can be set for particular transactions in the @@ -56,6 +56,6 @@ const txFlagIndices = { asfDefaultRipple: 8, asfDepositAuth: 9, }, -}; +} -export { txFlags, txFlagIndices }; +export { txFlags, txFlagIndices } diff --git a/src/common/types/commands/account_info.ts b/src/common/types/commands/account_info.ts index d91b5ded..dba9f8a8 100644 --- a/src/common/types/commands/account_info.ts +++ b/src/common/types/commands/account_info.ts @@ -2,22 +2,22 @@ import { AccountRootLedgerEntry, SignerListLedgerEntry, QueueData, -} from "../objects"; +} from '../objects' export interface AccountInfoRequest { - account: string; - strict?: boolean; - queue?: boolean; - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - signer_lists?: boolean; + account: string + strict?: boolean + queue?: boolean + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + signer_lists?: boolean } export interface AccountInfoResponse { - account_data: AccountRootLedgerEntry; - signer_lists?: SignerListLedgerEntry[]; - ledger_current_index?: number; - ledger_index?: number; - queue_data?: QueueData; - validated?: boolean; + account_data: AccountRootLedgerEntry + signer_lists?: SignerListLedgerEntry[] + ledger_current_index?: number + ledger_index?: number + queue_data?: QueueData + validated?: boolean } diff --git a/src/common/types/commands/account_lines.ts b/src/common/types/commands/account_lines.ts index 42c7b40a..41e34ce6 100644 --- a/src/common/types/commands/account_lines.ts +++ b/src/common/types/commands/account_lines.ts @@ -1,19 +1,19 @@ -import { Trustline } from "../objects"; +import { Trustline } from '../objects' export interface AccountLinesRequest { - account: string; - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - peer?: string; - limit?: number; - marker?: unknown; + account: string + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + peer?: string + limit?: number + marker?: unknown } export interface AccountLinesResponse { - account: string; - lines: Trustline[]; - ledger_current_index?: number; - ledger_index?: number; - ledger_hash?: string; - marker?: unknown; + account: string + lines: Trustline[] + ledger_current_index?: number + ledger_index?: number + ledger_hash?: string + marker?: unknown } diff --git a/src/common/types/commands/account_objects.ts b/src/common/types/commands/account_objects.ts index bedb7fb1..a80ff515 100644 --- a/src/common/types/commands/account_objects.ts +++ b/src/common/types/commands/account_objects.ts @@ -1,4 +1,4 @@ -import { AccountObjectType } from "../../../models/common"; +import { AccountObjectType } from '../../../models/common' import { CheckLedgerEntry, RippleStateLedgerEntry, @@ -7,45 +7,45 @@ import { EscrowLedgerEntry, PayChannelLedgerEntry, DepositPreauthLedgerEntry, -} from "../objects"; +} from '../objects' export interface GetAccountObjectsOptions { - type?: AccountObjectType; - ledgerHash?: string; - ledgerIndex?: number | ("validated" | "closed" | "current"); - limit?: number; - marker?: string; + type?: AccountObjectType + ledgerHash?: string + ledgerIndex?: number | ('validated' | 'closed' | 'current') + limit?: number + marker?: string } export interface AccountObjectsRequest { - account: string; + account: string // (Optional) Filter results to include only this type of ledger object. type?: | string | ( - | "check" - | "escrow" - | "offer" - | "payment_channel" - | "signer_list" - | "state" - ); + | 'check' + | 'escrow' + | 'offer' + | 'payment_channel' + | 'signer_list' + | 'state' + ) // (Optional) A 20-byte hex string for the ledger version to use. - ledger_hash?: string; + ledger_hash?: string // (Optional) The sequence number of the ledger to use, // or a shortcut string to choose a ledger automatically. - ledger_index?: number | ("validated" | "closed" | "current"); + ledger_index?: number | ('validated' | 'closed' | 'current') - limit?: number; + limit?: number - marker?: string; + marker?: string } export interface AccountObjectsResponse { - account: string; + account: string // Array of objects owned by this account. // from the getAccountObjects section of the dev center @@ -57,29 +57,29 @@ export interface AccountObjectsResponse { | EscrowLedgerEntry | PayChannelLedgerEntry | DepositPreauthLedgerEntry - >; + > // (May be omitted) The identifying hash of the ledger // that was used to generate this response. - ledger_hash?: string; + ledger_hash?: string // (May be omitted) The sequence number of the ledger version // that was used to generate this response. - ledger_index?: number; + ledger_index?: number // (May be omitted) The sequence number of the current in-progress ledger // version that was used to generate this response. - ledger_current_index?: number; + ledger_current_index?: number // The limit that was used in this request, if any. - limit?: number; + limit?: number // Server-defined value indicating the response is paginated. Pass this // to the next call to resume where this call left off. Omitted when there // are no additional pages after this one. - marker?: string; + marker?: string // If true, this information comes from a ledger version // that has been validated by consensus. - validated?: boolean; + validated?: boolean } diff --git a/src/common/types/commands/account_offers.ts b/src/common/types/commands/account_offers.ts index a68af7d7..3efa9881 100644 --- a/src/common/types/commands/account_offers.ts +++ b/src/common/types/commands/account_offers.ts @@ -1,27 +1,27 @@ -import { RippledAmount } from "../objects"; +import { RippledAmount } from '../objects' export interface AccountOffersRequest { - account: string; - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - limit?: number; - marker?: unknown; + account: string + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + limit?: number + marker?: unknown } export interface AccountOffersResponse { - account: string; - ledger_hash?: string; - ledger_current_index?: number; - ledger_index?: number; - marker?: unknown; - offers?: AccountOffer[]; + account: string + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number + marker?: unknown + offers?: AccountOffer[] } export interface AccountOffer { - seq: number; - flags: number; - taker_gets: RippledAmount; - taker_pays: RippledAmount; - quality: string; - expiration?: number; + seq: number + flags: number + taker_gets: RippledAmount + taker_pays: RippledAmount + quality: string + expiration?: number } diff --git a/src/common/types/commands/book_offers.ts b/src/common/types/commands/book_offers.ts index 11b7b861..31109320 100644 --- a/src/common/types/commands/book_offers.ts +++ b/src/common/types/commands/book_offers.ts @@ -1,30 +1,26 @@ -import { - TakerRequestAmount, - RippledAmount, - OfferLedgerEntry, -} from "../objects"; +import { TakerRequestAmount, RippledAmount, OfferLedgerEntry } from '../objects' export interface BookOffersRequest { - taker?: string; - taker_gets: TakerRequestAmount; - taker_pays: TakerRequestAmount; - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - limit?: number; - marker?: unknown; + taker?: string + taker_gets: TakerRequestAmount + taker_pays: TakerRequestAmount + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + limit?: number + marker?: unknown } export interface BookOffersResponse { - offers: BookOffer[]; - ledger_hash?: string; - ledger_current_index?: number; - ledger_index?: number; - marker?: unknown; + offers: BookOffer[] + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number + marker?: unknown } export interface BookOffer extends OfferLedgerEntry { - quality?: string; - owner_funds?: string; - taker_gets_funded?: RippledAmount; - taker_pays_funded?: RippledAmount; + quality?: string + owner_funds?: string + taker_gets_funded?: RippledAmount + taker_pays_funded?: RippledAmount } diff --git a/src/common/types/commands/gateway_balances.ts b/src/common/types/commands/gateway_balances.ts index 4698f3ec..651b4725 100644 --- a/src/common/types/commands/gateway_balances.ts +++ b/src/common/types/commands/gateway_balances.ts @@ -1,19 +1,19 @@ -import { Amount } from "../objects"; +import { Amount } from '../objects' export interface GatewayBalancesRequest { - account: string; - strict?: boolean; - hotwallet: string | string[]; - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); + account: string + strict?: boolean + hotwallet: string | string[] + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') } export interface GatewayBalancesResponse { - account: string; - obligations?: { [currency: string]: string }; - balances?: { [address: string]: Amount[] }; - assets?: { [address: string]: Amount[] }; - ledger_hash?: string; - ledger_current_index?: number; - ledger_index?: number; + account: string + obligations?: { [currency: string]: string } + balances?: { [address: string]: Amount[] } + assets?: { [address: string]: Amount[] } + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number } diff --git a/src/common/types/commands/index.ts b/src/common/types/commands/index.ts index 33645cdd..43ac8ffc 100644 --- a/src/common/types/commands/index.ts +++ b/src/common/types/commands/index.ts @@ -1,10 +1,10 @@ -export * from "./account_info"; -export * from "./account_lines"; -export * from "./account_objects"; -export * from "./account_offers"; -export * from "./book_offers"; -export * from "./gateway_balances"; -export * from "./ledger"; -export * from "./ledger_data"; -export * from "./ledger_entry"; -export * from "./server_info"; +export * from './account_info' +export * from './account_lines' +export * from './account_objects' +export * from './account_offers' +export * from './book_offers' +export * from './gateway_balances' +export * from './ledger' +export * from './ledger_data' +export * from './ledger_entry' +export * from './server_info' diff --git a/src/common/types/commands/ledger.ts b/src/common/types/commands/ledger.ts index 4edb00a1..2b3ca41d 100644 --- a/src/common/types/commands/ledger.ts +++ b/src/common/types/commands/ledger.ts @@ -1,20 +1,20 @@ -import { Ledger, QueueData } from "../objects"; +import { Ledger, QueueData } from '../objects' export interface LedgerRequest { - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - full?: boolean; - accounts?: boolean; - transactions?: boolean; - expand?: boolean; - owner_funds?: boolean; - binary?: boolean; - queue?: boolean; + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + full?: boolean + accounts?: boolean + transactions?: boolean + expand?: boolean + owner_funds?: boolean + binary?: boolean + queue?: boolean } export interface LedgerResponse { - ledger_index: number; - ledger_hash: string; - ledger: Ledger; - queue_data?: QueueData; + ledger_index: number + ledger_hash: string + ledger: Ledger + queue_data?: QueueData } diff --git a/src/common/types/commands/ledger_data.ts b/src/common/types/commands/ledger_data.ts index 8c5b8a8e..67b896cd 100644 --- a/src/common/types/commands/ledger_data.ts +++ b/src/common/types/commands/ledger_data.ts @@ -1,12 +1,12 @@ -import { LedgerData } from "../objects"; +import { LedgerData } from '../objects' export interface LedgerDataRequest { - id?: any; - ledger_hash?: string; - ledger_index?: string; - binary?: boolean; - limit?: number; - marker?: string; + id?: any + ledger_hash?: string + ledger_index?: string + binary?: boolean + limit?: number + marker?: string } -export type LedgerDataResponse = LedgerData; +export type LedgerDataResponse = LedgerData diff --git a/src/common/types/commands/ledger_entry.ts b/src/common/types/commands/ledger_entry.ts index 94030c54..8dc3d4fc 100644 --- a/src/common/types/commands/ledger_entry.ts +++ b/src/common/types/commands/ledger_entry.ts @@ -1,36 +1,36 @@ -import { LedgerEntry } from "../objects"; +import { LedgerEntry } from '../objects' export interface LedgerEntryRequest { - ledger_hash?: string; - ledger_index?: number | ("validated" | "closed" | "current"); - index?: string; - account_root?: string; + ledger_hash?: string + ledger_index?: number | ('validated' | 'closed' | 'current') + index?: string + account_root?: string directory?: | string | { - sub_index?: number; - dir_root: string; + sub_index?: number + dir_root: string } | { - sub_index?: number; - owner: string; - }; + sub_index?: number + owner: string + } offer?: | string | { - account: string; - seq: number; - }; + account: string + seq: number + } ripple_state?: { - accounts: [string, string]; - currency: string; - }; - binary?: boolean; + accounts: [string, string] + currency: string + } + binary?: boolean } export interface LedgerEntryResponse { - index: string; - ledger_index: number; - node_binary?: string; - node?: LedgerEntry; + index: string + ledger_index: number + node_binary?: string + node?: LedgerEntry } diff --git a/src/common/types/commands/server_info.ts b/src/common/types/commands/server_info.ts index 4223c0cc..cb4a6e5f 100644 --- a/src/common/types/commands/server_info.ts +++ b/src/common/types/commands/server_info.ts @@ -1,51 +1,51 @@ export interface ServerInfoRequest { - id?: number; + id?: number } export interface ServerInfoResponse { info: { - amendment_blocked?: boolean; - build_version: string; - closed_ledger?: LedgerInfo; - complete_ledgers: string; - hostid: string; - io_latency_ms: number; + amendment_blocked?: boolean + build_version: string + closed_ledger?: LedgerInfo + complete_ledgers: string + hostid: string + io_latency_ms: number last_close: { - converge_time_s: number; - proposers: number; - }; + converge_time_s: number + proposers: number + } load?: { job_types: Array<{ - job_type: string; - per_second: number; - in_progress: number; - }>; - threads: number; - }; - load_factor: number; - load_factor_local?: number; - load_factor_net?: number; - load_factor_cluster?: number; - load_factor_fee_escalation?: number; - load_factor_fee_queue?: number; - load_factor_server?: number; - peers: number; - pubkey_node: string; - pubkey_validator: string; - server_state: string; - state_accounting: any; - uptime: number; - validated_ledger?: LedgerInfo; - validation_quorum: number; - validator_list_expires: string; - }; + job_type: string + per_second: number + in_progress: number + }> + threads: number + } + load_factor: number + load_factor_local?: number + load_factor_net?: number + load_factor_cluster?: number + load_factor_fee_escalation?: number + load_factor_fee_queue?: number + load_factor_server?: number + peers: number + pubkey_node: string + pubkey_validator: string + server_state: string + state_accounting: any + uptime: number + validated_ledger?: LedgerInfo + validation_quorum: number + validator_list_expires: string + } } export interface LedgerInfo { - age: number; - base_fee_xrp: number; - hash: string; - reserve_base_xrp: number; - reserve_inc_xrp: number; - seq: number; + age: number + base_fee_xrp: number + hash: string + reserve_base_xrp: number + reserve_inc_xrp: number + seq: number } diff --git a/src/common/types/objects/adjustments.ts b/src/common/types/objects/adjustments.ts index fd7a115e..1048edc4 100644 --- a/src/common/types/objects/adjustments.ts +++ b/src/common/types/objects/adjustments.ts @@ -1,19 +1,19 @@ -import { Amount } from "./amounts"; +import { Amount } from './amounts' export interface Adjustment { - address: string; - amount: Amount; - tag?: number; + address: string + amount: Amount + tag?: number } export interface MaxAdjustment { - address: string; - maxAmount: Amount; - tag?: number; + address: string + maxAmount: Amount + tag?: number } export interface MinAdjustment { - address: string; - minAmount: Amount; - tag?: number; + address: string + minAmount: Amount + tag?: number } diff --git a/src/common/types/objects/amounts.ts b/src/common/types/objects/amounts.ts index 5cc48355..c7c45481 100644 --- a/src/common/types/objects/amounts.ts +++ b/src/common/types/objects/amounts.ts @@ -1,8 +1,8 @@ export interface Amount extends Issue { - value: string; + value: string } -export type RippledAmount = string | Amount; +export type RippledAmount = string | Amount /** * Specification of which currency the account taking the offer would pay/ @@ -10,15 +10,15 @@ export type RippledAmount = string | Amount; * Similar to currency amounts. */ export interface TakerRequestAmount { - currency: string; - issuer?: string; + currency: string + issuer?: string } /** * A currency-counterparty pair, or just currency if it's XRP. */ export interface Issue { - currency: string; - issuer?: string; - counterparty?: string; + currency: string + issuer?: string + counterparty?: string } diff --git a/src/common/types/objects/index.ts b/src/common/types/objects/index.ts index 6ac25d41..26658a51 100644 --- a/src/common/types/objects/index.ts +++ b/src/common/types/objects/index.ts @@ -1,12 +1,12 @@ -export * from "./adjustments"; -export * from "./amounts"; -export * from "./ledger"; -export * from "./ledger_data"; -export * from "./ledger_entries"; -export * from "./memos"; -export * from "./orders"; -export * from "./queue_data"; -export * from "./settings"; -export * from "./signers"; -export * from "./transactions"; -export * from "./trustlines"; +export * from './adjustments' +export * from './amounts' +export * from './ledger' +export * from './ledger_data' +export * from './ledger_entries' +export * from './memos' +export * from './orders' +export * from './queue_data' +export * from './settings' +export * from './signers' +export * from './transactions' +export * from './trustlines' diff --git a/src/common/types/objects/ledger.ts b/src/common/types/objects/ledger.ts index 68ac06db..183a00cc 100644 --- a/src/common/types/objects/ledger.ts +++ b/src/common/types/objects/ledger.ts @@ -1,31 +1,31 @@ export interface Ledger { - account_hash: string; - close_time: number; - close_time_human: string; - close_time_resolution: number; - closed: boolean; - ledger_hash: string; - ledger_index: string; - parent_hash: string; - total_coins: string; - transaction_hash: string; - transactions: string[] | object[]; - close_flags?: number; - parent_close_time?: number; - accountState?: any[]; - validated?: boolean; + account_hash: string + close_time: number + close_time_human: string + close_time_resolution: number + closed: boolean + ledger_hash: string + ledger_index: string + parent_hash: string + total_coins: string + transaction_hash: string + transactions: string[] | object[] + close_flags?: number + parent_close_time?: number + accountState?: any[] + validated?: boolean } // https://xrpl.org/subscribe.html#ledger-stream export interface LedgerClosedEvent { - type: "ledgerClosed"; - fee_base: number; - fee_ref: number; - ledger_hash: string; - ledger_index: number; - ledger_time: number; - reserve_base: number; - reserve_inc: number; - txn_count: number; - validated_ledgers: string; + type: 'ledgerClosed' + fee_base: number + fee_ref: number + ledger_hash: string + ledger_index: number + ledger_time: number + reserve_base: number + reserve_inc: number + txn_count: number + validated_ledgers: string } diff --git a/src/common/types/objects/ledger_data.ts b/src/common/types/objects/ledger_data.ts index e123ac0b..355b42a4 100644 --- a/src/common/types/objects/ledger_data.ts +++ b/src/common/types/objects/ledger_data.ts @@ -1,8 +1,6 @@ export interface LedgerData { - ledger_index: string; - ledger_hash: string; - marker: string; - state: Array< - { data?: string; LedgerEntryType?: string; index: string } & any - >; + ledger_index: string + ledger_hash: string + marker: string + state: Array<{ data?: string; LedgerEntryType?: string; index: string } & any> } diff --git a/src/common/types/objects/ledger_entries.ts b/src/common/types/objects/ledger_entries.ts index e2661b6a..a1d45621 100644 --- a/src/common/types/objects/ledger_entries.ts +++ b/src/common/types/objects/ledger_entries.ts @@ -1,176 +1,176 @@ -import { Amount, RippledAmount } from "./amounts"; +import { Amount, RippledAmount } from './amounts' -import { SignerEntry } from "./index"; +import { SignerEntry } from './index' export interface AccountRootLedgerEntry { - LedgerEntryType: "AccountRoot"; - Account: string; - Balance: string; - Flags: number; - OwnerCount: number; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - Sequence: number; - AccountTxnID?: string; - Domain?: string; - EmailHash?: string; - MessageKey?: string; - RegularKey?: string; - TickSize?: number; - TransferRate?: number; - WalletLocator?: string; - WalletSize?: number; // DEPRECATED + LedgerEntryType: 'AccountRoot' + Account: string + Balance: string + Flags: number + OwnerCount: number + PreviousTxnID: string + PreviousTxnLgrSeq: number + Sequence: number + AccountTxnID?: string + Domain?: string + EmailHash?: string + MessageKey?: string + RegularKey?: string + TickSize?: number + TransferRate?: number + WalletLocator?: string + WalletSize?: number // DEPRECATED } export interface AmendmentsLedgerEntry { - LedgerEntryType: "Amendments"; - Amendments?: string[]; - Majorities?: any[]; - Flags: 0; + LedgerEntryType: 'Amendments' + Amendments?: string[] + Majorities?: any[] + Flags: 0 } export interface CheckLedgerEntry { - LedgerEntryType: "Check"; - Account: string; - Destination; - string; - Flags: 0; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - SendMax: string | object; - Sequence: number; - DestinationNode: string; - DestinationTag: number; - Expiration: number; - InvoiceID: string; - SourceTag: number; + LedgerEntryType: 'Check' + Account: string + Destination + string + Flags: 0 + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + SendMax: string | object + Sequence: number + DestinationNode: string + DestinationTag: number + Expiration: number + InvoiceID: string + SourceTag: number } export interface DepositPreauthLedgerEntry { - LedgerEntryType: "DepositPreauth"; - Account: string; - Authorize: string; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; + LedgerEntryType: 'DepositPreauth' + Account: string + Authorize: string + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number } export interface DirectoryNodeLedgerEntry { - LedgerEntryType: "DirectoryNode"; - Flags: number; - RootIndex: string; - Indexes: string[]; - IndexNext?: number; - IndexPrevious?: number; + LedgerEntryType: 'DirectoryNode' + Flags: number + RootIndex: string + Indexes: string[] + IndexNext?: number + IndexPrevious?: number } export interface OfferDirectoryNodeLedgerEntry extends DirectoryNodeLedgerEntry { - TakerPaysCurrency: string; - TakerPaysIssuer: string; - TakerGetsCurrency: string; - TakerGetsIssuer: string; - ExchangeRate?: number; // DEPRECATED + TakerPaysCurrency: string + TakerPaysIssuer: string + TakerGetsCurrency: string + TakerGetsIssuer: string + ExchangeRate?: number // DEPRECATED } export interface OwnerDirectoryNodeLedgerEntry extends DirectoryNodeLedgerEntry { - Owner: string; + Owner: string } export interface EscrowLedgerEntry { - LedgerEntryType: "Escrow"; - Account: string; - Destination: string; - Amount: string; - Condition?: string; - CancelAfter?: number; - FinishAfter?: number; - Flags: number; - SourceTag?: number; - DestinationTag?: number; - OwnerNode: string; - DestinationNode?: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; + LedgerEntryType: 'Escrow' + Account: string + Destination: string + Amount: string + Condition?: string + CancelAfter?: number + FinishAfter?: number + Flags: number + SourceTag?: number + DestinationTag?: number + OwnerNode: string + DestinationNode?: string + PreviousTxnID: string + PreviousTxnLgrSeq: number } export interface FeeSettingsLedgerEntry { - LedgerEntryType: "FeeSettings"; - BaseFee: string; - ReferenceFeeUnits: number; - ReserveBase: number; - ReserveIncrement: number; - Flags: number; + LedgerEntryType: 'FeeSettings' + BaseFee: string + ReferenceFeeUnits: number + ReserveBase: number + ReserveIncrement: number + Flags: number } export interface LedgerHashesLedgerEntry { - LedgerEntryType: "LedgerHashes"; - Hashes: string[]; - Flags: number; - FirstLedgerSequence?: number; // DEPRECATED - LastLedgerSequence?: number; + LedgerEntryType: 'LedgerHashes' + Hashes: string[] + Flags: number + FirstLedgerSequence?: number // DEPRECATED + LastLedgerSequence?: number } export interface OfferLedgerEntry { - LedgerEntryType: "Offer"; - Flags: number; - Account: string; - Sequence: number; - TakerPays: RippledAmount; - TakerGets: RippledAmount; - BookDirectory: string; - BookNode: string; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - Expiration?: number; + LedgerEntryType: 'Offer' + Flags: number + Account: string + Sequence: number + TakerPays: RippledAmount + TakerGets: RippledAmount + BookDirectory: string + BookNode: string + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + Expiration?: number } export interface PayChannelLedgerEntry { - LedgerEntryType: "PayChannel"; - Sequence: number; - Account: string; - Amount: string; - Balance: string; - PublicKey: string; - Destination: string; - SettleDelay: number; - Expiration?: number; - CancelAfter?: number; - SourceTag?: number; - DestinationTag?: number; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - index: string; + LedgerEntryType: 'PayChannel' + Sequence: number + Account: string + Amount: string + Balance: string + PublicKey: string + Destination: string + SettleDelay: number + Expiration?: number + CancelAfter?: number + SourceTag?: number + DestinationTag?: number + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + index: string } export interface RippleStateLedgerEntry { - LedgerEntryType: "RippleState"; - Flags: number; - Balance: Amount; - LowLimit: Amount; - HighLimit: Amount; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - LowNode?: string; - HighNode?: string; - LowQualityIn?: number; - LowQualityOut?: number; - HighQualityIn?: number; - HighQualityOut?: number; + LedgerEntryType: 'RippleState' + Flags: number + Balance: Amount + LowLimit: Amount + HighLimit: Amount + PreviousTxnID: string + PreviousTxnLgrSeq: number + LowNode?: string + HighNode?: string + LowQualityIn?: number + LowQualityOut?: number + HighQualityIn?: number + HighQualityOut?: number } export interface SignerListLedgerEntry { - LedgerEntryType: "SignerList"; - OwnerNode: string; - SignerQuorum: number; - SignerEntries: SignerEntry[]; - SignerListID: number; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; + LedgerEntryType: 'SignerList' + OwnerNode: string + SignerQuorum: number + SignerEntries: SignerEntry[] + SignerListID: number + PreviousTxnID: string + PreviousTxnLgrSeq: number } // see https://ripple.com/build/ledger-format/#ledger-object-types @@ -188,4 +188,4 @@ export type LedgerEntry = | OfferLedgerEntry | PayChannelLedgerEntry | RippleStateLedgerEntry - | SignerListLedgerEntry; + | SignerListLedgerEntry diff --git a/src/common/types/objects/memos.ts b/src/common/types/objects/memos.ts index bc181a01..1c5ab81e 100644 --- a/src/common/types/objects/memos.ts +++ b/src/common/types/objects/memos.ts @@ -1,5 +1,5 @@ export interface Memo { - type?: string; - format?: string; - data?: string; + type?: string + format?: string + data?: string } diff --git a/src/common/types/objects/orders.ts b/src/common/types/objects/orders.ts index c8a1bde6..e0d29e46 100644 --- a/src/common/types/objects/orders.ts +++ b/src/common/types/objects/orders.ts @@ -1,17 +1,17 @@ -import { Amount } from "./amounts"; -import { Memo } from "./memos"; +import { Amount } from './amounts' +import { Memo } from './memos' export interface FormattedOrderSpecification { - direction: string; - quantity: Amount; - totalPrice: Amount; - immediateOrCancel?: boolean; - fillOrKill?: boolean; - expirationTime?: string; - orderToReplace?: number; - memos?: Memo[]; + direction: string + quantity: Amount + totalPrice: Amount + immediateOrCancel?: boolean + fillOrKill?: boolean + expirationTime?: string + orderToReplace?: number + memos?: Memo[] // If enabled, the offer will not consume offers that exactly match it, and // instead becomes an Offer node in the ledger. It will still consume offers // that cross it. - passive?: boolean; + passive?: boolean } diff --git a/src/common/types/objects/queue_data.ts b/src/common/types/objects/queue_data.ts index 331dac51..918f05a3 100644 --- a/src/common/types/objects/queue_data.ts +++ b/src/common/types/objects/queue_data.ts @@ -1,16 +1,16 @@ export interface QueueTransaction { - auth_change: boolean; - fee: string; - fee_level: string; - max_spend_drops: string; - seq: number; + auth_change: boolean + fee: string + fee_level: string + max_spend_drops: string + seq: number } export interface QueueData { - txn_count: number; - auth_change_queued?: boolean; - lowest_sequence?: number; - highest_sequence?: number; - max_spend_drops_total?: string; - transactions?: QueueTransaction[]; + txn_count: number + auth_change_queued?: boolean + lowest_sequence?: number + highest_sequence?: number + max_spend_drops_total?: string + transactions?: QueueTransaction[] } diff --git a/src/common/types/objects/settings.ts b/src/common/types/objects/settings.ts index 754257c6..1d896460 100644 --- a/src/common/types/objects/settings.ts +++ b/src/common/types/objects/settings.ts @@ -1,33 +1,33 @@ -import { Memo } from "./memos"; +import { Memo } from './memos' export interface WeightedSigner { - address: string; - weight: number; + address: string + weight: number } export interface Signers { - threshold?: number; - weights: WeightedSigner[]; + threshold?: number + weights: WeightedSigner[] } export interface FormattedSettings { - defaultRipple?: boolean; - depositAuth?: boolean; - disableMasterKey?: boolean; - disallowIncomingXRP?: boolean; - domain?: string; - emailHash?: string | null; - walletLocator?: string | null; - enableTransactionIDTracking?: boolean; - globalFreeze?: boolean; - memos?: Memo[]; - messageKey?: string; - noFreeze?: boolean; - passwordSpent?: boolean; - regularKey?: string; - requireAuthorization?: boolean; - requireDestinationTag?: boolean; - signers?: Signers; - transferRate?: number | null; - tickSize?: number; + defaultRipple?: boolean + depositAuth?: boolean + disableMasterKey?: boolean + disallowIncomingXRP?: boolean + domain?: string + emailHash?: string | null + walletLocator?: string | null + enableTransactionIDTracking?: boolean + globalFreeze?: boolean + memos?: Memo[] + messageKey?: string + noFreeze?: boolean + passwordSpent?: boolean + regularKey?: string + requireAuthorization?: boolean + requireDestinationTag?: boolean + signers?: Signers + transferRate?: number | null + tickSize?: number } diff --git a/src/common/types/objects/signers.ts b/src/common/types/objects/signers.ts index fdf869d5..3c7d85dc 100644 --- a/src/common/types/objects/signers.ts +++ b/src/common/types/objects/signers.ts @@ -1,6 +1,6 @@ export interface SignerEntry { SignerEntry: { - Account: string; - SignerWeight: number; - }; + Account: string + SignerWeight: number + } } diff --git a/src/common/types/objects/transactions.ts b/src/common/types/objects/transactions.ts index 14f1f563..c37b1090 100644 --- a/src/common/types/objects/transactions.ts +++ b/src/common/types/objects/transactions.ts @@ -1,27 +1,27 @@ -import { RippledAmount } from "./amounts"; -import { Memo } from "./memos"; +import { RippledAmount } from './amounts' +import { Memo } from './memos' export interface OfferCreateTransaction { - TransactionType: "OfferCreate"; - Account: string; - AccountTxnID?: string; - Fee: string; - Field: any; - Flags: number; - LastLedgerSequence?: number; - Sequence: number; - Signers: any[]; - SigningPubKey: string; - SourceTag?: number; - TakerGets: RippledAmount; - TakerPays: RippledAmount; - TxnSignature: string; - Expiration?: number; - Memos?: Memo[]; - OfferSequence?: number; + TransactionType: 'OfferCreate' + Account: string + AccountTxnID?: string + Fee: string + Field: any + Flags: number + LastLedgerSequence?: number + Sequence: number + Signers: any[] + SigningPubKey: string + SourceTag?: number + TakerGets: RippledAmount + TakerPays: RippledAmount + TxnSignature: string + Expiration?: number + Memos?: Memo[] + OfferSequence?: number } export interface SignedTransaction { - signedTransaction: string; - id: string; + signedTransaction: string + id: string } diff --git a/src/common/types/objects/trustlines.ts b/src/common/types/objects/trustlines.ts index d813eda0..91ae117a 100644 --- a/src/common/types/objects/trustlines.ts +++ b/src/common/types/objects/trustlines.ts @@ -1,42 +1,42 @@ -import { Memo } from "./memos"; +import { Memo } from './memos' export interface Trustline { - account: string; - balance: string; - currency: string; - limit: string; - limit_peer: string; - quality_in: number; - quality_out: number; - no_ripple?: boolean; - no_ripple_peer?: boolean; - freeze?: boolean; - freeze_peer?: boolean; - authorized?: boolean; - peer_authorized?: boolean; + account: string + balance: string + currency: string + limit: string + limit_peer: string + quality_in: number + quality_out: number + no_ripple?: boolean + no_ripple_peer?: boolean + freeze?: boolean + freeze_peer?: boolean + authorized?: boolean + peer_authorized?: boolean } export interface FormattedTrustlineSpecification { - currency: string; - counterparty: string; - limit: string; - qualityIn?: number; - qualityOut?: number; - ripplingDisabled?: boolean; - authorized?: boolean; - frozen?: boolean; - memos?: Memo[]; + currency: string + counterparty: string + limit: string + qualityIn?: number + qualityOut?: number + ripplingDisabled?: boolean + authorized?: boolean + frozen?: boolean + memos?: Memo[] } export interface FormattedTrustline { - specification: FormattedTrustlineSpecification; + specification: FormattedTrustlineSpecification counterparty: { - limit: string; - ripplingDisabled?: boolean; - frozen?: boolean; - authorized?: boolean; - }; + limit: string + ripplingDisabled?: boolean + frozen?: boolean + authorized?: boolean + } state: { - balance: string; - }; + balance: string + } } diff --git a/src/index.ts b/src/index.ts index c34a60d8..2e40b6e9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,16 +1,16 @@ // Broadcast client is experimental -import BroadcastClient from "./client/broadcastClient"; +import BroadcastClient from './client/broadcastClient' -export { Client } from "./client"; +export { Client } from './client' -export * from "./transaction/types"; +export * from './transaction/types' -export * from "./common/types/objects/ledger"; +export * from './common/types/objects/ledger' -export * from "./models/methods"; +export * from './models/methods' -export * from "./utils"; +export * from './utils' -export { BroadcastClient }; +export { BroadcastClient } -export { default as Wallet } from "./wallet"; +export { default as Wallet } from './wallet' diff --git a/src/ledger/balances.ts b/src/ledger/balances.ts index b4c27670..af3a1d6f 100644 --- a/src/ledger/balances.ts +++ b/src/ledger/balances.ts @@ -1,82 +1,83 @@ -import type { Client } from ".."; -import { ensureClassicAddress } from "../common"; -import { FormattedTrustline } from "../common/types/objects/trustlines"; +import type { Client } from '..' +import { ensureClassicAddress } from '../common' +import { FormattedTrustline } from '../common/types/objects/trustlines' -import { GetTrustlinesOptions } from "./trustlines"; -import * as utils from "./utils"; +import { GetTrustlinesOptions } from './trustlines' +import * as utils from './utils' export interface Balance { - value: string; - currency: string; - counterparty?: string; + value: string + currency: string + counterparty?: string } -export type GetBalances = Balance[]; +export type GetBalances = Balance[] function getTrustlineBalanceAmount(trustline: FormattedTrustline): Balance { return { currency: trustline.specification.currency, counterparty: trustline.specification.counterparty, value: trustline.state.balance, - }; + } } function formatBalances( options: GetTrustlinesOptions, - balances: { xrp: string; trustlines: FormattedTrustline[] } + balances: { xrp: string; trustlines: FormattedTrustline[] }, ) { - const result = balances.trustlines.map(getTrustlineBalanceAmount); + const result = balances.trustlines.map(getTrustlineBalanceAmount) if ( - !(options.counterparty || (options.currency && options.currency !== "XRP")) + !(options.counterparty || (options.currency && options.currency !== 'XRP')) ) { const xrpBalance = { - currency: "XRP", + currency: 'XRP', value: balances.xrp, - }; - result.unshift(xrpBalance); + } + result.unshift(xrpBalance) } if (options.limit && result.length > options.limit) { - const toRemove = result.length - options.limit; - result.splice(-toRemove, toRemove); + const toRemove = result.length - options.limit + result.splice(-toRemove, toRemove) } - return result; + return result } async function getLedgerVersionHelper( client: Client, - optionValue?: number + optionValue?: number, ): Promise { if (optionValue != null && optionValue !== null) { - return Promise.resolve(optionValue); + return Promise.resolve(optionValue) } return client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) - .then((response) => response.result.ledger_index); + .then((response) => response.result.ledger_index) } async function getBalances( this: Client, address: string, - options: GetTrustlinesOptions = {} + options: GetTrustlinesOptions = {}, ): Promise { // Only support retrieving balances without a tag, // since we currently do not calculate balances // on a per-tag basis. Apps must interpret and // use tags independent of the XRP Ledger, comparing // with the XRP Ledger's balance as an accounting check. - address = ensureClassicAddress(address); + address = ensureClassicAddress(address) return Promise.all([ getLedgerVersionHelper(this, options.ledgerVersion).then( - async (ledgerVersion) => utils.getXRPBalance(this, address, ledgerVersion) + async (ledgerVersion) => + utils.getXRPBalance(this, address, ledgerVersion), ), this.getTrustlines(address, options), ]).then((results) => - formatBalances(options, { xrp: results[0], trustlines: results[1] }) - ); + formatBalances(options, { xrp: results[0], trustlines: results[1] }), + ) } -export default getBalances; +export default getBalances diff --git a/src/ledger/orderbook.ts b/src/ledger/orderbook.ts index 7a805a04..d872393d 100644 --- a/src/ledger/orderbook.ts +++ b/src/ledger/orderbook.ts @@ -1,51 +1,51 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' -import type { Client } from "../client"; -import type { BookOffer } from "../common/types/commands"; -import type { Issue } from "../common/types/objects"; +import type { Client } from '../client' +import type { BookOffer } from '../common/types/commands' +import type { Issue } from '../common/types/objects' import { parseOrderbookOrder, FormattedOrderbookOrder, -} from "./parse/orderbook-order"; -import * as utils from "./utils"; +} from './parse/orderbook-order' +import * as utils from './utils' export interface FormattedOrderbook { - bids: FormattedOrderbookOrder[]; - asks: FormattedOrderbookOrder[]; + bids: FormattedOrderbookOrder[] + asks: FormattedOrderbookOrder[] } function isSameIssue(a: Issue, b: Issue) { - return a.currency === b.currency && a.counterparty === b.counterparty; + return a.currency === b.currency && a.counterparty === b.counterparty } function directionFilter(direction: string, order: FormattedOrderbookOrder) { - return order.specification.direction === direction; + return order.specification.direction === direction } function flipOrder(order: FormattedOrderbookOrder) { - const specification = order.specification; + const specification = order.specification const flippedSpecification = { quantity: specification.totalPrice, totalPrice: specification.quantity, - direction: specification.direction === "buy" ? "sell" : "buy", - }; - const newSpecification = _.merge({}, specification, flippedSpecification); - return _.merge({}, order, { specification: newSpecification }); + direction: specification.direction === 'buy' ? 'sell' : 'buy', + } + const newSpecification = _.merge({}, specification, flippedSpecification) + return _.merge({}, order, { specification: newSpecification }) } function alignOrder( base: Issue, - order: FormattedOrderbookOrder + order: FormattedOrderbookOrder, ): FormattedOrderbookOrder { - const quantity = order.specification.quantity; - return isSameIssue(quantity, base) ? order : flipOrder(order); + const quantity = order.specification.quantity + return isSameIssue(quantity, base) ? order : flipOrder(order) } export function formatBidsAndAsks( orderbook: OrderbookInfo, - offers: BookOffer[] + offers: BookOffer[], ) { // the "base" currency is the currency that you are buying or selling // the "counter" is the currency that the "base" is priced in @@ -59,17 +59,17 @@ export function formatBidsAndAsks( // we sort the orders so that earlier orders are closer to mid-market const orders = offers .sort((a, b) => { - const qualityA = a.quality ?? 0; - const qualityB = b.quality ?? 0; + const qualityA = a.quality ?? 0 + const qualityB = b.quality ?? 0 - return new BigNumber(qualityA).comparedTo(qualityB); + return new BigNumber(qualityA).comparedTo(qualityB) }) - .map(parseOrderbookOrder); + .map(parseOrderbookOrder) - const alignedOrders = orders.map(_.partial(alignOrder, orderbook.base)); - const bids = alignedOrders.filter(_.partial(directionFilter, "buy")); - const asks = alignedOrders.filter(_.partial(directionFilter, "sell")); - return { bids, asks }; + const alignedOrders = orders.map(_.partial(alignOrder, orderbook.base)) + const bids = alignedOrders.filter(_.partial(directionFilter, 'buy')) + const asks = alignedOrders.filter(_.partial(directionFilter, 'sell')) + return { bids, asks } } // account is to specify a "perspective", which affects which unfunded offers @@ -79,51 +79,51 @@ async function makeRequest( taker: string, options: GetOrderbookOptions, takerGets: Issue, - takerPays: Issue + takerPays: Issue, ) { const orderData = utils.renameCounterpartyToIssuerInOrder({ taker_gets: takerGets, taker_pays: takerPays, - }); + }) return client.requestAll({ - command: "book_offers", + command: 'book_offers', taker_gets: orderData.taker_gets, taker_pays: orderData.taker_pays, - ledger_index: options.ledgerVersion || "validated", + ledger_index: options.ledgerVersion || 'validated', limit: options.limit, taker, - }); + }) } export interface GetOrderbookOptions { - limit?: number; - ledgerVersion?: number; + limit?: number + ledgerVersion?: number } export interface OrderbookInfo { - base: Issue; - counter: Issue; + base: Issue + counter: Issue } export async function getOrderbook( this: Client, address: string, orderbook: OrderbookInfo, - options: GetOrderbookOptions = {} + options: GetOrderbookOptions = {}, ): Promise { // 2. Make Request const [directOfferResults, reverseOfferResults] = await Promise.all([ makeRequest(this, address, options, orderbook.base, orderbook.counter), makeRequest(this, address, options, orderbook.counter, orderbook.base), - ]); + ]) // 3. Return Formatted Response const directOffers = _.flatMap( directOfferResults, - (directOfferResult) => directOfferResult.result.offers - ); + (directOfferResult) => directOfferResult.result.offers, + ) const reverseOffers = _.flatMap( reverseOfferResults, - (reverseOfferResult) => reverseOfferResult.result.offers - ); - return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers]); + (reverseOfferResult) => reverseOfferResult.result.offers, + ) + return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers]) } diff --git a/src/ledger/parse/account-delete.ts b/src/ledger/parse/account-delete.ts index 17625ab4..3f428f00 100644 --- a/src/ledger/parse/account-delete.ts +++ b/src/ledger/parse/account-delete.ts @@ -1,28 +1,28 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { classicAddressToXAddress } from "ripple-address-codec"; +import { classicAddressToXAddress } from 'ripple-address-codec' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' export interface FormattedAccountDelete { // account (address) of an account to receive any leftover XRP after deleting the sending account. // Must be a funded account in the ledger, and must not be the sending account. - destination: string; + destination: string // (Optional) Arbitrary destination tag that identifies a hosted recipient or other information // for the recipient of the deleted account's leftover XRP. NB: Ensure that the hosted recipient is // able to account for AccountDelete transactions; if not, your balance may not be properly credited. - destinationTag?: number; + destinationTag?: number // X-address of an account to receive any leftover XRP after deleting the sending account. // Must be a funded account in the ledger, and must not be the sending account. - destinationXAddress: string; + destinationXAddress: string } function parseAccountDelete(tx: any): FormattedAccountDelete { - assert.ok(tx.TransactionType === "AccountDelete"); + assert.ok(tx.TransactionType === 'AccountDelete') return removeUndefined({ memos: parseMemos(tx), @@ -31,9 +31,9 @@ function parseAccountDelete(tx: any): FormattedAccountDelete { destinationXAddress: classicAddressToXAddress( tx.Destination, tx.DestinationTag == null ? false : tx.DestinationTag, - false + false, ), - }); + }) } -export default parseAccountDelete; +export default parseAccountDelete diff --git a/src/ledger/parse/account-order.ts b/src/ledger/parse/account-order.ts index 315c3343..8d18f1cf 100644 --- a/src/ledger/parse/account-order.ts +++ b/src/ledger/parse/account-order.ts @@ -1,38 +1,38 @@ -import BigNumber from "bignumber.js"; +import BigNumber from 'bignumber.js' -import { FormattedOrderSpecification } from "../../common/types/objects"; -import { removeUndefined } from "../../utils"; +import { FormattedOrderSpecification } from '../../common/types/objects' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { orderFlags } from "./flags"; -import { parseTimestamp, adjustQualityForXRP } from "./utils"; +import parseAmount from './amount' +import { orderFlags } from './flags' +import { parseTimestamp, adjustQualityForXRP } from './utils' export interface FormattedAccountOrder { - specification: FormattedOrderSpecification; + specification: FormattedOrderSpecification properties: { - maker: string; - sequence: number; - makerExchangeRate: string; - }; + maker: string + sequence: number + makerExchangeRate: string + } } // TODO: remove this function once rippled provides quality directly function computeQuality(takerGets, takerPays) { - const quotient = new BigNumber(takerPays.value).dividedBy(takerGets.value); - return quotient.precision(16, BigNumber.ROUND_HALF_UP).toString(); + const quotient = new BigNumber(takerPays.value).dividedBy(takerGets.value) + return quotient.precision(16, BigNumber.ROUND_HALF_UP).toString() } // rippled 'account_offers' returns a different format for orders than 'tx' // the flags are also different export function parseAccountOrder( address: string, - order: any + order: any, ): FormattedAccountOrder { - const direction = (order.flags & orderFlags.Sell) === 0 ? "buy" : "sell"; - const takerGetsAmount = parseAmount(order.taker_gets); - const takerPaysAmount = parseAmount(order.taker_pays); - const quantity = direction === "buy" ? takerPaysAmount : takerGetsAmount; - const totalPrice = direction === "buy" ? takerGetsAmount : takerPaysAmount; + const direction = (order.flags & orderFlags.Sell) === 0 ? 'buy' : 'sell' + const takerGetsAmount = parseAmount(order.taker_gets) + const takerPaysAmount = parseAmount(order.taker_pays) + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount // note: immediateOrCancel and fillOrKill orders cannot enter the order book // so we can omit those flags here @@ -43,20 +43,20 @@ export function parseAccountOrder( passive: (order.flags & orderFlags.Passive) !== 0 || undefined, // rippled currently does not provide "expiration" in account_offers expirationTime: parseTimestamp(order.expiration), - }); + }) const makerExchangeRate = order.quality ? adjustQualityForXRP( order.quality.toString(), takerGetsAmount.currency, - takerPaysAmount.currency + takerPaysAmount.currency, ) - : computeQuality(takerGetsAmount, takerPaysAmount); + : computeQuality(takerGetsAmount, takerPaysAmount) const properties = { maker: address, sequence: order.seq, makerExchangeRate, - }; + } - return { specification, properties }; + return { specification, properties } } diff --git a/src/ledger/parse/account-trustline.ts b/src/ledger/parse/account-trustline.ts index cc034ad4..7534f842 100644 --- a/src/ledger/parse/account-trustline.ts +++ b/src/ledger/parse/account-trustline.ts @@ -1,10 +1,10 @@ import { Trustline, FormattedTrustline, -} from "../../common/types/objects/trustlines"; -import { removeUndefined } from "../../utils"; +} from '../../common/types/objects/trustlines' +import { removeUndefined } from '../../utils' -import { parseQuality } from "./utils"; +import { parseQuality } from './utils' // rippled 'account_lines' returns a different format for // trustlines than 'tx' @@ -18,18 +18,18 @@ function parseAccountTrustline(trustline: Trustline): FormattedTrustline { ripplingDisabled: trustline.no_ripple, frozen: trustline.freeze, authorized: trustline.authorized, - }); + }) // rippled doesn't provide the counterparty's qualities const counterparty = removeUndefined({ limit: trustline.limit_peer, ripplingDisabled: trustline.no_ripple_peer, frozen: trustline.freeze_peer, authorized: trustline.peer_authorized, - }); + }) const state = { balance: trustline.balance, - }; - return { specification, counterparty, state }; + } + return { specification, counterparty, state } } -export default parseAccountTrustline; +export default parseAccountTrustline diff --git a/src/ledger/parse/amendment.ts b/src/ledger/parse/amendment.ts index 01c22f74..c9834688 100644 --- a/src/ledger/parse/amendment.ts +++ b/src/ledger/parse/amendment.ts @@ -1,7 +1,7 @@ function parseAmendment(tx: any) { return { amendment: tx.Amendment, - }; + } } -export default parseAmendment; +export default parseAmendment diff --git a/src/ledger/parse/amount.ts b/src/ledger/parse/amount.ts index 91f853d3..ed973f25 100644 --- a/src/ledger/parse/amount.ts +++ b/src/ledger/parse/amount.ts @@ -1,18 +1,18 @@ -import { Amount, RippledAmount } from "../../common/types/objects"; -import { dropsToXrp } from "../../utils"; +import { Amount, RippledAmount } from '../../common/types/objects' +import { dropsToXrp } from '../../utils' function parseAmount(amount: RippledAmount): Amount { - if (typeof amount === "string") { + if (typeof amount === 'string') { return { - currency: "XRP", + currency: 'XRP', value: dropsToXrp(amount), - }; + } } return { currency: amount.currency, value: amount.value, counterparty: amount.issuer, - }; + } } -export default parseAmount; +export default parseAmount diff --git a/src/ledger/parse/cancellation.ts b/src/ledger/parse/cancellation.ts index f94238ea..05630031 100644 --- a/src/ledger/parse/cancellation.ts +++ b/src/ledger/parse/cancellation.ts @@ -1,13 +1,13 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' function parseOrderCancellation(tx: any): object { - assert.ok(tx.TransactionType === "OfferCancel"); + assert.ok(tx.TransactionType === 'OfferCancel') return { memos: parseMemos(tx), orderSequence: tx.OfferSequence, - }; + } } -export default parseOrderCancellation; +export default parseOrderCancellation diff --git a/src/ledger/parse/check-cancel.ts b/src/ledger/parse/check-cancel.ts index 3f357fb4..c6519c14 100644 --- a/src/ledger/parse/check-cancel.ts +++ b/src/ledger/parse/check-cancel.ts @@ -1,21 +1,21 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' export interface FormattedCheckCancel { // ID of the Check ledger object to cancel. - checkID: string; + checkID: string } function parseCheckCancel(tx: any): FormattedCheckCancel { - assert.ok(tx.TransactionType === "CheckCancel"); + assert.ok(tx.TransactionType === 'CheckCancel') return removeUndefined({ memos: parseMemos(tx), checkID: tx.CheckID, - }); + }) } -export default parseCheckCancel; +export default parseCheckCancel diff --git a/src/ledger/parse/check-cash.ts b/src/ledger/parse/check-cash.ts index 43da3823..27f18d4e 100644 --- a/src/ledger/parse/check-cash.ts +++ b/src/ledger/parse/check-cash.ts @@ -1,38 +1,38 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { Amount } from "../../common/types/objects"; -import { removeUndefined } from "../../utils"; +import { Amount } from '../../common/types/objects' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseMemos } from './utils' export interface FormattedCheckCash { // ID of the Check ledger object to cash. - checkID: string; + checkID: string // (Optional) redeem the Check for exactly this amount, if possible. // The currency must match that of the `SendMax` of the corresponding // `CheckCreate` transaction. - amount: Amount; + amount: Amount // (Optional) redeem the Check for at least this amount and // for as much as possible. // The currency must match that of the `SendMax` of the corresponding // `CheckCreate` transaction. - deliverMin: Amount; + deliverMin: Amount // *must* include either Amount or DeliverMin, but not both. } function parseCheckCash(tx: any): FormattedCheckCash { - assert.ok(tx.TransactionType === "CheckCash"); + assert.ok(tx.TransactionType === 'CheckCash') return removeUndefined({ memos: parseMemos(tx), checkID: tx.CheckID, amount: tx.Amount && parseAmount(tx.Amount), deliverMin: tx.DeliverMin && parseAmount(tx.DeliverMin), - }); + }) } -export default parseCheckCash; +export default parseCheckCash diff --git a/src/ledger/parse/check-create.ts b/src/ledger/parse/check-create.ts index e7cc606c..6fa164d6 100644 --- a/src/ledger/parse/check-create.ts +++ b/src/ledger/parse/check-create.ts @@ -1,31 +1,31 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { Amount } from "../../common/types/objects"; -import { removeUndefined } from "../../utils"; +import { Amount } from '../../common/types/objects' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseTimestamp, parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseTimestamp, parseMemos } from './utils' export interface FormattedCheckCreate { // account that can cash the check. - destination: string; + destination: string // amount the check is allowed to debit the sender, // including transfer fees on non-XRP currencies. - sendMax: Amount; + sendMax: Amount // (Optional) identifies the reason for the check, or a hosted recipient. - destinationTag?: string; + destinationTag?: string // (Optional) time in seconds since the Ripple Epoch. - expiration?: string; + expiration?: string // (Optional) 256-bit hash representing a specific reason or identifier. - invoiceID?: string; + invoiceID?: string } function parseCheckCreate(tx: any): FormattedCheckCreate { - assert.ok(tx.TransactionType === "CheckCreate"); + assert.ok(tx.TransactionType === 'CheckCreate') return removeUndefined({ memos: parseMemos(tx), @@ -34,7 +34,7 @@ function parseCheckCreate(tx: any): FormattedCheckCreate { destinationTag: tx.DestinationTag, expiration: tx.Expiration && parseTimestamp(tx.Expiration), invoiceID: tx.InvoiceID, - }); + }) } -export default parseCheckCreate; +export default parseCheckCreate diff --git a/src/ledger/parse/deposit-preauth.ts b/src/ledger/parse/deposit-preauth.ts index 680b26c8..4a6f0408 100644 --- a/src/ledger/parse/deposit-preauth.ts +++ b/src/ledger/parse/deposit-preauth.ts @@ -1,25 +1,25 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' export interface FormattedDepositPreauth { // account (address) of the sender to preauthorize - authorize: string; + authorize: string // account (address) of the sender whose preauthorization should be revoked - unauthorize: string; + unauthorize: string } function parseDepositPreauth(tx: any): FormattedDepositPreauth { - assert.ok(tx.TransactionType === "DepositPreauth"); + assert.ok(tx.TransactionType === 'DepositPreauth') return removeUndefined({ memos: parseMemos(tx), authorize: tx.Authorize, unauthorize: tx.Unauthorize, - }); + }) } -export default parseDepositPreauth; +export default parseDepositPreauth diff --git a/src/ledger/parse/escrow-cancellation.ts b/src/ledger/parse/escrow-cancellation.ts index c21a15ae..2003898a 100644 --- a/src/ledger/parse/escrow-cancellation.ts +++ b/src/ledger/parse/escrow-cancellation.ts @@ -1,17 +1,17 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' function parseEscrowCancellation(tx: any): object { - assert.ok(tx.TransactionType === "EscrowCancel"); + assert.ok(tx.TransactionType === 'EscrowCancel') return removeUndefined({ memos: parseMemos(tx), owner: tx.Owner, escrowSequence: tx.OfferSequence, - }); + }) } -export default parseEscrowCancellation; +export default parseEscrowCancellation diff --git a/src/ledger/parse/escrow-creation.ts b/src/ledger/parse/escrow-creation.ts index f1cb839a..abf7b7e3 100644 --- a/src/ledger/parse/escrow-creation.ts +++ b/src/ledger/parse/escrow-creation.ts @@ -1,12 +1,12 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseTimestamp, parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseTimestamp, parseMemos } from './utils' function parseEscrowCreation(tx: any): object { - assert.ok(tx.TransactionType === "EscrowCreate"); + assert.ok(tx.TransactionType === 'EscrowCreate') return removeUndefined({ amount: parseAmount(tx.Amount).value, @@ -17,7 +17,7 @@ function parseEscrowCreation(tx: any): object { allowExecuteAfter: parseTimestamp(tx.FinishAfter), sourceTag: tx.SourceTag, destinationTag: tx.DestinationTag, - }); + }) } -export default parseEscrowCreation; +export default parseEscrowCreation diff --git a/src/ledger/parse/escrow-execution.ts b/src/ledger/parse/escrow-execution.ts index fedecdb9..33ba4c35 100644 --- a/src/ledger/parse/escrow-execution.ts +++ b/src/ledger/parse/escrow-execution.ts @@ -1,11 +1,11 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' function parseEscrowExecution(tx: any): object { - assert.ok(tx.TransactionType === "EscrowFinish"); + assert.ok(tx.TransactionType === 'EscrowFinish') return removeUndefined({ memos: parseMemos(tx), @@ -13,7 +13,7 @@ function parseEscrowExecution(tx: any): object { escrowSequence: tx.OfferSequence, condition: tx.Condition, fulfillment: tx.Fulfillment, - }); + }) } -export default parseEscrowExecution; +export default parseEscrowExecution diff --git a/src/ledger/parse/fee-update.ts b/src/ledger/parse/fee-update.ts index 88937729..b70853a8 100644 --- a/src/ledger/parse/fee-update.ts +++ b/src/ledger/parse/fee-update.ts @@ -1,18 +1,18 @@ -import BigNumber from "bignumber.js"; +import BigNumber from 'bignumber.js' -import { dropsToXrp } from "../../utils"; +import { dropsToXrp } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' function parseFeeUpdate(tx: any) { - const baseFeeDrops = new BigNumber(tx.BaseFee, 16).toString(); + const baseFeeDrops = new BigNumber(tx.BaseFee, 16).toString() return { memos: parseMemos(tx), baseFeeXRP: dropsToXrp(baseFeeDrops), referenceFeeUnits: tx.ReferenceFeeUnits, reserveBaseXRP: dropsToXrp(tx.ReserveBase), reserveIncrementXRP: dropsToXrp(tx.ReserveIncrement), - }; + } } -export default parseFeeUpdate; +export default parseFeeUpdate diff --git a/src/ledger/parse/fields.ts b/src/ledger/parse/fields.ts index cf01c8b1..75c82af0 100644 --- a/src/ledger/parse/fields.ts +++ b/src/ledger/parse/fields.ts @@ -1,41 +1,41 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' -import { constants } from "../../common"; +import { constants } from '../../common' -const AccountFields = constants.AccountFields; +const AccountFields = constants.AccountFields function parseField(info, value) { - if (info.encoding === "hex" && !info.length) { + if (info.encoding === 'hex' && !info.length) { // e.g. "domain" - return Buffer.from(value, "hex").toString("ascii"); + return Buffer.from(value, 'hex').toString('ascii') } if (info.shift) { - return new BigNumber(value).shiftedBy(-info.shift).toNumber(); + return new BigNumber(value).shiftedBy(-info.shift).toNumber() } - return value; + return value } function parseFields(data: any): object { - const settings: any = {}; + const settings: any = {} for (const fieldName in AccountFields) { - const fieldValue = data[fieldName]; + const fieldValue = data[fieldName] if (fieldValue != null) { - const info = AccountFields[fieldName]; - settings[info.name] = parseField(info, fieldValue); + const info = AccountFields[fieldName] + settings[info.name] = parseField(info, fieldValue) } } if (data.RegularKey) { - settings.regularKey = data.RegularKey; + settings.regularKey = data.RegularKey } // Since an account can own at most one SignerList, // this array must have exactly one member if it is present. if (data.signer_lists && data.signer_lists.length === 1) { - settings.signers = {}; + settings.signers = {} if (data.signer_lists[0].SignerQuorum) { - settings.signers.threshold = data.signer_lists[0].SignerQuorum; + settings.signers.threshold = data.signer_lists[0].SignerQuorum } if (data.signer_lists[0].SignerEntries) { settings.signers.weights = data.signer_lists[0].SignerEntries.map( @@ -43,12 +43,12 @@ function parseFields(data: any): object { return { address: entry.SignerEntry.Account, weight: entry.SignerEntry.SignerWeight, - }; - } - ); + } + }, + ) } } - return settings; + return settings } -export default parseFields; +export default parseFields diff --git a/src/ledger/parse/flags.ts b/src/ledger/parse/flags.ts index ed9a14f3..ba1f1634 100644 --- a/src/ledger/parse/flags.ts +++ b/src/ledger/parse/flags.ts @@ -1,7 +1,7 @@ const orderFlags = { Passive: 0x00010000, Sell: 0x00020000, // offer was placed as a sell -}; +} const trustlineFlags = { LowReserve: 0x00010000, // entry counts toward reserve @@ -12,6 +12,6 @@ const trustlineFlags = { HighNoRipple: 0x00200000, LowFreeze: 0x00400000, HighFreeze: 0x00800000, -}; +} -export { orderFlags, trustlineFlags }; +export { orderFlags, trustlineFlags } diff --git a/src/ledger/parse/ledger.ts b/src/ledger/parse/ledger.ts index 3218510f..d4e949de 100644 --- a/src/ledger/parse/ledger.ts +++ b/src/ledger/parse/ledger.ts @@ -1,71 +1,71 @@ -import _ from "lodash"; +import _ from 'lodash' -import { TransactionAndMetadata } from "../../models/transactions"; -import { removeUndefined, rippleTimeToISOTime } from "../../utils"; +import { TransactionAndMetadata } from '../../models/transactions' +import { removeUndefined, rippleTimeToISOTime } from '../../utils' -import parseTransaction from "./transaction"; +import parseTransaction from './transaction' export interface FormattedLedger { // TODO: properties in type don't match response object. Fix! // closed: boolean, - stateHash: string; - closeTime: string; - closeTimeResolution: number; - closeFlags: number; - ledgerHash: string; - ledgerVersion: number; - parentLedgerHash: string; - parentCloseTime: string; - totalDrops: string; - transactionHash: string; - transactions?: object[]; - transactionHashes?: string[]; - rawState?: string; - stateHashes?: string[]; + stateHash: string + closeTime: string + closeTimeResolution: number + closeFlags: number + ledgerHash: string + ledgerVersion: number + parentLedgerHash: string + parentCloseTime: string + totalDrops: string + transactionHash: string + transactions?: object[] + transactionHashes?: string[] + rawState?: string + stateHashes?: string[] } function parseTransactionWrapper( ledgerVersion: number, - tx: TransactionAndMetadata + tx: TransactionAndMetadata, ) { // renames metaData to meta and adds ledger_index const transaction = { - ..._.omit(tx, "metadata"), + ..._.omit(tx, 'metadata'), meta: tx.metadata, ledger_index: ledgerVersion, - }; - const result = parseTransaction(transaction, true); - if (!result.outcome.ledgerVersion) { - result.outcome.ledgerVersion = ledgerVersion; } - return result; + const result = parseTransaction(transaction, true) + if (!result.outcome.ledgerVersion) { + result.outcome.ledgerVersion = ledgerVersion + } + return result } function parseTransactions( transactions: string[] | TransactionAndMetadata[], - ledgerVersion: number + ledgerVersion: number, ) { if (_.isEmpty(transactions)) { - return {}; + return {} } - if (typeof transactions[0] === "string") { - return { transactionHashes: transactions as unknown as string[] }; + if (typeof transactions[0] === 'string') { + return { transactionHashes: transactions as unknown as string[] } } return { transactions: (transactions as unknown as TransactionAndMetadata[]).map( - _.partial(parseTransactionWrapper, ledgerVersion) + _.partial(parseTransactionWrapper, ledgerVersion), ), - }; + } } function parseState(state) { if (_.isEmpty(state)) { - return {}; + return {} } - if (typeof state[0] === "string") { - return { stateHashes: state }; + if (typeof state[0] === 'string') { + return { stateHashes: state } } - return { rawState: JSON.stringify(state) }; + return { rawState: JSON.stringify(state) } } /** @@ -74,7 +74,7 @@ function parseState(state) { * @throws RangeError: Invalid time value (rippleTimeToISOTime). */ export function parseLedger(ledger): FormattedLedger { - const ledgerVersion = parseInt(ledger.ledger_index, 10); + const ledgerVersion = parseInt(ledger.ledger_index, 10) return removeUndefined({ stateHash: ledger.account_hash, closeTime: rippleTimeToISOTime(ledger.close_time), @@ -88,5 +88,5 @@ export function parseLedger(ledger): FormattedLedger { transactionHash: ledger.transaction_hash, ...parseTransactions(ledger.transactions, ledgerVersion), ...parseState(ledger.accountState), - }); + }) } diff --git a/src/ledger/parse/order.ts b/src/ledger/parse/order.ts index 1f5e29c6..b468f101 100644 --- a/src/ledger/parse/order.ts +++ b/src/ledger/parse/order.ts @@ -1,25 +1,25 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { txFlags } from "../../common"; +import { txFlags } from '../../common' import { FormattedOrderSpecification, OfferCreateTransaction, -} from "../../common/types/objects/index"; -import { removeUndefined } from "../../utils"; +} from '../../common/types/objects/index' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseTimestamp, parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseTimestamp, parseMemos } from './utils' -const flags = txFlags.OfferCreate; +const flags = txFlags.OfferCreate function parseOrder(tx: OfferCreateTransaction): FormattedOrderSpecification { - assert.ok(tx.TransactionType === "OfferCreate"); + assert.ok(tx.TransactionType === 'OfferCreate') - const direction = (tx.Flags & flags.Sell) === 0 ? "buy" : "sell"; - const takerGetsAmount = parseAmount(tx.TakerGets); - const takerPaysAmount = parseAmount(tx.TakerPays); - const quantity = direction === "buy" ? takerPaysAmount : takerGetsAmount; - const totalPrice = direction === "buy" ? takerGetsAmount : takerPaysAmount; + const direction = (tx.Flags & flags.Sell) === 0 ? 'buy' : 'sell' + const takerGetsAmount = parseAmount(tx.TakerGets) + const takerPaysAmount = parseAmount(tx.TakerPays) + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount return removeUndefined({ memos: parseMemos(tx), @@ -30,7 +30,7 @@ function parseOrder(tx: OfferCreateTransaction): FormattedOrderSpecification { immediateOrCancel: (tx.Flags & flags.ImmediateOrCancel) !== 0 || undefined, fillOrKill: (tx.Flags & flags.FillOrKill) !== 0 || undefined, expirationTime: parseTimestamp(tx.Expiration), - }); + }) } -export default parseOrder; +export default parseOrder diff --git a/src/ledger/parse/orderbook-order.ts b/src/ledger/parse/orderbook-order.ts index 15a1b078..9a173643 100644 --- a/src/ledger/parse/orderbook-order.ts +++ b/src/ledger/parse/orderbook-order.ts @@ -1,36 +1,33 @@ -import _ from "lodash"; +import _ from 'lodash' -import { BookOffer } from "../../common/types/commands"; -import { - Amount, - FormattedOrderSpecification, -} from "../../common/types/objects"; -import { removeUndefined } from "../../utils"; +import { BookOffer } from '../../common/types/commands' +import { Amount, FormattedOrderSpecification } from '../../common/types/objects' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { orderFlags } from "./flags"; -import { parseTimestamp, adjustQualityForXRP } from "./utils"; +import parseAmount from './amount' +import { orderFlags } from './flags' +import { parseTimestamp, adjustQualityForXRP } from './utils' export interface FormattedOrderbookOrder { - specification: FormattedOrderSpecification; + specification: FormattedOrderSpecification properties: { - maker: string; - sequence: number; - makerExchangeRate: string; - }; + maker: string + sequence: number + makerExchangeRate: string + } state?: { - fundedAmount: Amount; - priceOfFundedAmount: Amount; - }; - data: BookOffer; + fundedAmount: Amount + priceOfFundedAmount: Amount + } + data: BookOffer } export function parseOrderbookOrder(data: BookOffer): FormattedOrderbookOrder { - const direction = (data.Flags & orderFlags.Sell) === 0 ? "buy" : "sell"; - const takerGetsAmount = parseAmount(data.TakerGets); - const takerPaysAmount = parseAmount(data.TakerPays); - const quantity = direction === "buy" ? takerPaysAmount : takerGetsAmount; - const totalPrice = direction === "buy" ? takerGetsAmount : takerPaysAmount; + const direction = (data.Flags & orderFlags.Sell) === 0 ? 'buy' : 'sell' + const takerGetsAmount = parseAmount(data.TakerGets) + const takerPaysAmount = parseAmount(data.TakerPays) + const quantity = direction === 'buy' ? takerPaysAmount : takerGetsAmount + const totalPrice = direction === 'buy' ? takerGetsAmount : takerPaysAmount // note: immediateOrCancel and fillOrKill orders cannot enter the order book // so we can omit those flags here @@ -40,10 +37,10 @@ export function parseOrderbookOrder(data: BookOffer): FormattedOrderbookOrder { totalPrice, passive: (data.Flags & orderFlags.Passive) !== 0 || undefined, expirationTime: parseTimestamp(data.Expiration), - }); + }) if (data.quality == null) { - throw new Error("parseOrderBookOrder: Could not find quality"); + throw new Error('parseOrderBookOrder: Could not find quality') } const properties = { @@ -52,26 +49,26 @@ export function parseOrderbookOrder(data: BookOffer): FormattedOrderbookOrder { makerExchangeRate: adjustQualityForXRP( data.quality, takerGetsAmount.currency, - takerPaysAmount.currency + takerPaysAmount.currency, ), - }; + } const takerGetsFunded = data.taker_gets_funded ? parseAmount(data.taker_gets_funded) - : undefined; + : undefined const takerPaysFunded = data.taker_pays_funded ? parseAmount(data.taker_pays_funded) - : undefined; + : undefined const available = removeUndefined({ fundedAmount: takerGetsFunded, priceOfFundedAmount: takerPaysFunded, - }); - const state = _.isEmpty(available) ? undefined : available; + }) + const state = _.isEmpty(available) ? undefined : available return removeUndefined({ specification, properties, state, data, - }) as FormattedOrderbookOrder; + }) as FormattedOrderbookOrder } diff --git a/src/ledger/parse/pathfind.ts b/src/ledger/parse/pathfind.ts index f00be559..86b511ed 100644 --- a/src/ledger/parse/pathfind.ts +++ b/src/ledger/parse/pathfind.ts @@ -1,40 +1,40 @@ -import _ from "lodash"; +import _ from 'lodash' -import { Amount, RippledAmount } from "../../common/types/objects"; -import { Path, GetPaths, RippledPathsResponse } from "../pathfind-types"; +import { Amount, RippledAmount } from '../../common/types/objects' +import { Path, GetPaths, RippledPathsResponse } from '../pathfind-types' -import parseAmount from "./amount"; +import parseAmount from './amount' function parsePaths(paths) { return paths.map((steps) => - steps.map((step) => _.omit(step, ["type", "type_hex"])) - ); + steps.map((step) => _.omit(step, ['type', 'type_hex'])), + ) } function removeAnyCounterpartyEncoding(address: string, amount: Amount) { return amount.counterparty === address - ? _.omit(amount, "counterparty") - : amount; + ? _.omit(amount, 'counterparty') + : amount } function createAdjustment( address: string, - adjustmentWithoutAddress: object + adjustmentWithoutAddress: object, ): any { - const amountKey = Object.keys(adjustmentWithoutAddress)[0]; - const amount = adjustmentWithoutAddress[amountKey]; + const amountKey = Object.keys(adjustmentWithoutAddress)[0] + const amount = adjustmentWithoutAddress[amountKey] return _.set( { address }, amountKey, - removeAnyCounterpartyEncoding(address, amount) - ); + removeAnyCounterpartyEncoding(address, amount), + ) } function parseAlternative( sourceAddress: string, destinationAddress: string, destinationAmount: RippledAmount, - alternative: any + alternative: any, ): Path { // we use "maxAmount"/"minAmount" here so that the result can be passed // directly to preparePayment @@ -49,22 +49,22 @@ function parseAlternative( : { source: { maxAmount: parseAmount(alternative.source_amount) }, destination: { amount: parseAmount(destinationAmount) }, - }; + } return { source: createAdjustment(sourceAddress, amounts.source), destination: createAdjustment(destinationAddress, amounts.destination), paths: JSON.stringify(parsePaths(alternative.paths_computed)), - }; + } } function parsePathfind(pathfindResult: RippledPathsResponse): GetPaths { - const sourceAddress = pathfindResult.source_account; - const destinationAddress = pathfindResult.destination_account; - const destinationAmount = pathfindResult.destination_amount; + const sourceAddress = pathfindResult.source_account + const destinationAddress = pathfindResult.destination_account + const destinationAmount = pathfindResult.destination_amount return pathfindResult.alternatives.map((alt) => - parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt) - ); + parseAlternative(sourceAddress, destinationAddress, destinationAmount, alt), + ) } -export default parsePathfind; +export default parsePathfind diff --git a/src/ledger/parse/payment-channel-claim.ts b/src/ledger/parse/payment-channel-claim.ts index 8a185937..026401dd 100644 --- a/src/ledger/parse/payment-channel-claim.ts +++ b/src/ledger/parse/payment-channel-claim.ts @@ -1,15 +1,15 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { txFlags } from "../../common"; -import { removeUndefined } from "../../utils"; +import { txFlags } from '../../common' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseMemos } from './utils' -const claimFlags = txFlags.PaymentChannelClaim; +const claimFlags = txFlags.PaymentChannelClaim function parsePaymentChannelClaim(tx: any): object { - assert.ok(tx.TransactionType === "PaymentChannelClaim"); + assert.ok(tx.TransactionType === 'PaymentChannelClaim') return removeUndefined({ memos: parseMemos(tx), @@ -20,7 +20,7 @@ function parsePaymentChannelClaim(tx: any): object { publicKey: tx.PublicKey, renew: Boolean(tx.Flags & claimFlags.Renew) || undefined, close: Boolean(tx.Flags & claimFlags.Close) || undefined, - }); + }) } -export default parsePaymentChannelClaim; +export default parsePaymentChannelClaim diff --git a/src/ledger/parse/payment-channel-create.ts b/src/ledger/parse/payment-channel-create.ts index 95413838..e6be67e9 100644 --- a/src/ledger/parse/payment-channel-create.ts +++ b/src/ledger/parse/payment-channel-create.ts @@ -1,12 +1,12 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseTimestamp, parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseTimestamp, parseMemos } from './utils' function parsePaymentChannelCreate(tx: any): object { - assert.ok(tx.TransactionType === "PaymentChannelCreate"); + assert.ok(tx.TransactionType === 'PaymentChannelCreate') return removeUndefined({ memos: parseMemos(tx), @@ -17,7 +17,7 @@ function parsePaymentChannelCreate(tx: any): object { cancelAfter: tx.CancelAfter && parseTimestamp(tx.CancelAfter), sourceTag: tx.SourceTag, destinationTag: tx.DestinationTag, - }); + }) } -export default parsePaymentChannelCreate; +export default parsePaymentChannelCreate diff --git a/src/ledger/parse/payment-channel-fund.ts b/src/ledger/parse/payment-channel-fund.ts index 92720291..2ea87149 100644 --- a/src/ledger/parse/payment-channel-fund.ts +++ b/src/ledger/parse/payment-channel-fund.ts @@ -1,19 +1,19 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import { parseTimestamp, parseMemos } from "./utils"; +import parseAmount from './amount' +import { parseTimestamp, parseMemos } from './utils' function parsePaymentChannelFund(tx: any): object { - assert.ok(tx.TransactionType === "PaymentChannelFund"); + assert.ok(tx.TransactionType === 'PaymentChannelFund') return removeUndefined({ memos: parseMemos(tx), channel: tx.Channel, amount: parseAmount(tx.Amount).value, expiration: tx.Expiration && parseTimestamp(tx.Expiration), - }); + }) } -export default parsePaymentChannelFund; +export default parsePaymentChannelFund diff --git a/src/ledger/parse/payment-channel.ts b/src/ledger/parse/payment-channel.ts index c02cd141..56074cb7 100644 --- a/src/ledger/parse/payment-channel.ts +++ b/src/ledger/parse/payment-channel.ts @@ -1,21 +1,21 @@ -import { PayChannel } from "../../models/ledger"; -import { removeUndefined, dropsToXrp } from "../../utils"; +import { PayChannel } from '../../models/ledger' +import { removeUndefined, dropsToXrp } from '../../utils' -import { parseTimestamp, parseMemos } from "./utils"; +import { parseTimestamp, parseMemos } from './utils' export interface FormattedPaymentChannel { - account: string; - amount: string; - balance: string; - publicKey: string; - destination: string; - settleDelay: number; - expiration?: string; - cancelAfter?: string; - sourceTag?: number; - destinationTag?: number; - previousAffectingTransactionID: string; - previousAffectingTransactionLedgerVersion: number; + account: string + amount: string + balance: string + publicKey: string + destination: string + settleDelay: number + expiration?: string + cancelAfter?: string + sourceTag?: number + destinationTag?: number + previousAffectingTransactionID: string + previousAffectingTransactionLedgerVersion: number } export function parsePaymentChannel(data: PayChannel): FormattedPaymentChannel { @@ -33,5 +33,5 @@ export function parsePaymentChannel(data: PayChannel): FormattedPaymentChannel { destinationTag: data.DestinationTag, previousAffectingTransactionID: data.PreviousTxnID, previousAffectingTransactionLedgerVersion: data.PreviousTxnLgrSeq, - }); + }) } diff --git a/src/ledger/parse/payment.ts b/src/ledger/parse/payment.ts index a48e0a5e..12b4f239 100644 --- a/src/ledger/parse/payment.ts +++ b/src/ledger/parse/payment.ts @@ -1,48 +1,48 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import _ from "lodash"; +import _ from 'lodash' -import { txFlags } from "../../common"; -import { removeUndefined } from "../../utils"; +import { txFlags } from '../../common' +import { removeUndefined } from '../../utils' -import parseAmount from "./amount"; -import * as utils from "./utils"; +import parseAmount from './amount' +import * as utils from './utils' function isNoDirectRipple(tx) { - return (tx.Flags & txFlags.Payment.NoRippleDirect) !== 0; + return (tx.Flags & txFlags.Payment.NoRippleDirect) !== 0 } function isQualityLimited(tx) { - return (tx.Flags & txFlags.Payment.LimitQuality) !== 0; + return (tx.Flags & txFlags.Payment.LimitQuality) !== 0 } function removeGenericCounterparty(amount, address) { return amount.counterparty === address - ? _.omit(amount, "counterparty") - : amount; + ? _.omit(amount, 'counterparty') + : amount } // Payment specification function parsePayment(tx: any): object { - assert.ok(tx.TransactionType === "Payment"); + assert.ok(tx.TransactionType === 'Payment') const source = { address: tx.Account, maxAmount: removeGenericCounterparty( parseAmount(tx.SendMax || tx.Amount), - tx.Account + tx.Account, ), tag: tx.SourceTag, - }; + } const destination: { - address: string; - tag: number | undefined; + address: string + tag: number | undefined } = { address: tx.Destination, tag: tx.DestinationTag, // Notice that `amount` is omitted to prevent misinterpretation - }; + } return removeUndefined({ source: removeUndefined(source), @@ -53,7 +53,7 @@ function parsePayment(tx: any): object { allowPartialPayment: utils.isPartialPayment(tx) || undefined, noDirectRipple: isNoDirectRipple(tx) || undefined, limitQuality: isQualityLimited(tx) || undefined, - }); + }) } -export default parsePayment; +export default parsePayment diff --git a/src/ledger/parse/settings.ts b/src/ledger/parse/settings.ts index da99b8b1..f1f0fea0 100644 --- a/src/ledger/parse/settings.ts +++ b/src/ledger/parse/settings.ts @@ -1,69 +1,69 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import _ from "lodash"; +import _ from 'lodash' -import { constants } from "../../common"; +import { constants } from '../../common' -import parseFields from "./fields"; +import parseFields from './fields' -const AccountFlags = constants.AccountFlags; +const AccountFlags = constants.AccountFlags function getAccountRootModifiedNode(tx: any) { const modifiedNodes = tx.meta.AffectedNodes.filter( - (node) => node.ModifiedNode.LedgerEntryType === "AccountRoot" - ); - assert.ok(modifiedNodes.length === 1); - return modifiedNodes[0].ModifiedNode; + (node) => node.ModifiedNode.LedgerEntryType === 'AccountRoot', + ) + assert.ok(modifiedNodes.length === 1) + return modifiedNodes[0].ModifiedNode } function parseFlags(tx: any): any { - const settings: any = {}; - if (tx.TransactionType !== "AccountSet") { - return settings; + const settings: any = {} + if (tx.TransactionType !== 'AccountSet') { + return settings } - const node = getAccountRootModifiedNode(tx); - const oldFlags = _.get(node.PreviousFields, "Flags"); - const newFlags = _.get(node.FinalFields, "Flags"); + const node = getAccountRootModifiedNode(tx) + const oldFlags = _.get(node.PreviousFields, 'Flags') + const newFlags = _.get(node.FinalFields, 'Flags') if (oldFlags != null && newFlags != null) { - const changedFlags = oldFlags ^ newFlags; - const setFlags = newFlags & changedFlags; - const clearedFlags = oldFlags & changedFlags; + const changedFlags = oldFlags ^ newFlags + const setFlags = newFlags & changedFlags + const clearedFlags = oldFlags & changedFlags Object.entries(AccountFlags).forEach((entry) => { - const [flagName, flagValue] = entry; + const [flagName, flagValue] = entry if (setFlags & flagValue) { - settings[flagName] = true; + settings[flagName] = true } else if (clearedFlags & flagValue) { - settings[flagName] = false; + settings[flagName] = false } - }); + }) } // enableTransactionIDTracking requires a special case because it // does not affect the Flags field; instead it adds/removes a field called // "AccountTxnID" to/from the account root. - const oldField = _.get(node.PreviousFields, "AccountTxnID"); - const newField = _.get(node.FinalFields, "AccountTxnID"); + const oldField = _.get(node.PreviousFields, 'AccountTxnID') + const newField = _.get(node.FinalFields, 'AccountTxnID') if (newField && !oldField) { - settings.enableTransactionIDTracking = true; + settings.enableTransactionIDTracking = true } else if (oldField && !newField) { - settings.enableTransactionIDTracking = false; + settings.enableTransactionIDTracking = false } - return settings; + return settings } function parseSettings(tx: any) { - const txType = tx.TransactionType; + const txType = tx.TransactionType assert.ok( - txType === "AccountSet" || - txType === "SetRegularKey" || - txType === "SignerListSet" - ); + txType === 'AccountSet' || + txType === 'SetRegularKey' || + txType === 'SignerListSet', + ) - return { ...parseFlags(tx), ...parseFields(tx) }; + return { ...parseFlags(tx), ...parseFields(tx) } } -export default parseSettings; +export default parseSettings diff --git a/src/ledger/parse/ticket-create.ts b/src/ledger/parse/ticket-create.ts index b193e48f..c9e695d6 100644 --- a/src/ledger/parse/ticket-create.ts +++ b/src/ledger/parse/ticket-create.ts @@ -1,15 +1,15 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import { parseMemos } from "./utils"; +import { parseMemos } from './utils' function parseTicketCreate(tx: any): object { - assert.ok(tx.TransactionType === "TicketCreate"); + assert.ok(tx.TransactionType === 'TicketCreate') return removeUndefined({ memos: parseMemos(tx), ticketCount: tx.TicketCount, - }); + }) } -export default parseTicketCreate; +export default parseTicketCreate diff --git a/src/ledger/parse/transaction.ts b/src/ledger/parse/transaction.ts index 34292034..37a161a8 100644 --- a/src/ledger/parse/transaction.ts +++ b/src/ledger/parse/transaction.ts @@ -1,58 +1,58 @@ -import { removeUndefined } from "../../utils"; +import { removeUndefined } from '../../utils' -import parseAccountDelete from "./account-delete"; -import parseAmendment from "./amendment"; // pseudo-transaction -import parseOrderCancellation from "./cancellation"; -import parseCheckCancel from "./check-cancel"; -import parseCheckCash from "./check-cash"; -import parseCheckCreate from "./check-create"; -import parseDepositPreauth from "./deposit-preauth"; -import parseEscrowCancellation from "./escrow-cancellation"; -import parseEscrowCreation from "./escrow-creation"; -import parseEscrowExecution from "./escrow-execution"; -import parseFeeUpdate from "./fee-update"; // pseudo-transaction -import parseOrder from "./order"; -import parsePayment from "./payment"; -import parsePaymentChannelClaim from "./payment-channel-claim"; -import parsePaymentChannelCreate from "./payment-channel-create"; -import parsePaymentChannelFund from "./payment-channel-fund"; -import parseSettings from "./settings"; -import parseTicketCreate from "./ticket-create"; -import parseTrustline from "./trustline"; -import { parseOutcome } from "./utils"; +import parseAccountDelete from './account-delete' +import parseAmendment from './amendment' // pseudo-transaction +import parseOrderCancellation from './cancellation' +import parseCheckCancel from './check-cancel' +import parseCheckCash from './check-cash' +import parseCheckCreate from './check-create' +import parseDepositPreauth from './deposit-preauth' +import parseEscrowCancellation from './escrow-cancellation' +import parseEscrowCreation from './escrow-creation' +import parseEscrowExecution from './escrow-execution' +import parseFeeUpdate from './fee-update' // pseudo-transaction +import parseOrder from './order' +import parsePayment from './payment' +import parsePaymentChannelClaim from './payment-channel-claim' +import parsePaymentChannelCreate from './payment-channel-create' +import parsePaymentChannelFund from './payment-channel-fund' +import parseSettings from './settings' +import parseTicketCreate from './ticket-create' +import parseTrustline from './trustline' +import { parseOutcome } from './utils' function parseTransactionType(type) { // Ordering matches https://developers.ripple.com/transaction-types.html const mapping = { - AccountSet: "settings", - AccountDelete: "accountDelete", - CheckCancel: "checkCancel", - CheckCash: "checkCash", - CheckCreate: "checkCreate", - DepositPreauth: "depositPreauth", - EscrowCancel: "escrowCancellation", - EscrowCreate: "escrowCreation", - EscrowFinish: "escrowExecution", - OfferCancel: "orderCancellation", - OfferCreate: "order", - Payment: "payment", - PaymentChannelClaim: "paymentChannelClaim", - PaymentChannelCreate: "paymentChannelCreate", - PaymentChannelFund: "paymentChannelFund", - SetRegularKey: "settings", - SignerListSet: "settings", - TicketCreate: "ticketCreate", - TrustSet: "trustline", + AccountSet: 'settings', + AccountDelete: 'accountDelete', + CheckCancel: 'checkCancel', + CheckCash: 'checkCash', + CheckCreate: 'checkCreate', + DepositPreauth: 'depositPreauth', + EscrowCancel: 'escrowCancellation', + EscrowCreate: 'escrowCreation', + EscrowFinish: 'escrowExecution', + OfferCancel: 'orderCancellation', + OfferCreate: 'order', + Payment: 'payment', + PaymentChannelClaim: 'paymentChannelClaim', + PaymentChannelCreate: 'paymentChannelCreate', + PaymentChannelFund: 'paymentChannelFund', + SetRegularKey: 'settings', + SignerListSet: 'settings', + TicketCreate: 'ticketCreate', + TrustSet: 'trustline', - EnableAmendment: "amendment", // pseudo-transaction - SetFee: "feeUpdate", // pseudo-transaction - }; - return mapping[type] || null; + EnableAmendment: 'amendment', // pseudo-transaction + SetFee: 'feeUpdate', // pseudo-transaction + } + return mapping[type] || null } // includeRawTransaction: undefined by default (getTransaction) function parseTransaction(tx: any, includeRawTransaction: boolean): any { - const type = parseTransactionType(tx.TransactionType); + const type = parseTransactionType(tx.TransactionType) const mapping = { settings: parseSettings, accountDelete: parseAccountDelete, @@ -74,21 +74,21 @@ function parseTransaction(tx: any, includeRawTransaction: boolean): any { amendment: parseAmendment, // pseudo-transaction feeUpdate: parseFeeUpdate, // pseudo-transaction - }; - const parser: Function = mapping[type]; + } + const parser: Function = mapping[type] const specification = parser ? parser(tx) : { - UNAVAILABLE: "Unrecognized transaction type.", + UNAVAILABLE: 'Unrecognized transaction type.', SEE_RAW_TRANSACTION: - "Since this type is unrecognized, `rawTransaction` is included in this response.", - }; + 'Since this type is unrecognized, `rawTransaction` is included in this response.', + } if (!parser) { - includeRawTransaction = true; + includeRawTransaction = true } - const outcome = parseOutcome(tx); + const outcome = parseOutcome(tx) return removeUndefined({ type, address: tx.Account, @@ -97,7 +97,7 @@ function parseTransaction(tx: any, includeRawTransaction: boolean): any { specification: removeUndefined(specification), outcome: outcome ? removeUndefined(outcome) : undefined, rawTransaction: includeRawTransaction ? JSON.stringify(tx) : undefined, - }); + }) } -export default parseTransaction; +export default parseTransaction diff --git a/src/ledger/parse/trustline.ts b/src/ledger/parse/trustline.ts index fbbbd5a9..88f8c62b 100644 --- a/src/ledger/parse/trustline.ts +++ b/src/ledger/parse/trustline.ts @@ -1,24 +1,24 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import { txFlags } from "../../common"; -import { removeUndefined } from "../../utils"; +import { txFlags } from '../../common' +import { removeUndefined } from '../../utils' -import { parseQuality, parseMemos } from "./utils"; +import { parseQuality, parseMemos } from './utils' -const flags = txFlags.TrustSet; +const flags = txFlags.TrustSet function parseFlag(flagsValue, trueValue, falseValue) { if (flagsValue & trueValue) { - return true; + return true } if (flagsValue & falseValue) { - return false; + return false } - return undefined; + return undefined } function parseTrustline(tx: any): object { - assert.ok(tx.TransactionType === "TrustSet"); + assert.ok(tx.TransactionType === 'TrustSet') return removeUndefined({ limit: tx.LimitAmount.value, @@ -30,11 +30,11 @@ function parseTrustline(tx: any): object { ripplingDisabled: parseFlag( tx.Flags, flags.SetNoRipple, - flags.ClearNoRipple + flags.ClearNoRipple, ), frozen: parseFlag(tx.Flags, flags.SetFreeze, flags.ClearFreeze), authorized: parseFlag(tx.Flags, flags.SetAuth, 0), - }); + }) } -export default parseTrustline; +export default parseTrustline diff --git a/src/ledger/parse/utils.ts b/src/ledger/parse/utils.ts index 3f34e605..cc90a55b 100644 --- a/src/ledger/parse/utils.ts +++ b/src/ledger/parse/utils.ts @@ -1,115 +1,115 @@ -import BigNumber from "bignumber.js"; -import transactionParser from "ripple-lib-transactionparser"; +import BigNumber from 'bignumber.js' +import transactionParser from 'ripple-lib-transactionparser' -import { txFlags } from "../../common"; -import { Amount, Memo } from "../../common/types/objects"; -import { removeUndefined, dropsToXrp, rippleTimeToISOTime } from "../../utils"; +import { txFlags } from '../../common' +import { Amount, Memo } from '../../common/types/objects' +import { removeUndefined, dropsToXrp, rippleTimeToISOTime } from '../../utils' -import parseAmount from "./amount"; +import parseAmount from './amount' interface OfferDescription { - direction: string; - quantity: any; - totalPrice: any; - sequence: number; - status: string; - makerExchangeRate: string; + direction: string + quantity: any + totalPrice: any + sequence: number + status: string + makerExchangeRate: string } interface Orderbook { - [key: string]: OfferDescription[]; + [key: string]: OfferDescription[] } interface BalanceSheetItem { - counterparty: string; - currency: string; - value: string; + counterparty: string + currency: string + value: string } interface BalanceSheet { - [key: string]: BalanceSheetItem[]; + [key: string]: BalanceSheetItem[] } function adjustQualityForXRP( quality: string, takerGetsCurrency: string, - takerPaysCurrency: string + takerPaysCurrency: string, ) { // quality = takerPays.value/takerGets.value // using drops (1e-6 XRP) for XRP values - const numeratorShift = takerPaysCurrency === "XRP" ? -6 : 0; - const denominatorShift = takerGetsCurrency === "XRP" ? -6 : 0; - const shift = numeratorShift - denominatorShift; + const numeratorShift = takerPaysCurrency === 'XRP' ? -6 : 0 + const denominatorShift = takerGetsCurrency === 'XRP' ? -6 : 0 + const shift = numeratorShift - denominatorShift return shift === 0 ? quality - : new BigNumber(quality).shiftedBy(shift).toString(); + : new BigNumber(quality).shiftedBy(shift).toString() } function parseQuality(quality?: number | null): number | undefined { - if (typeof quality !== "number") { - return undefined; + if (typeof quality !== 'number') { + return undefined } - return new BigNumber(quality).shiftedBy(-9).toNumber(); + return new BigNumber(quality).shiftedBy(-9).toNumber() } function parseTimestamp(rippleTime?: number | null): string | undefined { - if (typeof rippleTime !== "number") { - return undefined; + if (typeof rippleTime !== 'number') { + return undefined } - return rippleTimeToISOTime(rippleTime); + return rippleTimeToISOTime(rippleTime) } function removeEmptyCounterparty(amount) { - if (amount.counterparty === "") { - delete amount.counterparty; + if (amount.counterparty === '') { + delete amount.counterparty } } function removeEmptyCounterpartyInBalanceChanges(balanceChanges: BalanceSheet) { Object.entries(balanceChanges).forEach(([_, changes]) => { - changes.forEach(removeEmptyCounterparty); - }); + changes.forEach(removeEmptyCounterparty) + }) } function removeEmptyCounterpartyInOrderbookChanges( - orderbookChanges: Orderbook + orderbookChanges: Orderbook, ) { Object.entries(orderbookChanges).forEach(([_, changes]) => { changes.forEach((change) => { - Object.entries(change).forEach(removeEmptyCounterparty); - }); - }); + Object.entries(change).forEach(removeEmptyCounterparty) + }) + }) } function isPartialPayment(tx: any) { - return (tx.Flags & txFlags.Payment.PartialPayment) !== 0; + return (tx.Flags & txFlags.Payment.PartialPayment) !== 0 } function parseDeliveredAmount(tx: any): Amount | void { if ( - tx.TransactionType !== "Payment" || - tx.meta.TransactionResult !== "tesSUCCESS" + tx.TransactionType !== 'Payment' || + tx.meta.TransactionResult !== 'tesSUCCESS' ) { - return undefined; + return undefined } - if (tx.meta.delivered_amount && tx.meta.delivered_amount === "unavailable") { - return undefined; + if (tx.meta.delivered_amount && tx.meta.delivered_amount === 'unavailable') { + return undefined } // parsable delivered_amount if (tx.meta.delivered_amount) { - return parseAmount(tx.meta.delivered_amount); + return parseAmount(tx.meta.delivered_amount) } // DeliveredAmount only present on partial payments if (tx.meta.DeliveredAmount) { - return parseAmount(tx.meta.DeliveredAmount); + return parseAmount(tx.meta.DeliveredAmount) } // no partial payment flag, use tx.Amount if (tx.Amount && !isPartialPayment(tx)) { - return parseAmount(tx.Amount); + return parseAmount(tx.Amount) } // DeliveredAmount field was introduced at @@ -119,23 +119,23 @@ function parseDeliveredAmount(tx: any): Amount | void { // transferred with a partial payment before // that date must be derived from metadata. if (tx.Amount && tx.ledger_index > 4594094) { - return parseAmount(tx.Amount); + return parseAmount(tx.Amount) } - return undefined; + return undefined } function parseOutcome(tx: any): any | undefined { - const metadata = tx.meta || tx.metaData; + const metadata = tx.meta || tx.metaData if (!metadata) { - return undefined; + return undefined } - const balanceChanges = transactionParser.parseBalanceChanges(metadata); - const orderbookChanges = transactionParser.parseOrderbookChanges(metadata); - const channelChanges = transactionParser.parseChannelChanges(metadata); + const balanceChanges = transactionParser.parseBalanceChanges(metadata) + const orderbookChanges = transactionParser.parseOrderbookChanges(metadata) + const channelChanges = transactionParser.parseChannelChanges(metadata) - removeEmptyCounterpartyInBalanceChanges(balanceChanges); - removeEmptyCounterpartyInOrderbookChanges(orderbookChanges); + removeEmptyCounterpartyInBalanceChanges(balanceChanges) + removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) return removeUndefined({ result: tx.meta.TransactionResult, @@ -147,24 +147,24 @@ function parseOutcome(tx: any): any | undefined { ledgerVersion: tx.ledger_index, indexInLedger: tx.meta.TransactionIndex, deliveredAmount: parseDeliveredAmount(tx), - }); + }) } function hexToString(hex: string): string | undefined { - return hex ? Buffer.from(hex, "hex").toString("utf-8") : undefined; + return hex ? Buffer.from(hex, 'hex').toString('utf-8') : undefined } function parseMemos(tx: any): Memo[] | undefined { if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) { - return undefined; + return undefined } return tx.Memos.map((m) => { return removeUndefined({ type: m.Memo.parsed_memo_type || hexToString(m.Memo.MemoType), format: m.Memo.parsed_memo_format || hexToString(m.Memo.MemoFormat), data: m.Memo.parsed_memo_data || hexToString(m.Memo.MemoData), - }); - }); + }) + }) } export { @@ -175,4 +175,4 @@ export { parseTimestamp, adjustQualityForXRP, isPartialPayment, -}; +} diff --git a/src/ledger/pathfind-types.ts b/src/ledger/pathfind-types.ts index 8612567f..78d83970 100644 --- a/src/ledger/pathfind-types.ts +++ b/src/ledger/pathfind-types.ts @@ -4,63 +4,63 @@ import { Adjustment, MaxAdjustment, MinAdjustment, -} from "../common/types/objects"; +} from '../common/types/objects' // Amount where counterparty and value are optional export interface LaxLaxAmount { - currency: string; - value?: string; - issuer?: string; - counterparty?: string; + currency: string + value?: string + issuer?: string + counterparty?: string } export interface Path { - source: Adjustment | MaxAdjustment; - destination: Adjustment | MinAdjustment; - paths: string; + source: Adjustment | MaxAdjustment + destination: Adjustment | MinAdjustment + paths: string } -export type GetPaths = Path[]; +export type GetPaths = Path[] export interface PathFind { source: { - address: string; - amount?: Amount; - currencies?: Array<{ currency: string; counterparty?: string }>; - }; + address: string + amount?: Amount + currencies?: Array<{ currency: string; counterparty?: string }> + } destination: { - address: string; - amount: LaxLaxAmount; - }; + address: string + amount: LaxLaxAmount + } } export interface PathFindRequest { - command: string; - source_account: string; - destination_amount: RippledAmount; - destination_account: string; - source_currencies?: Array<{ currency: string; issuer?: string }>; - send_max?: RippledAmount; + command: string + source_account: string + destination_amount: RippledAmount + destination_account: string + source_currencies?: Array<{ currency: string; issuer?: string }> + send_max?: RippledAmount } export interface RippledPathsResponse { alternatives: Array<{ paths_computed: Array< Array<{ - type: number; - type_hex: string; - account?: string; - issuer?: string; - currency?: string; + type: number + type_hex: string + account?: string + issuer?: string + currency?: string }> - >; - source_amount: RippledAmount; - }>; - type: string; - destination_account: string; - destination_amount: RippledAmount; - destination_currencies?: string[]; - source_account: string; - source_currencies?: Array<{ currency: string }>; - full_reply?: boolean; + > + source_amount: RippledAmount + }> + type: string + destination_account: string + destination_amount: RippledAmount + destination_currencies?: string[] + source_account: string + source_currencies?: Array<{ currency: string }> + full_reply?: boolean } diff --git a/src/ledger/pathfind.ts b/src/ledger/pathfind.ts index afbf36c9..93c0edb5 100644 --- a/src/ledger/pathfind.ts +++ b/src/ledger/pathfind.ts @@ -1,28 +1,28 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' -import type { Client } from ".."; -import type { Connection } from "../client"; -import { errors } from "../common"; -import { RippledAmount, Amount } from "../common/types/objects"; -import { RipplePathFindRequest } from "../models/methods"; -import { toRippledAmount, xrpToDrops, dropsToXrp } from "../utils"; +import type { Client } from '..' +import type { Connection } from '../client' +import { errors } from '../common' +import { RippledAmount, Amount } from '../common/types/objects' +import { RipplePathFindRequest } from '../models/methods' +import { toRippledAmount, xrpToDrops, dropsToXrp } from '../utils' -import parsePathfind from "./parse/pathfind"; +import parsePathfind from './parse/pathfind' import { GetPaths, PathFind, RippledPathsResponse, PathFindRequest, -} from "./pathfind-types"; -import { getXRPBalance, renameCounterpartyToIssuer } from "./utils"; +} from './pathfind-types' +import { getXRPBalance, renameCounterpartyToIssuer } from './utils' -const NotFoundError = errors.NotFoundError; -const ValidationError = errors.ValidationError; +const NotFoundError = errors.NotFoundError +const ValidationError = errors.ValidationError function addParams( request: PathFindRequest, - result: RippledPathsResponse + result: RippledPathsResponse, ): RippledPathsResponse { return _.defaults( { @@ -30,106 +30,106 @@ function addParams( source_account: request.source_account, source_currencies: request.source_currencies, }, - { destination_amount: request.destination_amount } - ); + { destination_amount: request.destination_amount }, + ) } async function requestPathFind( connection: Connection, - pathfind: PathFind + pathfind: PathFind, ): Promise { const destinationAmount: Amount = { // This is converted back to drops by toRippledAmount() value: - pathfind.destination.amount.currency === "XRP" ? dropsToXrp("-1") : "-1", + pathfind.destination.amount.currency === 'XRP' ? dropsToXrp('-1') : '-1', ...pathfind.destination.amount, - }; + } const request: RipplePathFindRequest = { - command: "ripple_path_find", + command: 'ripple_path_find', source_account: pathfind.source.address, destination_account: pathfind.destination.address, // @ts-expect-error destination_amount: destinationAmount, - }; + } if ( - typeof request.destination_amount === "object" && + typeof request.destination_amount === 'object' && !request.destination_amount.issuer ) { // Convert blank issuer to sender's address // (Ripple convention for 'any issuer') // https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount - request.destination_amount.issuer = request.destination_account; + request.destination_amount.issuer = request.destination_account } if (pathfind.source.currencies && pathfind.source.currencies.length > 0) { // @ts-expect-error request.source_currencies = pathfind.source.currencies.map((amount) => - renameCounterpartyToIssuer(amount) - ); + renameCounterpartyToIssuer(amount), + ) } if (pathfind.source.amount) { if (pathfind.destination.amount.value != null) { throw new ValidationError( - "Cannot specify both source.amount" + - " and destination.amount.value in getPaths" - ); + 'Cannot specify both source.amount' + + ' and destination.amount.value in getPaths', + ) } // @ts-expect-error - request.send_max = toRippledAmount(pathfind.source.amount); + request.send_max = toRippledAmount(pathfind.source.amount) if ( request.send_max != null && - typeof request.send_max !== "string" && + typeof request.send_max !== 'string' && !request.send_max.issuer ) { - request.send_max.issuer = pathfind.source.address; + request.send_max.issuer = pathfind.source.address } } // @ts-expect-error - return connection.request(request).then((paths) => addParams(request, paths)); + return connection.request(request).then((paths) => addParams(request, paths)) } function addDirectXrpPath( paths: RippledPathsResponse, - xrpBalance: string + xrpBalance: string, ): RippledPathsResponse { // Add XRP "path" only if the source acct has enough XRP to make the payment - const destinationAmount = paths.destination_amount; + const destinationAmount = paths.destination_amount // @ts-expect-error: destinationAmount can be a currency amount object! Fix! if (new BigNumber(xrpBalance).isGreaterThanOrEqualTo(destinationAmount)) { paths.alternatives.unshift({ paths_computed: [], source_amount: paths.destination_amount, - }); + }) } - return paths; + return paths } function isRippledIOUAmount(amount: RippledAmount) { // rippled XRP amounts are specified as decimal strings return ( - typeof amount === "object" && amount.currency && amount.currency !== "XRP" - ); + typeof amount === 'object' && amount.currency && amount.currency !== 'XRP' + ) } async function conditionallyAddDirectXRPPath( client: Client, address: string, - paths: RippledPathsResponse + paths: RippledPathsResponse, ): Promise { if ( isRippledIOUAmount(paths.destination_amount) || (paths.destination_currencies && - !paths.destination_currencies.includes("XRP")) + !paths.destination_currencies.includes('XRP')) ) { - return Promise.resolve(paths); + return Promise.resolve(paths) } return getXRPBalance(client, address, undefined).then((xrpBalance) => - addDirectXrpPath(paths, xrpBalance) - ); + addDirectXrpPath(paths, xrpBalance), + ) } function filterSourceFundsLowPaths( pathfind: PathFind, - paths: RippledPathsResponse + paths: RippledPathsResponse, ): RippledPathsResponse { if ( pathfind.source.amount && @@ -138,65 +138,65 @@ function filterSourceFundsLowPaths( ) { paths.alternatives = paths.alternatives.filter((alt) => { if (!alt.source_amount) { - return false; + return false } if (pathfind.source.amount === undefined) { - return false; + return false } const pathfindSourceAmountValue = new BigNumber( - pathfind.source.amount.currency === "XRP" + pathfind.source.amount.currency === 'XRP' ? xrpToDrops(pathfind.source.amount.value) - : pathfind.source.amount.value - ); + : pathfind.source.amount.value, + ) const altSourceAmountValue = new BigNumber( - typeof alt.source_amount === "string" + typeof alt.source_amount === 'string' ? alt.source_amount - : alt.source_amount.value - ); - return altSourceAmountValue.eq(pathfindSourceAmountValue); - }); + : alt.source_amount.value, + ) + return altSourceAmountValue.eq(pathfindSourceAmountValue) + }) } - return paths; + return paths } function formatResponse(pathfind: PathFind, paths: RippledPathsResponse) { if (paths.alternatives && paths.alternatives.length > 0) { - return parsePathfind(paths); + return parsePathfind(paths) } if ( paths.destination_currencies != null && !paths.destination_currencies.includes(pathfind.destination.amount.currency) ) { throw new NotFoundError( - `${"No paths found. " + "The destination_account does not accept "}${ + `${'No paths found. ' + 'The destination_account does not accept '}${ pathfind.destination.amount.currency - }, they only accept: ${paths.destination_currencies.join(", ")}` - ); + }, they only accept: ${paths.destination_currencies.join(', ')}`, + ) } else if (paths.source_currencies && paths.source_currencies.length > 0) { throw new NotFoundError( - "No paths found. Please ensure" + - " that the source_account has sufficient funds to execute" + - " the payment in one of the specified source_currencies. If it does" + - " there may be insufficient liquidity in the network to execute" + - " this payment right now" - ); + 'No paths found. Please ensure' + + ' that the source_account has sufficient funds to execute' + + ' the payment in one of the specified source_currencies. If it does' + + ' there may be insufficient liquidity in the network to execute' + + ' this payment right now', + ) } else { throw new NotFoundError( - "No paths found." + - " Please ensure that the source_account has sufficient funds to" + - " execute the payment. If it does there may be insufficient liquidity" + - " in the network to execute this payment right now" - ); + 'No paths found.' + + ' Please ensure that the source_account has sufficient funds to' + + ' execute the payment. If it does there may be insufficient liquidity' + + ' in the network to execute this payment right now', + ) } } async function getPaths(this: Client, pathfind: PathFind): Promise { - const address = pathfind.source.address; + const address = pathfind.source.address return requestPathFind(this.connection, pathfind) .then(async (paths) => conditionallyAddDirectXRPPath(this, address, paths)) .then((paths) => filterSourceFundsLowPaths(pathfind, paths)) - .then((paths) => formatResponse(pathfind, paths)); + .then((paths) => formatResponse(pathfind, paths)) } -export default getPaths; +export default getPaths diff --git a/src/ledger/trustlines.ts b/src/ledger/trustlines.ts index 034c85d0..2206408d 100644 --- a/src/ledger/trustlines.ts +++ b/src/ledger/trustlines.ts @@ -1,48 +1,48 @@ -import _ from "lodash"; +import _ from 'lodash' -import type { Client } from ".."; -import { ensureClassicAddress } from "../common"; -import { FormattedTrustline } from "../common/types/objects"; +import type { Client } from '..' +import { ensureClassicAddress } from '../common' +import { FormattedTrustline } from '../common/types/objects' -import parseAccountTrustline from "./parse/account-trustline"; +import parseAccountTrustline from './parse/account-trustline' export interface GetTrustlinesOptions { - counterparty?: string; - currency?: string; - limit?: number; - ledgerVersion?: number; + counterparty?: string + currency?: string + limit?: number + ledgerVersion?: number } function currencyFilter( currency: string | null, - trustline: FormattedTrustline + trustline: FormattedTrustline, ) { - return currency === null || trustline.specification.currency === currency; + return currency === null || trustline.specification.currency === currency } async function getTrustlines( this: Client, address: string, - options: GetTrustlinesOptions = {} + options: GetTrustlinesOptions = {}, ): Promise { // Only support retrieving trustlines without a tag, // since it does not make sense to filter trustlines // by tag. - address = ensureClassicAddress(address); + address = ensureClassicAddress(address) // 2. Make Request const responses = await this.requestAll({ - command: "account_lines", + command: 'account_lines', account: address, - ledger_index: options.ledgerVersion ?? "validated", + ledger_index: options.ledgerVersion ?? 'validated', limit: options.limit, peer: options.counterparty, - }); + }) // 3. Return Formatted Response - const trustlines = _.flatMap(responses, (response) => response.result.lines); + const trustlines = _.flatMap(responses, (response) => response.result.lines) return trustlines.map(parseAccountTrustline).filter((trustline) => { - return currencyFilter(options.currency ?? null, trustline); - }); + return currencyFilter(options.currency ?? null, trustline) + }) } -export default getTrustlines; +export default getTrustlines diff --git a/src/ledger/utils.ts b/src/ledger/utils.ts index fb660a1d..b41e0356 100644 --- a/src/ledger/utils.ts +++ b/src/ledger/utils.ts @@ -1,92 +1,89 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import _ from "lodash"; +import _ from 'lodash' -import type { Client } from ".."; -import type { Connection } from "../client"; -import * as common from "../common"; -import { Issue } from "../common/types/objects"; -import { AccountInfoRequest } from "../models/methods"; -import { FormattedTransactionType } from "../transaction/types"; -import { dropsToXrp } from "../utils"; +import type { Client } from '..' +import type { Connection } from '../client' +import * as common from '../common' +import { Issue } from '../common/types/objects' +import { AccountInfoRequest } from '../models/methods' +import { FormattedTransactionType } from '../transaction/types' +import { dropsToXrp } from '../utils' export interface RecursiveData { - marker: string; - results: any[]; + marker: string + results: any[] } -export type Getter = ( - marker?: string, - limit?: number -) => Promise; +export type Getter = (marker?: string, limit?: number) => Promise function clamp(value: number, min: number, max: number): number { - assert.ok(min <= max, "Illegal clamp bounds"); - return Math.min(Math.max(value, min), max); + assert.ok(min <= max, 'Illegal clamp bounds') + return Math.min(Math.max(value, min), max) } async function getXRPBalance( client: Client, address: string, - ledgerVersion?: number + ledgerVersion?: number, ): Promise { const request: AccountInfoRequest = { - command: "account_info", + command: 'account_info', account: address, ledger_index: ledgerVersion, - }; - const data = await client.request(request); - return dropsToXrp(data.result.account_data.Balance); + } + const data = await client.request(request) + return dropsToXrp(data.result.account_data.Balance) } // If the marker is omitted from a response, you have reached the end async function getRecursiveRecur( getter: Getter, marker: string | undefined, - limit: number + limit: number, ): Promise { - const data = await getter(marker, limit); - const remaining = limit - data.results.length; + const data = await getter(marker, limit) + const remaining = limit - data.results.length if (remaining > 0 && data.marker != null) { return getRecursiveRecur(getter, data.marker, remaining).then((results) => - data.results.concat(results) - ); + data.results.concat(results), + ) } - return data.results.slice(0, limit); + return data.results.slice(0, limit) } -function getRecursive(getter: Getter, limit?: number): Promise { - return getRecursiveRecur(getter, undefined, limit || Infinity); +async function getRecursive(getter: Getter, limit?: number): Promise { + return getRecursiveRecur(getter, undefined, limit || Infinity) } function renameCounterpartyToIssuer( - obj: T & { counterparty?: string; issuer?: string } + obj: T & { counterparty?: string; issuer?: string }, ): T & { issuer?: string } { const issuer = obj.counterparty != null ? obj.counterparty : obj.issuer != null ? obj.issuer - : undefined; - const withIssuer = { ...obj, issuer }; - delete withIssuer.counterparty; - return withIssuer; + : undefined + const withIssuer = { ...obj, issuer } + delete withIssuer.counterparty + return withIssuer } export interface RequestBookOffersArgs { - taker_gets: Issue; - taker_pays: Issue; + taker_gets: Issue + taker_pays: Issue } 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 { ...order, ..._.omitBy(changes, (value) => value == null) }; + const taker_gets = renameCounterpartyToIssuer(order.taker_gets) + const taker_pays = renameCounterpartyToIssuer(order.taker_pays) + const changes = { taker_gets, taker_pays } + return { ...order, ..._.omitBy(changes, (value) => value == null) } } function signum(num) { - return num === 0 ? 0 : num > 0 ? 1 : -1; + return num === 0 ? 0 : num > 0 ? 1 : -1 } /** @@ -100,46 +97,46 @@ function signum(num) { */ function compareTransactions( first: FormattedTransactionType, - second: FormattedTransactionType + second: FormattedTransactionType, ): number { if (!first.outcome || !second.outcome) { - return 0; + return 0 } if (first.outcome.ledgerVersion === second.outcome.ledgerVersion) { - return signum(first.outcome.indexInLedger - second.outcome.indexInLedger); + return signum(first.outcome.indexInLedger - second.outcome.indexInLedger) } - return first.outcome.ledgerVersion < second.outcome.ledgerVersion ? -1 : 1; + return first.outcome.ledgerVersion < second.outcome.ledgerVersion ? -1 : 1 } async function isPendingLedgerVersion( client: Client, - maxLedgerVersion?: number + maxLedgerVersion?: number, ): Promise { const response = await client.request({ - command: "ledger", - ledger_index: "validated", - }); - const ledgerVersion = response.result.ledger_index; - return ledgerVersion < (maxLedgerVersion || 0); + command: 'ledger', + ledger_index: 'validated', + }) + const ledgerVersion = response.result.ledger_index + return ledgerVersion < (maxLedgerVersion || 0) } async function ensureLedgerVersion( this: Client, - options: any + options: any, ): Promise { if ( Boolean(options) && options.ledgerVersion != null && options.ledgerVersion !== null ) { - return Promise.resolve(options); + return Promise.resolve(options) } const response = await this.request({ - command: "ledger", - ledger_index: "validated", - }); - const ledgerVersion = response.result.ledger_index; - return { ...options, ledgerVersion }; + command: 'ledger', + ledger_index: 'validated', + }) + const ledgerVersion = response.result.ledger_index + return { ...options, ledgerVersion } } export { @@ -153,4 +150,4 @@ export { clamp, common, Connection, -}; +} diff --git a/src/models/common/index.ts b/src/models/common/index.ts index c9aeebb8..23825c7e 100644 --- a/src/models/common/index.ts +++ b/src/models/common/index.ts @@ -1,61 +1,61 @@ -export type LedgerIndex = number | ("validated" | "closed" | "current"); +export type LedgerIndex = number | ('validated' | 'closed' | 'current') export type AccountObjectType = - | "check" - | "escrow" - | "offer" - | "payment_channel" - | "signer_list" - | "state"; + | 'check' + | 'escrow' + | 'offer' + | 'payment_channel' + | 'signer_list' + | 'state' interface XRP { - currency: "XRP"; + currency: 'XRP' } interface IssuedCurrency { - currency: string; - issuer: string; + currency: string + issuer: string } -export type Currency = IssuedCurrency | XRP; +export type Currency = IssuedCurrency | XRP export interface IssuedCurrencyAmount extends IssuedCurrency { - value: string; + value: string } -export type Amount = IssuedCurrencyAmount | string; +export type Amount = IssuedCurrencyAmount | string export interface Signer { - Account: string; - TxnSignature: string; - SigningPubKey: string; + Account: string + TxnSignature: string + SigningPubKey: string } export interface Memo { - MemoData?: string; - MemoType?: string; - MemoFormat?: string; + MemoData?: string + MemoType?: string + MemoFormat?: string } export type StreamType = - | "consensus" - | "ledger" - | "manifests" - | "peer_status" - | "transactions" - | "transactions_proposed" - | "server" - | "validations"; + | 'consensus' + | 'ledger' + | 'manifests' + | 'peer_status' + | 'transactions' + | 'transactions_proposed' + | 'server' + | 'validations' interface PathStep { - account?: string; - currency?: string; - issuer?: string; + account?: string + currency?: string + issuer?: string } -export type Path = PathStep[]; +export type Path = PathStep[] export interface SignerEntry { - Account: string; - SignerWeight: number; + Account: string + SignerWeight: number } diff --git a/src/models/ledger/accountRoot.ts b/src/models/ledger/accountRoot.ts index 6e871d1e..f7111210 100644 --- a/src/models/ledger/accountRoot.ts +++ b/src/models/ledger/accountRoot.ts @@ -1,20 +1,20 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface AccountRoot extends BaseLedgerEntry { - LedgerEntryType: "AccountRoot"; - Account: string; - Balance: string; - Flags: number; - OwnerCount: number; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - Sequence: number; - AccountTxnID?: string; - Domain?: string; - EmailHash?: string; - MessageKey?: string; - RegularKey?: string; - TicketCount?: number; - TickSize?: number; - TransferRate?: number; + LedgerEntryType: 'AccountRoot' + Account: string + Balance: string + Flags: number + OwnerCount: number + PreviousTxnID: string + PreviousTxnLgrSeq: number + Sequence: number + AccountTxnID?: string + Domain?: string + EmailHash?: string + MessageKey?: string + RegularKey?: string + TicketCount?: number + TickSize?: number + TransferRate?: number } diff --git a/src/models/ledger/amendments.ts b/src/models/ledger/amendments.ts index c472ddbc..60a0f599 100644 --- a/src/models/ledger/amendments.ts +++ b/src/models/ledger/amendments.ts @@ -1,15 +1,15 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' interface Majority { Majority: { - Amendment: string; - CloseTime: number; - }; + Amendment: string + CloseTime: number + } } export default interface Amendments extends BaseLedgerEntry { - LedgerEntryType: "Amendments"; - Amendments?: string[]; - Majorities?: Majority[]; - Flags: 0; + LedgerEntryType: 'Amendments' + Amendments?: string[] + Majorities?: Majority[] + Flags: 0 } diff --git a/src/models/ledger/baseLedgerEntry.ts b/src/models/ledger/baseLedgerEntry.ts index eda3b127..4bf9e5c2 100644 --- a/src/models/ledger/baseLedgerEntry.ts +++ b/src/models/ledger/baseLedgerEntry.ts @@ -1,3 +1,3 @@ export default interface BaseLedgerEntry { - index: string; + index: string } diff --git a/src/models/ledger/check.ts b/src/models/ledger/check.ts index 83dd8d81..94ad3ace 100644 --- a/src/models/ledger/check.ts +++ b/src/models/ledger/check.ts @@ -1,20 +1,20 @@ -import { Amount } from "../common"; +import { Amount } from '../common' -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface Check extends BaseLedgerEntry { - LedgerEntryType: "Check"; - Account: string; - Destination: string; - Flags: 0; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - SendMax: Amount; - Sequence: number; - DestinationNode?: string; - DestinationTag?: number; - Expiration?: number; - InvoiceID?: string; - SourceTag?: number; + LedgerEntryType: 'Check' + Account: string + Destination: string + Flags: 0 + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + SendMax: Amount + Sequence: number + DestinationNode?: string + DestinationTag?: number + Expiration?: number + InvoiceID?: string + SourceTag?: number } diff --git a/src/models/ledger/depositPreauth.ts b/src/models/ledger/depositPreauth.ts index 0ab82153..cd41a39a 100644 --- a/src/models/ledger/depositPreauth.ts +++ b/src/models/ledger/depositPreauth.ts @@ -1,11 +1,11 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface DepositPreauth extends BaseLedgerEntry { - LedgerEntryType: "DepositPreauth"; - Account: string; - Authorize: string; - Flags: 0; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; + LedgerEntryType: 'DepositPreauth' + Account: string + Authorize: string + Flags: 0 + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number } diff --git a/src/models/ledger/directoryNode.ts b/src/models/ledger/directoryNode.ts index b60fab39..2d5b717d 100644 --- a/src/models/ledger/directoryNode.ts +++ b/src/models/ledger/directoryNode.ts @@ -1,15 +1,15 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface DirectoryNode extends BaseLedgerEntry { - LedgerEntryType: "DirectoryNode"; - Flags: number; - RootIndex: string; - Indexes: string[]; - IndexNext?: number; - IndexPrevious?: number; - Owner?: string; - TakerPaysCurrency?: string; - TakerPaysIssuer?: string; - TakerGetsCurrency?: string; - TakerGetsIssuer?: string; + LedgerEntryType: 'DirectoryNode' + Flags: number + RootIndex: string + Indexes: string[] + IndexNext?: number + IndexPrevious?: number + Owner?: string + TakerPaysCurrency?: string + TakerPaysIssuer?: string + TakerGetsCurrency?: string + TakerGetsIssuer?: string } diff --git a/src/models/ledger/escrow.ts b/src/models/ledger/escrow.ts index 950bdce4..da04c685 100644 --- a/src/models/ledger/escrow.ts +++ b/src/models/ledger/escrow.ts @@ -1,18 +1,18 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface Escrow extends BaseLedgerEntry { - LedgerEntryType: "Escrow"; - Account: string; - Destination: string; - Amount: string; - Condition?: string; - CancelAfter?: number; - FinishAfter?: number; - Flags: number; - SourceTag?: number; - DestinationTag?: number; - OwnerNode: string; - DestinationNode?: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; + LedgerEntryType: 'Escrow' + Account: string + Destination: string + Amount: string + Condition?: string + CancelAfter?: number + FinishAfter?: number + Flags: number + SourceTag?: number + DestinationTag?: number + OwnerNode: string + DestinationNode?: string + PreviousTxnID: string + PreviousTxnLgrSeq: number } diff --git a/src/models/ledger/feeSettings.ts b/src/models/ledger/feeSettings.ts index 53550405..ae79b37c 100644 --- a/src/models/ledger/feeSettings.ts +++ b/src/models/ledger/feeSettings.ts @@ -1,10 +1,10 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface FeeSettings extends BaseLedgerEntry { - LedgerEntryType: "FeeSettings"; - BaseFee: string; - ReferenceFeeUnits: number; - ReserveBase: number; - ReserveIncrement: number; - Flags: number; + LedgerEntryType: 'FeeSettings' + BaseFee: string + ReferenceFeeUnits: number + ReserveBase: number + ReserveIncrement: number + Flags: number } diff --git a/src/models/ledger/index.ts b/src/models/ledger/index.ts index 58ea1838..4bf26562 100644 --- a/src/models/ledger/index.ts +++ b/src/models/ledger/index.ts @@ -1,21 +1,21 @@ /* eslint-disable import/max-dependencies -- Needs to export all ledger objects */ /* eslint-disable import/no-unused-modules -- Needs to export all ledger objects */ -import AccountRoot from "./accountRoot"; -import Amendments from "./amendments"; -import Check from "./check"; -import DepositPreauth from "./depositPreauth"; -import DirectoryNode from "./directoryNode"; -import Escrow from "./escrow"; -import FeeSettings from "./feeSettings"; -import Ledger from "./ledger"; -import LedgerEntry from "./ledgerEntry"; -import LedgerHashes from "./ledgerHashes"; -import NegativeUNL from "./negativeUNL"; -import Offer from "./offer"; -import PayChannel from "./payChannel"; -import RippleState from "./rippleState"; -import SignerList from "./signerList"; -import Ticket from "./ticket"; +import AccountRoot from './accountRoot' +import Amendments from './amendments' +import Check from './check' +import DepositPreauth from './depositPreauth' +import DirectoryNode from './directoryNode' +import Escrow from './escrow' +import FeeSettings from './feeSettings' +import Ledger from './ledger' +import LedgerEntry from './ledgerEntry' +import LedgerHashes from './ledgerHashes' +import NegativeUNL from './negativeUNL' +import Offer from './offer' +import PayChannel from './payChannel' +import RippleState from './rippleState' +import SignerList from './signerList' +import Ticket from './ticket' export { AccountRoot, @@ -34,4 +34,4 @@ export { RippleState, SignerList, Ticket, -}; +} diff --git a/src/models/ledger/ledger.ts b/src/models/ledger/ledger.ts index ecd3fdda..eb9706f3 100644 --- a/src/models/ledger/ledger.ts +++ b/src/models/ledger/ledger.ts @@ -1,20 +1,20 @@ -import { Transaction } from "../transactions"; +import { Transaction } from '../transactions' -import LedgerEntry from "./ledgerEntry"; +import LedgerEntry from './ledgerEntry' export default interface Ledger { - account_hash: string; - accountState?: LedgerEntry[]; - close_flags: number; - close_time: number; - close_time_human: string; - close_time_resolution: number; - closed: boolean; - ledger_hash: string; - ledger_index: string; - parent_close_time: number; - parent_hash: string; - total_coins: string; - transaction_hash: string; - transactions?: Transaction[]; + account_hash: string + accountState?: LedgerEntry[] + close_flags: number + close_time: number + close_time_human: string + close_time_resolution: number + closed: boolean + ledger_hash: string + ledger_index: string + parent_close_time: number + parent_hash: string + total_coins: string + transaction_hash: string + transactions?: Transaction[] } diff --git a/src/models/ledger/ledgerEntry.ts b/src/models/ledger/ledgerEntry.ts index d5f513dc..62533be5 100644 --- a/src/models/ledger/ledgerEntry.ts +++ b/src/models/ledger/ledgerEntry.ts @@ -1,18 +1,18 @@ /* eslint-disable import/max-dependencies -- Needed for the type */ -import AccountRoot from "./accountRoot"; -import Amendments from "./amendments"; -import Check from "./check"; -import DepositPreauth from "./depositPreauth"; -import DirectoryNode from "./directoryNode"; -import Escrow from "./escrow"; -import FeeSettings from "./feeSettings"; -import LedgerHashes from "./ledgerHashes"; -import NegativeUNL from "./negativeUNL"; -import Offer from "./offer"; -import PayChannel from "./payChannel"; -import RippleState from "./rippleState"; -import SignerList from "./signerList"; -import Ticket from "./ticket"; +import AccountRoot from './accountRoot' +import Amendments from './amendments' +import Check from './check' +import DepositPreauth from './depositPreauth' +import DirectoryNode from './directoryNode' +import Escrow from './escrow' +import FeeSettings from './feeSettings' +import LedgerHashes from './ledgerHashes' +import NegativeUNL from './negativeUNL' +import Offer from './offer' +import PayChannel from './payChannel' +import RippleState from './rippleState' +import SignerList from './signerList' +import Ticket from './ticket' type LedgerEntry = | AccountRoot @@ -28,6 +28,6 @@ type LedgerEntry = | PayChannel | RippleState | SignerList - | Ticket; + | Ticket -export default LedgerEntry; +export default LedgerEntry diff --git a/src/models/ledger/ledgerHashes.ts b/src/models/ledger/ledgerHashes.ts index cb140f3a..8aac96c3 100644 --- a/src/models/ledger/ledgerHashes.ts +++ b/src/models/ledger/ledgerHashes.ts @@ -1,8 +1,8 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface LedgerHashes extends BaseLedgerEntry { - LedgerEntryType: "LedgerHashes"; - LastLedgerSequence?: number; - Hashes: string[]; - Flags: number; + LedgerEntryType: 'LedgerHashes' + LastLedgerSequence?: number + Hashes: string[] + Flags: number } diff --git a/src/models/ledger/negativeUNL.ts b/src/models/ledger/negativeUNL.ts index f12c25eb..948691d1 100644 --- a/src/models/ledger/negativeUNL.ts +++ b/src/models/ledger/negativeUNL.ts @@ -1,13 +1,13 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' interface DisabledValidator { - FirstLedgerSequence: number; - PublicKey: string; + FirstLedgerSequence: number + PublicKey: string } export default interface NegativeUNL extends BaseLedgerEntry { - LedgerEntryType: "NegativeUNL"; - DisabledValidators?: DisabledValidator[]; - ValidatorToDisable?: string; - ValidatorToReEnable?: string; + LedgerEntryType: 'NegativeUNL' + DisabledValidators?: DisabledValidator[] + ValidatorToDisable?: string + ValidatorToReEnable?: string } diff --git a/src/models/ledger/offer.ts b/src/models/ledger/offer.ts index 387a91a7..19c85b35 100644 --- a/src/models/ledger/offer.ts +++ b/src/models/ledger/offer.ts @@ -1,18 +1,18 @@ -import { Amount } from "../common"; +import { Amount } from '../common' -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface Offer extends BaseLedgerEntry { - LedgerEntryType: "Offer"; - Flags: number; - Account: string; - Sequence: number; - TakerPays: Amount; - TakerGets: Amount; - BookDirectory: string; - BookNode: string; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - Expiration?: number; + LedgerEntryType: 'Offer' + Flags: number + Account: string + Sequence: number + TakerPays: Amount + TakerGets: Amount + BookDirectory: string + BookNode: string + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + Expiration?: number } diff --git a/src/models/ledger/payChannel.ts b/src/models/ledger/payChannel.ts index 1e5972ed..94977de7 100644 --- a/src/models/ledger/payChannel.ts +++ b/src/models/ledger/payChannel.ts @@ -1,20 +1,20 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface PayChannel extends BaseLedgerEntry { - LedgerEntryType: "PayChannel"; - Account: string; - Destination: string; - Amount: string; - Balance: string; - PublicKey: string; - SettleDelay: number; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - Flags: number; - Expiration?: number; - CancelAfter?: number; - SourceTag?: number; - DestinationTag?: number; - DestinationNode?: string; + LedgerEntryType: 'PayChannel' + Account: string + Destination: string + Amount: string + Balance: string + PublicKey: string + SettleDelay: number + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + Flags: number + Expiration?: number + CancelAfter?: number + SourceTag?: number + DestinationTag?: number + DestinationNode?: string } diff --git a/src/models/ledger/rippleState.ts b/src/models/ledger/rippleState.ts index 115f331f..2fd7165f 100644 --- a/src/models/ledger/rippleState.ts +++ b/src/models/ledger/rippleState.ts @@ -1,19 +1,19 @@ -import { IssuedCurrencyAmount } from "../common"; +import { IssuedCurrencyAmount } from '../common' -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface RippleState extends BaseLedgerEntry { - LedgerEntryType: "RippleState"; - Flags: number; - Balance: IssuedCurrencyAmount; - LowLimit: IssuedCurrencyAmount; - HighLimit: IssuedCurrencyAmount; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - LowNode?: string; - HighNode?: string; - LowQualityIn?: number; - LowQualityOut?: number; - HighQualityIn?: number; - HighQualityOut?: number; + LedgerEntryType: 'RippleState' + Flags: number + Balance: IssuedCurrencyAmount + LowLimit: IssuedCurrencyAmount + HighLimit: IssuedCurrencyAmount + PreviousTxnID: string + PreviousTxnLgrSeq: number + LowNode?: string + HighNode?: string + LowQualityIn?: number + LowQualityOut?: number + HighQualityIn?: number + HighQualityOut?: number } diff --git a/src/models/ledger/signerList.ts b/src/models/ledger/signerList.ts index 800eb529..191fb3a4 100644 --- a/src/models/ledger/signerList.ts +++ b/src/models/ledger/signerList.ts @@ -1,19 +1,19 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' interface SignerEntry { SignerEntry: { - Account: string; - SignerWeight: number; - }; + Account: string + SignerWeight: number + } } export default interface SignerList extends BaseLedgerEntry { - LedgerEntryType: "SignerList"; - Flags: number; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - OwnerNode: string; - SignerEntries: SignerEntry[]; - SignerListID: number; - SignerQuorum: number; + LedgerEntryType: 'SignerList' + Flags: number + PreviousTxnID: string + PreviousTxnLgrSeq: number + OwnerNode: string + SignerEntries: SignerEntry[] + SignerListID: number + SignerQuorum: number } diff --git a/src/models/ledger/ticket.ts b/src/models/ledger/ticket.ts index 636c4a2d..d831f0b8 100644 --- a/src/models/ledger/ticket.ts +++ b/src/models/ledger/ticket.ts @@ -1,11 +1,11 @@ -import BaseLedgerEntry from "./baseLedgerEntry"; +import BaseLedgerEntry from './baseLedgerEntry' export default interface Ticket extends BaseLedgerEntry { - LedgerEntryType: "Ticket"; - Account: string; - Flags: number; - OwnerNode: string; - PreviousTxnID: string; - PreviousTxnLgrSeq: number; - TicketSequence: number; + LedgerEntryType: 'Ticket' + Account: string + Flags: number + OwnerNode: string + PreviousTxnID: string + PreviousTxnLgrSeq: number + TicketSequence: number } diff --git a/src/models/methods/accountChannels.ts b/src/models/methods/accountChannels.ts index 01e06e50..d4d5a99b 100644 --- a/src/models/methods/accountChannels.ts +++ b/src/models/methods/accountChannels.ts @@ -1,40 +1,40 @@ -import { LedgerIndex } from "../common"; +import { LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface Channel { - account: string; - amount: string; - balance: string; - channel_id: string; - destination_account: string; - settle_delay: number; - public_key?: string; - public_key_hex?: string; - expiration?: number; - cancel_after?: number; - source_tab?: number; - destination_tag?: number; + account: string + amount: string + balance: string + channel_id: string + destination_account: string + settle_delay: number + public_key?: string + public_key_hex?: string + expiration?: number + cancel_after?: number + source_tab?: number + destination_tag?: number } export interface AccountChannelsRequest extends BaseRequest { - command: "account_channels"; - account: string; - destination_account?: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; - limit: number; - marker?: unknown; + command: 'account_channels' + account: string + destination_account?: string + ledger_hash?: string + ledger_index?: LedgerIndex + limit: number + marker?: unknown } export interface AccountChannelsResponse extends BaseResponse { result: { - account: string; - channels: Channel[]; - ledger_hash: string; - ledger_index: number; - validated?: boolean; - limit?: number; - marker?: unknown; - }; + account: string + channels: Channel[] + ledger_hash: string + ledger_index: number + validated?: boolean + limit?: number + marker?: unknown + } } diff --git a/src/models/methods/accountCurrencies.ts b/src/models/methods/accountCurrencies.ts index 8aa88834..665e8218 100644 --- a/src/models/methods/accountCurrencies.ts +++ b/src/models/methods/accountCurrencies.ts @@ -1,22 +1,22 @@ -import { LedgerIndex } from "../common"; +import { LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface AccountCurrenciesRequest extends BaseRequest { - command: "account_currencies"; - account: string; - destination_account?: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; - strict?: boolean; + command: 'account_currencies' + account: string + destination_account?: string + ledger_hash?: string + ledger_index?: LedgerIndex + strict?: boolean } export interface AccountCurrenciesResponse extends BaseResponse { result: { - ledger_hash?: string; - ledger_index: number; - receive_currencies: string[]; - send_currencies: string[]; - validated: boolean; - }; + ledger_hash?: string + ledger_index: number + receive_currencies: string[] + send_currencies: string[] + validated: boolean + } } diff --git a/src/models/methods/accountInfo.ts b/src/models/methods/accountInfo.ts index 4a249984..553b545c 100644 --- a/src/models/methods/accountInfo.ts +++ b/src/models/methods/accountInfo.ts @@ -1,42 +1,42 @@ -import { LedgerIndex } from "../common"; -import { AccountRoot, SignerList } from "../ledger"; +import { LedgerIndex } from '../common' +import { AccountRoot, SignerList } from '../ledger' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface AccountInfoRequest extends BaseRequest { - command: "account_info"; - account: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; - queue?: boolean; - signer_lists?: boolean; - strict?: boolean; + command: 'account_info' + account: string + ledger_hash?: string + ledger_index?: LedgerIndex + queue?: boolean + signer_lists?: boolean + strict?: boolean } interface QueueTransaction { - auth_change: boolean; - fee: string; - fee_level: string; - max_spend_drops: string; - seq: number; + auth_change: boolean + fee: string + fee_level: string + max_spend_drops: string + seq: number } interface QueueData { - txn_count: number; - auth_change_queued?: boolean; - lowest_sequence?: number; - highest_sequence?: number; - max_spend_drops_total?: string; - transactions?: QueueTransaction[]; + txn_count: number + auth_change_queued?: boolean + lowest_sequence?: number + highest_sequence?: number + max_spend_drops_total?: string + transactions?: QueueTransaction[] } export interface AccountInfoResponse extends BaseResponse { result: { - account_data: AccountRoot; - signer_lists?: SignerList[]; - ledger_current_index?: number; - ledger_index?: number; - queue_data?: QueueData; - validated?: boolean; - }; + account_data: AccountRoot + signer_lists?: SignerList[] + ledger_current_index?: number + ledger_index?: number + queue_data?: QueueData + validated?: boolean + } } diff --git a/src/models/methods/accountLines.ts b/src/models/methods/accountLines.ts index eef7aeca..d5f69e10 100644 --- a/src/models/methods/accountLines.ts +++ b/src/models/methods/accountLines.ts @@ -1,40 +1,40 @@ -import { LedgerIndex } from "../common"; +import { LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface Trustline { - account: string; - balance: string; - currency: string; - limit: string; - limit_peer: string; - quality_in: number; - quality_out: number; - no_ripple?: boolean; - no_ripple_peer?: boolean; - authorized?: boolean; - peer_authorized?: boolean; - freeze?: boolean; - freeze_peer?: boolean; + account: string + balance: string + currency: string + limit: string + limit_peer: string + quality_in: number + quality_out: number + no_ripple?: boolean + no_ripple_peer?: boolean + authorized?: boolean + peer_authorized?: boolean + freeze?: boolean + freeze_peer?: boolean } export interface AccountLinesRequest extends BaseRequest { - command: "account_lines"; - account: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; - peer?: string; - limit?: number; - marker?: unknown; + command: 'account_lines' + account: string + ledger_hash?: string + ledger_index?: LedgerIndex + peer?: string + limit?: number + marker?: unknown } export interface AccountLinesResponse extends BaseResponse { result: { - account: string; - lines: Trustline[]; - ledger_current_index?: number; - ledger_index?: number; - ledger_hash?: string; - marker?: unknown; - }; + account: string + lines: Trustline[] + ledger_current_index?: number + ledger_index?: number + ledger_hash?: string + marker?: unknown + } } diff --git a/src/models/methods/accountObjects.ts b/src/models/methods/accountObjects.ts index 9671cba2..66af3773 100644 --- a/src/models/methods/accountObjects.ts +++ b/src/models/methods/accountObjects.ts @@ -1,4 +1,4 @@ -import { AccountObjectType, LedgerIndex } from "../common"; +import { AccountObjectType, LedgerIndex } from '../common' import { Check, DepositPreauth, @@ -8,19 +8,19 @@ import { RippleState, SignerList, Ticket, -} from "../ledger"; +} from '../ledger' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface AccountObjectsRequest extends BaseRequest { - command: "account_objects"; - account: string; - type?: AccountObjectType; - deletion_blockers_only?: boolean; - ledger_hash?: string; - ledger_index?: LedgerIndex; - limit?: number; - marker?: unknown; + command: 'account_objects' + account: string + type?: AccountObjectType + deletion_blockers_only?: boolean + ledger_hash?: string + ledger_index?: LedgerIndex + limit?: number + marker?: unknown } type AccountObject = @@ -31,17 +31,17 @@ type AccountObject = | PayChannel | SignerList | Ticket - | RippleState; + | RippleState export interface AccountObjectsResponse extends BaseResponse { result: { - account: string; - account_objects: AccountObject[]; - ledger_hash?: string; - ledger_index?: number; - ledger_current_index?: number; - limit?: number; - marker?: string; - validated?: boolean; - }; + account: string + account_objects: AccountObject[] + ledger_hash?: string + ledger_index?: number + ledger_current_index?: number + limit?: number + marker?: string + validated?: boolean + } } diff --git a/src/models/methods/accountOffers.ts b/src/models/methods/accountOffers.ts index ec1dc030..f40d9cdb 100644 --- a/src/models/methods/accountOffers.ts +++ b/src/models/methods/accountOffers.ts @@ -1,33 +1,33 @@ -import { Amount, LedgerIndex } from "../common"; +import { Amount, LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface AccountOffersRequest extends BaseRequest { - command: "account_offers"; - account: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; - limit?: number; - marker?: unknown; - strict?: boolean; + command: 'account_offers' + account: string + ledger_hash?: string + ledger_index?: LedgerIndex + limit?: number + marker?: unknown + strict?: boolean } interface AccountOffer { - flags: number; - seq: number; - taker_gets: Amount; - taker_pays: Amount; - quality: string; - expiration?: number; + flags: number + seq: number + taker_gets: Amount + taker_pays: Amount + quality: string + expiration?: number } export interface AccountOffersResponse extends BaseResponse { result: { - account: string; - offers?: AccountOffer[]; - ledger_current_index?: number; - ledger_index?: number; - ledger_hash?: string; - marker?: unknown; - }; + account: string + offers?: AccountOffer[] + ledger_current_index?: number + ledger_index?: number + ledger_hash?: string + marker?: unknown + } } diff --git a/src/models/methods/accountTx.ts b/src/models/methods/accountTx.ts index 03842b96..1827c563 100644 --- a/src/models/methods/accountTx.ts +++ b/src/models/methods/accountTx.ts @@ -1,38 +1,38 @@ -import { LedgerIndex } from "../common"; -import { Transaction } from "../transactions"; -import Metadata from "../transactions/metadata"; +import { LedgerIndex } from '../common' +import { Transaction } from '../transactions' +import Metadata from '../transactions/metadata' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface AccountTxRequest extends BaseRequest { - command: "account_tx"; - account: string; - ledger_index_min?: number; - ledger_index_max?: number; - ledger_hash?: string; - ledger_index?: LedgerIndex; - binary?: boolean; - forward?: boolean; - limit?: number; - marker?: unknown; + command: 'account_tx' + account: string + ledger_index_min?: number + ledger_index_max?: number + ledger_hash?: string + ledger_index?: LedgerIndex + binary?: boolean + forward?: boolean + limit?: number + marker?: unknown } interface AccountTransaction { - ledger_index: number; - meta: string | Metadata; - tx?: Transaction; - tx_blob?: string; - validated: boolean; + ledger_index: number + meta: string | Metadata + tx?: Transaction + tx_blob?: string + validated: boolean } export interface AccountTxResponse extends BaseResponse { result: { - account: string; - ledger_index_min: number; - ledger_index_max: number; - limit: number; - marker?: unknown; - transactions: AccountTransaction[]; - validated?: boolean; - }; + account: string + ledger_index_min: number + ledger_index_max: number + limit: number + marker?: unknown + transactions: AccountTransaction[] + validated?: boolean + } } diff --git a/src/models/methods/baseMethod.ts b/src/models/methods/baseMethod.ts index 6e937b24..a00af8f8 100644 --- a/src/models/methods/baseMethod.ts +++ b/src/models/methods/baseMethod.ts @@ -1,27 +1,27 @@ export interface BaseRequest { - [x: string]: unknown; - id?: number | string; - command: string; - api_version?: number; + [x: string]: unknown + id?: number | string + command: string + api_version?: number } interface Warning { - id: number; - message: string; - details?: { [key: string]: string }; + id: number + message: string + details?: { [key: string]: string } } export interface BaseResponse { - id: number | string; - status: "success" | "error" | string; - type: "response" | string; - result: unknown; - warning?: "load"; - warnings?: Warning[]; - forwarded?: boolean; - error?: string; - error_message?: string; + id: number | string + status: 'success' | 'error' | string + type: 'response' | string + result: unknown + warning?: 'load' + warnings?: Warning[] + forwarded?: boolean + error?: string + error_message?: string // TODO: type this better - request?: unknown; - api_version?: number; + request?: unknown + api_version?: number } diff --git a/src/models/methods/bookOffers.ts b/src/models/methods/bookOffers.ts index 3f9381d6..b238c9c1 100644 --- a/src/models/methods/bookOffers.ts +++ b/src/models/methods/bookOffers.ts @@ -1,35 +1,35 @@ -import { Amount, LedgerIndex } from "../common"; -import { Offer } from "../ledger"; +import { Amount, LedgerIndex } from '../common' +import { Offer } from '../ledger' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface TakerAmount { - currency: string; - issuer?: string; + currency: string + issuer?: string } export interface BookOffersRequest extends BaseRequest { - command: "book_offers"; - ledger_hash?: string; - ledger_index?: LedgerIndex; - limit?: number; - taker?: string; - taker_gets: TakerAmount; - taker_pays: TakerAmount; + command: 'book_offers' + ledger_hash?: string + ledger_index?: LedgerIndex + limit?: number + taker?: string + taker_gets: TakerAmount + taker_pays: TakerAmount } interface BookOffer extends Offer { - owner_funds?: string; - taker_gets_funded?: Amount; - taker_pays_funded?: Amount; - quality?: string; + owner_funds?: string + taker_gets_funded?: Amount + taker_pays_funded?: Amount + quality?: string } export interface BookOffersResponse extends BaseResponse { result: { - ledger_current_index?: number; - ledger_index?: number; - ledger_hash?: string; - offers: BookOffer[]; - }; + ledger_current_index?: number + ledger_index?: number + ledger_hash?: string + offers: BookOffer[] + } } diff --git a/src/models/methods/channelVerify.ts b/src/models/methods/channelVerify.ts index c86b39bb..bd6861f8 100644 --- a/src/models/methods/channelVerify.ts +++ b/src/models/methods/channelVerify.ts @@ -1,15 +1,15 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface ChannelVerifyRequest extends BaseRequest { - command: "channel_verify"; - amount: string; - channel_id: string; - public_key: string; - signature: string; + command: 'channel_verify' + amount: string + channel_id: string + public_key: string + signature: string } export interface ChannelVerifyResponse extends BaseResponse { result: { - signature_verified: boolean; - }; + signature_verified: boolean + } } diff --git a/src/models/methods/depositAuthorized.ts b/src/models/methods/depositAuthorized.ts index 94fc5ab9..b10545e8 100644 --- a/src/models/methods/depositAuthorized.ts +++ b/src/models/methods/depositAuthorized.ts @@ -1,23 +1,23 @@ -import { LedgerIndex } from "../common"; +import { LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface DepositAuthorizedRequest extends BaseRequest { - command: "deposit_authorized"; - source_account: string; - destination_account: string; - ledger_hash?: string; - ledger_index?: LedgerIndex; + command: 'deposit_authorized' + source_account: string + destination_account: string + ledger_hash?: string + ledger_index?: LedgerIndex } export interface DepositAuthorizedResponse extends BaseResponse { result: { - deposit_authorized: boolean; - destination_account: string; - ledger_hash?: string; - ledger_index?: number; - ledger_current_index?: number; - source_account: string; - validated?: boolean; - }; + deposit_authorized: boolean + destination_account: string + ledger_hash?: string + ledger_index?: number + ledger_current_index?: number + source_account: string + validated?: boolean + } } diff --git a/src/models/methods/fee.ts b/src/models/methods/fee.ts index aa5c9c61..efca04dd 100644 --- a/src/models/methods/fee.ts +++ b/src/models/methods/fee.ts @@ -1,27 +1,27 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface FeeRequest extends BaseRequest { - command: "fee"; + command: 'fee' } export interface FeeResponse extends BaseResponse { result: { - current_ledger_size: string; - current_queue_size: string; + current_ledger_size: string + current_queue_size: string drops: { - base_fee: string; - median_fee: string; - minimum_fee: string; - open_ledger_fee: string; - }; - expected_ledger_size: string; - ledger_current_index: number; + base_fee: string + median_fee: string + minimum_fee: string + open_ledger_fee: string + } + expected_ledger_size: string + ledger_current_index: number levels: { - median_level: string; - minimum_level: string; - open_ledger_level: string; - reference_level: string; - }; - max_queue_size: string; - }; + median_level: string + minimum_level: string + open_ledger_level: string + reference_level: string + } + max_queue_size: string + } } diff --git a/src/models/methods/gatewayBalances.ts b/src/models/methods/gatewayBalances.ts index a960bb1c..6cf0e720 100644 --- a/src/models/methods/gatewayBalances.ts +++ b/src/models/methods/gatewayBalances.ts @@ -1,29 +1,29 @@ -import { LedgerIndex } from "../common"; +import { LedgerIndex } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface GatewayBalancesRequest extends BaseRequest { - command: "gateway_balances"; - account: string; - strict?: boolean; - hotwallet: string | string[]; - ledger_hash?: string; - ledger_index?: LedgerIndex; + command: 'gateway_balances' + account: string + strict?: boolean + hotwallet: string | string[] + ledger_hash?: string + ledger_index?: LedgerIndex } interface Balance { - currency: string; - value: string; + currency: string + value: string } export interface GatewayBalancesResponse extends BaseResponse { result: { - account: string; - obligations?: { [currency: string]: string }; - balances?: { [address: string]: Balance[] }; - assets?: { [address: string]: Balance[] }; - ledger_hash?: string; - ledger_current_index?: number; - ledger_index?: number; - }; + account: string + obligations?: { [currency: string]: string } + balances?: { [address: string]: Balance[] } + assets?: { [address: string]: Balance[] } + ledger_hash?: string + ledger_current_index?: number + ledger_index?: number + } } diff --git a/src/models/methods/index.ts b/src/models/methods/index.ts index be684cf0..015a16dc 100644 --- a/src/models/methods/index.ts +++ b/src/models/methods/index.ts @@ -3,51 +3,45 @@ import { AccountChannelsRequest, AccountChannelsResponse, -} from "./accountChannels"; +} from './accountChannels' import { AccountCurrenciesRequest, AccountCurrenciesResponse, -} from "./accountCurrencies"; -import { AccountInfoRequest, AccountInfoResponse } from "./accountInfo"; -import { AccountLinesRequest, AccountLinesResponse } from "./accountLines"; -import { - AccountObjectsRequest, - AccountObjectsResponse, -} from "./accountObjects"; -import { AccountOffersRequest, AccountOffersResponse } from "./accountOffers"; -import { AccountTxRequest, AccountTxResponse } from "./accountTx"; -import { BookOffersRequest, BookOffersResponse } from "./bookOffers"; -import { ChannelVerifyRequest, ChannelVerifyResponse } from "./channelVerify"; +} from './accountCurrencies' +import { AccountInfoRequest, AccountInfoResponse } from './accountInfo' +import { AccountLinesRequest, AccountLinesResponse } from './accountLines' +import { AccountObjectsRequest, AccountObjectsResponse } from './accountObjects' +import { AccountOffersRequest, AccountOffersResponse } from './accountOffers' +import { AccountTxRequest, AccountTxResponse } from './accountTx' +import { BookOffersRequest, BookOffersResponse } from './bookOffers' +import { ChannelVerifyRequest, ChannelVerifyResponse } from './channelVerify' import { DepositAuthorizedRequest, DepositAuthorizedResponse, -} from "./depositAuthorized"; -import { FeeRequest, FeeResponse } from "./fee"; +} from './depositAuthorized' +import { FeeRequest, FeeResponse } from './fee' import { GatewayBalancesRequest, GatewayBalancesResponse, -} from "./gatewayBalances"; -import { LedgerRequest, LedgerResponse } from "./ledger"; -import { LedgerClosedRequest, LedgerClosedResponse } from "./ledgerClosed"; -import { LedgerCurrentRequest, LedgerCurrentResponse } from "./ledgerCurrent"; -import { LedgerDataRequest, LedgerDataResponse } from "./ledgerData"; -import { LedgerEntryRequest, LedgerEntryResponse } from "./ledgerEntry"; -import { ManifestRequest, ManifestResponse } from "./manifest"; -import { NoRippleCheckRequest, NoRippleCheckResponse } from "./norippleCheck"; -import { PathFindRequest, PathFindResponse } from "./pathFind"; -import { PingRequest, PingResponse } from "./ping"; -import { RandomRequest, RandomResponse } from "./random"; -import { - RipplePathFindRequest, - RipplePathFindResponse, -} from "./ripplePathFind"; -import { ServerInfoRequest, ServerInfoResponse } from "./serverInfo"; -import { ServerStateRequest, ServerStateResponse } from "./serverState"; -import { SubmitRequest, SubmitResponse } from "./submit"; +} from './gatewayBalances' +import { LedgerRequest, LedgerResponse } from './ledger' +import { LedgerClosedRequest, LedgerClosedResponse } from './ledgerClosed' +import { LedgerCurrentRequest, LedgerCurrentResponse } from './ledgerCurrent' +import { LedgerDataRequest, LedgerDataResponse } from './ledgerData' +import { LedgerEntryRequest, LedgerEntryResponse } from './ledgerEntry' +import { ManifestRequest, ManifestResponse } from './manifest' +import { NoRippleCheckRequest, NoRippleCheckResponse } from './norippleCheck' +import { PathFindRequest, PathFindResponse } from './pathFind' +import { PingRequest, PingResponse } from './ping' +import { RandomRequest, RandomResponse } from './random' +import { RipplePathFindRequest, RipplePathFindResponse } from './ripplePathFind' +import { ServerInfoRequest, ServerInfoResponse } from './serverInfo' +import { ServerStateRequest, ServerStateResponse } from './serverState' +import { SubmitRequest, SubmitResponse } from './submit' import { SubmitMultisignedRequest, SubmitMultisignedResponse, -} from "./submitMultisigned"; +} from './submitMultisigned' import { ConsensusStream, LedgerStream, @@ -58,13 +52,13 @@ import { SubscribeResponse, TransactionStream, ValidationStream, -} from "./subscribe"; +} from './subscribe' import { TransactionEntryRequest, TransactionEntryResponse, -} from "./transactionEntry"; -import { TxRequest, TxResponse } from "./tx"; -import { UnsubscribeRequest, UnsubscribeResponse } from "./unsubscribe"; +} from './transactionEntry' +import { TxRequest, TxResponse } from './tx' +import { UnsubscribeRequest, UnsubscribeResponse } from './unsubscribe' // account methods type Request = @@ -105,7 +99,7 @@ type Request = | ServerStateRequest // utility methods | PingRequest - | RandomRequest; + | RandomRequest // account methods type Response = @@ -146,7 +140,7 @@ type Response = | ServerStateResponse // utility methods | PingResponse - | RandomResponse; + | RandomResponse export { Request, @@ -228,4 +222,4 @@ export { PingResponse, RandomRequest, RandomResponse, -}; +} diff --git a/src/models/methods/ledger.ts b/src/models/methods/ledger.ts index 8d5ac421..2af7a363 100644 --- a/src/models/methods/ledger.ts +++ b/src/models/methods/ledger.ts @@ -1,59 +1,59 @@ -import { LedgerIndex } from "../common"; -import { Ledger } from "../ledger"; -import { Transaction, TransactionAndMetadata } from "../transactions"; -import TransactionMetadata from "../transactions/metadata"; +import { LedgerIndex } from '../common' +import { Ledger } from '../ledger' +import { Transaction, TransactionAndMetadata } from '../transactions' +import TransactionMetadata from '../transactions/metadata' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface LedgerRequest extends BaseRequest { - command: "ledger"; - ledger_hash?: string; - ledger_index?: LedgerIndex; - full?: boolean; - accounts?: boolean; - transactions?: boolean; - expand?: boolean; - owner_funds?: boolean; - binary?: boolean; - queue?: boolean; + command: 'ledger' + ledger_hash?: string + ledger_index?: LedgerIndex + full?: boolean + accounts?: boolean + transactions?: boolean + expand?: boolean + owner_funds?: boolean + binary?: boolean + queue?: boolean } interface ModifiedMetadata extends TransactionMetadata { - owner_funds: string; + owner_funds: string } interface ModifiedOfferCreateTransaction { - transaction: Transaction; - metadata: ModifiedMetadata; + transaction: Transaction + metadata: ModifiedMetadata } interface LedgerQueueData { - account: string; + account: string tx: | TransactionAndMetadata | ModifiedOfferCreateTransaction - | { tx_blob: string }; - retries_remaining: number; - preflight_result: string; - last_result?: string; - auth_change?: boolean; - fee?: string; - fee_level?: string; - max_spend_drops?: string; + | { tx_blob: string } + retries_remaining: number + preflight_result: string + last_result?: string + auth_change?: boolean + fee?: string + fee_level?: string + max_spend_drops?: string } interface BinaryLedger - extends Omit, "accountState"> { - accountState?: string[]; - transactions?: string[]; + extends Omit, 'accountState'> { + accountState?: string[] + transactions?: string[] } export interface LedgerResponse extends BaseResponse { result: { - ledger: Ledger | BinaryLedger; - ledger_hash: string; - ledger_index: number; - queue_data?: Array; - validated?: boolean; - }; + ledger: Ledger | BinaryLedger + ledger_hash: string + ledger_index: number + queue_data?: Array + validated?: boolean + } } diff --git a/src/models/methods/ledgerClosed.ts b/src/models/methods/ledgerClosed.ts index bf89459a..e33cd47e 100644 --- a/src/models/methods/ledgerClosed.ts +++ b/src/models/methods/ledgerClosed.ts @@ -1,12 +1,12 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface LedgerClosedRequest extends BaseRequest { - command: "ledger_closed"; + command: 'ledger_closed' } export interface LedgerClosedResponse extends BaseResponse { result: { - ledger_hash: string; - ledger_index: number; - }; + ledger_hash: string + ledger_index: number + } } diff --git a/src/models/methods/ledgerCurrent.ts b/src/models/methods/ledgerCurrent.ts index 1507ff78..882ff05a 100644 --- a/src/models/methods/ledgerCurrent.ts +++ b/src/models/methods/ledgerCurrent.ts @@ -1,11 +1,11 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface LedgerCurrentRequest extends BaseRequest { - command: "ledger_current"; + command: 'ledger_current' } export interface LedgerCurrentResponse extends BaseResponse { result: { - ledger_current_index: number; - }; + ledger_current_index: number + } } diff --git a/src/models/methods/ledgerData.ts b/src/models/methods/ledgerData.ts index 286d6a2e..2d3b017b 100644 --- a/src/models/methods/ledgerData.ts +++ b/src/models/methods/ledgerData.ts @@ -1,30 +1,30 @@ -import { LedgerIndex } from "../common"; -import { LedgerEntry } from "../ledger"; +import { LedgerIndex } from '../common' +import { LedgerEntry } from '../ledger' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface LedgerDataRequest extends BaseRequest { - command: "ledger_data"; - ledger_hash?: string; - ledger_index?: LedgerIndex; - binary?: boolean; - limit?: number; - marker?: unknown; + command: 'ledger_data' + ledger_hash?: string + ledger_index?: LedgerIndex + binary?: boolean + limit?: number + marker?: unknown } -type LabeledLedgerEntry = { ledgerEntryType: string } & LedgerEntry; +type LabeledLedgerEntry = { ledgerEntryType: string } & LedgerEntry interface BinaryLedgerEntry { - data: string; + data: string } -type State = { index: string } & (BinaryLedgerEntry | LabeledLedgerEntry); +type State = { index: string } & (BinaryLedgerEntry | LabeledLedgerEntry) export interface LedgerDataResponse extends BaseResponse { result: { - ledger_index: number; - ledger_hash: string; - state: State[]; - marker?: unknown; - }; + ledger_index: number + ledger_hash: string + state: State[] + marker?: unknown + } } diff --git a/src/models/methods/ledgerEntry.ts b/src/models/methods/ledgerEntry.ts index 3c015a6c..a0c48a66 100644 --- a/src/models/methods/ledgerEntry.ts +++ b/src/models/methods/ledgerEntry.ts @@ -1,72 +1,72 @@ -import { LedgerIndex } from "../common"; -import { LedgerEntry } from "../ledger"; +import { LedgerIndex } from '../common' +import { LedgerEntry } from '../ledger' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface LedgerEntryRequest extends BaseRequest { - command: "ledger_entry"; - binary?: boolean; - ledger_hash?: string; - ledger_index?: LedgerIndex; + command: 'ledger_entry' + binary?: boolean + ledger_hash?: string + ledger_index?: LedgerIndex // Only one of the following properties should be defined in a single request // https://xrpl.org/ledger_entry.html - index?: string; + index?: string - account_root?: string; + account_root?: string directory?: | { - sub_index?: number; - dir_root?: string; - owner?: string; + sub_index?: number + dir_root?: string + owner?: string } - | string; + | string offer?: | { - account: string; - seq: number; + account: string + seq: number } - | string; + | string ripple_state?: { - accounts: string[]; - currency: string; - }; + accounts: string[] + currency: string + } - check?: string; + check?: string escrow?: | { - owner: string; - seq: number; + owner: string + seq: number } - | string; + | string - payment_channel?: string; + payment_channel?: string deposit_preauth?: | { - owner: string; - authorized: string; + owner: string + authorized: string } - | string; + | string ticket?: | { - owner: string; - ticket_sequence: number; + owner: string + ticket_sequence: number } - | string; + | string } export interface LedgerEntryResponse extends BaseResponse { result: { - index: string; - ledger_index: number; - node?: LedgerEntry; - node_binary?: string; - }; + index: string + ledger_index: number + node?: LedgerEntry + node_binary?: string + } } diff --git a/src/models/methods/manifest.ts b/src/models/methods/manifest.ts index 0081fb5c..d6df13d0 100644 --- a/src/models/methods/manifest.ts +++ b/src/models/methods/manifest.ts @@ -1,19 +1,19 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface ManifestRequest extends BaseRequest { - command: "manifest"; - public_key: string; + command: 'manifest' + public_key: string } export interface ManifestResponse extends BaseResponse { result: { details?: { - domain: string; - ephemeral_key: string; - master_key: string; - seq: number; - }; - manifest?: string; - requested: string; - }; + domain: string + ephemeral_key: string + master_key: string + seq: number + } + manifest?: string + requested: string + } } diff --git a/src/models/methods/norippleCheck.ts b/src/models/methods/norippleCheck.ts index 31b76207..56d3ffcf 100644 --- a/src/models/methods/norippleCheck.ts +++ b/src/models/methods/norippleCheck.ts @@ -1,21 +1,21 @@ -import { LedgerIndex } from "../common"; -import { Transaction } from "../transactions"; +import { LedgerIndex } from '../common' +import { Transaction } from '../transactions' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface NoRippleCheckRequest extends BaseRequest { - command: "noripple_check"; - account: string; - role: "gateway" | "user"; - transactions?: boolean; - ledger_hash?: string; - ledger_index?: LedgerIndex; + command: 'noripple_check' + account: string + role: 'gateway' | 'user' + transactions?: boolean + ledger_hash?: string + ledger_index?: LedgerIndex } export interface NoRippleCheckResponse extends BaseResponse { result: { - ledger_current_index: number; - problems: string[]; - transactions: Transaction[]; - }; + ledger_current_index: number + problems: string[] + transactions: Transaction[] + } } diff --git a/src/models/methods/pathFind.ts b/src/models/methods/pathFind.ts index c8f7ec3a..60dd5928 100644 --- a/src/models/methods/pathFind.ts +++ b/src/models/methods/pathFind.ts @@ -1,50 +1,50 @@ -import { Amount, Path } from "../common"; +import { Amount, Path } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface BasePathFindRequest extends BaseRequest { - command: "path_find"; - subcommand: string; + command: 'path_find' + subcommand: string } interface PathFindCreateRequest extends BasePathFindRequest { - subcommand: "create"; - source_account: string; - destination_account: string; - destination_amount: Amount; - send_max?: Amount; - paths?: Path[]; + subcommand: 'create' + source_account: string + destination_account: string + destination_amount: Amount + send_max?: Amount + paths?: Path[] } interface PathFindCloseRequest extends BasePathFindRequest { - subcommand: "close"; + subcommand: 'close' } interface PathFindStatusRequest extends BasePathFindRequest { - subcommand: "status"; + subcommand: 'status' } export type PathFindRequest = | PathFindCreateRequest | PathFindCloseRequest - | PathFindStatusRequest; + | PathFindStatusRequest interface PathOption { - paths_computed: Path[]; - source_amount: Amount; + paths_computed: Path[] + source_amount: Amount } export interface PathFindResponse extends BaseResponse { result: { - alternatives: PathOption[]; - destination_account: string; - destination_amount: Amount; - source_account: string; - full_reply: boolean; - id?: number | string; - closed?: true; - status?: true; - }; + alternatives: PathOption[] + destination_account: string + destination_amount: Amount + source_account: string + full_reply: boolean + id?: number | string + closed?: true + status?: true + } } // TODO: figure out where to put the path_find asynchronous follow-ups diff --git a/src/models/methods/ping.ts b/src/models/methods/ping.ts index 42eb00b7..84711b44 100644 --- a/src/models/methods/ping.ts +++ b/src/models/methods/ping.ts @@ -1,11 +1,11 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface PingRequest extends BaseRequest { - command: "ping"; + command: 'ping' } export interface PingResponse extends BaseResponse { // TODO: figure out if there's a better way to type this // eslint-disable-next-line @typescript-eslint/ban-types -- actually should be an empty object - result: {}; + result: {} } diff --git a/src/models/methods/random.ts b/src/models/methods/random.ts index af00c3d6..ae3ec141 100644 --- a/src/models/methods/random.ts +++ b/src/models/methods/random.ts @@ -1,11 +1,11 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface RandomRequest extends BaseRequest { - command: "random"; + command: 'random' } export interface RandomResponse extends BaseResponse { result: { - random: string; - }; + random: string + } } diff --git a/src/models/methods/ripplePathFind.ts b/src/models/methods/ripplePathFind.ts index d4c5e99f..fc218297 100644 --- a/src/models/methods/ripplePathFind.ts +++ b/src/models/methods/ripplePathFind.ts @@ -1,32 +1,32 @@ -import { Amount, LedgerIndex, Path } from "../common"; +import { Amount, LedgerIndex, Path } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface SourceCurrencyAmount { - currency: string; - issuer?: string; + currency: string + issuer?: string } export interface RipplePathFindRequest extends BaseRequest { - command: "ripple_path_find"; - source_account: string; - destination_account: string; - destination_amount: Amount; - send_max?: Amount; - source_currencies?: SourceCurrencyAmount; - ledger_hash?: string; - ledger_index?: LedgerIndex; + command: 'ripple_path_find' + source_account: string + destination_account: string + destination_amount: Amount + send_max?: Amount + source_currencies?: SourceCurrencyAmount + ledger_hash?: string + ledger_index?: LedgerIndex } interface PathOption { - paths_computed: Path[]; - source_amount: Amount; + paths_computed: Path[] + source_amount: Amount } export interface RipplePathFindResponse extends BaseResponse { result: { - alternatives: PathOption[]; - destination_account: string; - destination_currencies: string[]; - }; + alternatives: PathOption[] + destination_account: string + destination_currencies: string[] + } } diff --git a/src/models/methods/serverInfo.ts b/src/models/methods/serverInfo.ts index c7ed1879..27127808 100644 --- a/src/models/methods/serverInfo.ts +++ b/src/models/methods/serverInfo.ts @@ -1,82 +1,82 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface ServerInfoRequest extends BaseRequest { - command: "server_info"; + command: 'server_info' } export type ServerState = - | "disconnected" - | "connected" - | "syncing" - | "tracking" - | "full" - | "validating" - | "proposing"; + | 'disconnected' + | 'connected' + | 'syncing' + | 'tracking' + | 'full' + | 'validating' + | 'proposing' export interface StateAccounting { - duration_us: string; - transitions: number; + duration_us: string + transitions: number } export interface JobType { - job_type: string; - per_second: number; - peak_time?: number; - avg_time?: number; - in_progress?: number; + job_type: string + per_second: number + peak_time?: number + avg_time?: number + in_progress?: number } export interface ServerInfoResponse extends BaseResponse { result: { info: { - amendment_blocked?: boolean; - build_version: string; + amendment_blocked?: boolean + build_version: string closed_ledger?: { - age: number; - base_fee_xrp: number; - hash: string; - reserve_base_xrp: number; - reserve_inc_xrp: number; - seq: number; - }; - complete_ledgers: string; - hostid: string; - io_latency_ms: number; - jq_trans_overflow: string; + age: number + base_fee_xrp: number + hash: string + reserve_base_xrp: number + reserve_inc_xrp: number + seq: number + } + complete_ledgers: string + hostid: string + io_latency_ms: number + jq_trans_overflow: string last_close: { - converge_time_s: number; - proposers: number; - }; + converge_time_s: number + proposers: number + } load?: { - job_types: JobType[]; - threads: number; - }; - load_factor: number; - load_factor_local?: number; - load_factor_net?: number; - load_factor_cluster?: number; - load_factor_fee_escalation?: number; - load_factor_fee_queue?: number; - load_factor_server?: number; - network_ledger?: "waiting"; - peers: number; - pubkey_node: string; - pubkey_validator?: string; - server_state: ServerState; - server_state_duration_us: number; - state_accounting: Record; - time: string; - uptime: number; + job_types: JobType[] + threads: number + } + load_factor: number + load_factor_local?: number + load_factor_net?: number + load_factor_cluster?: number + load_factor_fee_escalation?: number + load_factor_fee_queue?: number + load_factor_server?: number + network_ledger?: 'waiting' + peers: number + pubkey_node: string + pubkey_validator?: string + server_state: ServerState + server_state_duration_us: number + state_accounting: Record + time: string + uptime: number validated_ledger?: { - age: number; - base_fee_xrp: number; - hash: string; - reserve_base_xrp: number; - reserve_inc_xrp: number; - seq: number; - }; - validation_quorum: number; - validator_list_expires?: string; - }; - }; + age: number + base_fee_xrp: number + hash: string + reserve_base_xrp: number + reserve_inc_xrp: number + seq: number + } + validation_quorum: number + validator_list_expires?: string + } + } } diff --git a/src/models/methods/serverState.ts b/src/models/methods/serverState.ts index 20969a87..eac233e7 100644 --- a/src/models/methods/serverState.ts +++ b/src/models/methods/serverState.ts @@ -1,57 +1,57 @@ -import { BaseRequest, BaseResponse } from "./baseMethod"; -import { JobType, ServerState, StateAccounting } from "./serverInfo"; +import { BaseRequest, BaseResponse } from './baseMethod' +import { JobType, ServerState, StateAccounting } from './serverInfo' export interface ServerStateRequest extends BaseRequest { - command: "server_state"; + command: 'server_state' } export interface ServerStateResponse extends BaseResponse { result: { state: { - amendment_blocked?: boolean; - build_version: string; - complete_ledgers: string; + amendment_blocked?: boolean + build_version: string + complete_ledgers: string closed_ledger?: { - age: number; - base_fee: number; - hash: string; - reserve_base: number; - reserve_inc: number; - seq: number; - }; - io_latency_ms: number; - jq_trans_overflow: string; + age: number + base_fee: number + hash: string + reserve_base: number + reserve_inc: number + seq: number + } + io_latency_ms: number + jq_trans_overflow: string last_close: { - converge_time_s: number; - proposers: number; - }; + converge_time_s: number + proposers: number + } load?: { - job_types: JobType[]; - threads: number; - }; - load_base: number; - load_factor: number; - load_factor_fee_escalation?: number; - load_factor_fee_queue?: number; - load_factor_fee_reference?: number; - load_factor_server?: number; - peers: number; - pubkey_node: string; - pubkey_validator?: string; - server_state: ServerState; - server_state_duration_us: number; - state_accounting: Record; - time: string; - uptime: number; + job_types: JobType[] + threads: number + } + load_base: number + load_factor: number + load_factor_fee_escalation?: number + load_factor_fee_queue?: number + load_factor_fee_reference?: number + load_factor_server?: number + peers: number + pubkey_node: string + pubkey_validator?: string + server_state: ServerState + server_state_duration_us: number + state_accounting: Record + time: string + uptime: number validated_ledger?: { - age: number; - base_fee: number; - hash: string; - reserve_base: number; - reserve_inc: number; - seq: number; - }; - validation_quorum: number; - validator_list_expires?: string; - }; - }; + age: number + base_fee: number + hash: string + reserve_base: number + reserve_inc: number + seq: number + } + validation_quorum: number + validator_list_expires?: string + } + } } diff --git a/src/models/methods/submit.ts b/src/models/methods/submit.ts index 6ba465e1..da1ab1b2 100644 --- a/src/models/methods/submit.ts +++ b/src/models/methods/submit.ts @@ -1,28 +1,28 @@ -import { Transaction } from "../transactions"; +import { Transaction } from '../transactions' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface SubmitRequest extends BaseRequest { - command: "submit"; - tx_blob: string; - fail_hard?: boolean; + command: 'submit' + tx_blob: string + fail_hard?: boolean } export interface SubmitResponse extends BaseResponse { result: { - engine_result: string; - engine_result_code: number; - engine_result_message: string; - tx_blob: string; - tx_json: Transaction; - accepted: boolean; - account_sequence_available: number; - account_sequence_next: number; - applied: boolean; - broadcast: boolean; - kept: boolean; - queued: boolean; - open_ledger_cost: string; - validated_ledger_index: number; - }; + engine_result: string + engine_result_code: number + engine_result_message: string + tx_blob: string + tx_json: Transaction + accepted: boolean + account_sequence_available: number + account_sequence_next: number + applied: boolean + broadcast: boolean + kept: boolean + queued: boolean + open_ledger_cost: string + validated_ledger_index: number + } } diff --git a/src/models/methods/submitMultisigned.ts b/src/models/methods/submitMultisigned.ts index 7b5e4f3f..50113c4f 100644 --- a/src/models/methods/submitMultisigned.ts +++ b/src/models/methods/submitMultisigned.ts @@ -1,19 +1,19 @@ -import { Transaction } from "../transactions"; +import { Transaction } from '../transactions' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface SubmitMultisignedRequest extends BaseRequest { - command: "submit_multisigned"; - tx_json: Transaction; - fail_hard?: boolean; + command: 'submit_multisigned' + tx_json: Transaction + fail_hard?: boolean } export interface SubmitMultisignedResponse extends BaseResponse { result: { - engine_result: string; - engine_result_code: number; - engine_result_message: string; - tx_blob: string; - tx_json: Transaction; - }; + engine_result: string + engine_result_code: number + engine_result_message: string + tx_blob: string + tx_json: Transaction + } } diff --git a/src/models/methods/subscribe.ts b/src/models/methods/subscribe.ts index 81f8fa65..d3a3c6d7 100644 --- a/src/models/methods/subscribe.ts +++ b/src/models/methods/subscribe.ts @@ -1,118 +1,114 @@ -import { OfferCreateTransaction } from "../../common/types/objects"; -import { Currency, StreamType } from "../common"; -import { Transaction } from "../transactions"; -import TransactionMetadata from "../transactions/metadata"; +import { OfferCreateTransaction } from '../../common/types/objects' +import { Currency, StreamType } from '../common' +import { Transaction } from '../transactions' +import TransactionMetadata from '../transactions/metadata' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface Book { - taker_gets: Currency; - taker_pays: Currency; - taker: string; - snapshot?: boolean; - both?: boolean; + taker_gets: Currency + taker_pays: Currency + taker: string + snapshot?: boolean + both?: boolean } export interface SubscribeRequest extends BaseRequest { - command: "subscribe"; - streams?: StreamType[]; - accounts?: string[]; - accounts_proposed?: string[]; - books?: Book[]; - url?: string; - url_username?: string; - url_password?: string; + command: 'subscribe' + streams?: StreamType[] + accounts?: string[] + accounts_proposed?: string[] + books?: Book[] + url?: string + url_username?: string + url_password?: string } export interface SubscribeResponse extends BaseResponse { // TODO: figure out if there's a better way to type this // eslint-disable-next-line @typescript-eslint/ban-types -- actually should be an empty object - result: {} | Stream; + result: {} | Stream } interface BaseStream { - type: string; + type: string } export interface LedgerStream extends BaseStream { - type: "ledgerClosed"; - fee_base: number; - fee_ref: number; - ledger_hash: string; - ledger_index: number; - ledger_time: number; - reserve_base: number; - reserve_inc: number; - txn_count: number; - validated_ledgers?: string; + type: 'ledgerClosed' + fee_base: number + fee_ref: number + ledger_hash: string + ledger_index: number + ledger_time: number + reserve_base: number + reserve_inc: number + txn_count: number + validated_ledgers?: string } export interface ValidationStream extends BaseStream { - type: "validationReceived"; - amendments?: string[]; - base_fee?: number; - flags: number; - full: boolean; - ledger_hash: string; - ledger_index: string; - load_fee?: number; - master_key?: string; - reserve_base?: number; - reserve_inc?: number; - signature: string; - signing_time: number; - validation_public_key: string; + type: 'validationReceived' + amendments?: string[] + base_fee?: number + flags: number + full: boolean + ledger_hash: string + ledger_index: string + load_fee?: number + master_key?: string + reserve_base?: number + reserve_inc?: number + signature: string + signing_time: number + validation_public_key: string } export interface TransactionStream extends BaseStream { - status: string; - type: "transaction"; - engine_result: string; - engine_result_code: number; - engine_result_message: string; - ledger_current_index?: number; - ledger_hash?: string; - ledger_index?: number; - meta?: TransactionMetadata; - transaction: Transaction; - validated?: boolean; + status: string + type: 'transaction' + engine_result: string + engine_result_code: number + engine_result_message: string + ledger_current_index?: number + ledger_hash?: string + ledger_index?: number + meta?: TransactionMetadata + transaction: Transaction + validated?: boolean } export interface PeerStatusStream extends BaseStream { - type: "peerStatusChange"; - action: - | "CLOSING_LEDGER" - | "ACCEPTED_LEDGER" - | "SWITCHED_LEDGER" - | "LOST_SYNC"; - date: number; - ledger_hash?: string; - ledger_index?: number; - ledger_index_max?: number; - ledger_index_min?: number; + type: 'peerStatusChange' + action: 'CLOSING_LEDGER' | 'ACCEPTED_LEDGER' | 'SWITCHED_LEDGER' | 'LOST_SYNC' + date: number + ledger_hash?: string + ledger_index?: number + ledger_index_max?: number + ledger_index_min?: number } interface ModifiedOfferCreateTransaction extends OfferCreateTransaction { - owner_funds: string; + owner_funds: string } export interface OrderBookStream extends BaseStream { - status: string; - type: "transaction"; - engine_result: string; - engine_result_code: number; - engine_result_message: string; - ledger_current_index?: number; - ledger_hash?: string; - ledger_index?: number; - meta: TransactionMetadata; - transaction: Transaction | ModifiedOfferCreateTransaction; - validated: boolean; + status: string + type: 'transaction' + engine_result: string + engine_result_code: number + engine_result_message: string + ledger_current_index?: number + ledger_hash?: string + ledger_index?: number + meta: TransactionMetadata + transaction: Transaction | ModifiedOfferCreateTransaction + validated: boolean } export interface ConsensusStream extends BaseStream { - type: "consensusPhase"; - consensus: "open" | "establish" | "accepted"; + type: 'consensusPhase' + consensus: 'open' | 'establish' | 'accepted' } export type Stream = @@ -121,4 +117,4 @@ export type Stream = | TransactionStream | PeerStatusStream | OrderBookStream - | ConsensusStream; + | ConsensusStream diff --git a/src/models/methods/transactionEntry.ts b/src/models/methods/transactionEntry.ts index ec74ae7f..2c808656 100644 --- a/src/models/methods/transactionEntry.ts +++ b/src/models/methods/transactionEntry.ts @@ -1,21 +1,21 @@ -import { LedgerIndex } from "../common"; -import { Transaction } from "../transactions"; -import TransactionMetadata from "../transactions/metadata"; +import { LedgerIndex } from '../common' +import { Transaction } from '../transactions' +import TransactionMetadata from '../transactions/metadata' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface TransactionEntryRequest extends BaseRequest { - command: "transaction_entry"; - ledger_hash?: string; - ledger_index?: LedgerIndex; - tx_hash: string; + command: 'transaction_entry' + ledger_hash?: string + ledger_index?: LedgerIndex + tx_hash: string } export interface TransactionEntryResponse extends BaseResponse { result: { - ledger_hash: string; - ledger_index: number; - metadata: TransactionMetadata; - tx_json: Transaction; - }; + ledger_hash: string + ledger_index: number + metadata: TransactionMetadata + tx_json: Transaction + } } diff --git a/src/models/methods/tx.ts b/src/models/methods/tx.ts index 03a61640..abc5141d 100644 --- a/src/models/methods/tx.ts +++ b/src/models/methods/tx.ts @@ -1,22 +1,22 @@ -import { Transaction } from "../transactions"; -import TransactionMetadata from "../transactions/metadata"; +import { Transaction } from '../transactions' +import TransactionMetadata from '../transactions/metadata' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' export interface TxRequest extends BaseRequest { - command: "tx"; - transaction: string; - binary?: boolean; - min_ledger?: number; - max_ledger?: number; + command: 'tx' + transaction: string + binary?: boolean + min_ledger?: number + max_ledger?: number } export interface TxResponse extends BaseResponse { result: { - hash: string; - ledger_index: number; - meta: TransactionMetadata | string; - validated?: boolean; - } & Transaction; - searched_all?: boolean; + hash: string + ledger_index: number + meta: TransactionMetadata | string + validated?: boolean + } & Transaction + searched_all?: boolean } diff --git a/src/models/methods/unsubscribe.ts b/src/models/methods/unsubscribe.ts index 4c77cad2..5fc3a339 100644 --- a/src/models/methods/unsubscribe.ts +++ b/src/models/methods/unsubscribe.ts @@ -1,23 +1,23 @@ -import { Currency, StreamType } from "../common"; +import { Currency, StreamType } from '../common' -import { BaseRequest, BaseResponse } from "./baseMethod"; +import { BaseRequest, BaseResponse } from './baseMethod' interface Book { - taker_gets: Currency; - taker_pays: Currency; - both?: boolean; + taker_gets: Currency + taker_pays: Currency + both?: boolean } export interface UnsubscribeRequest extends BaseRequest { - command: "unsubscribe"; - streams?: StreamType[]; - accounts?: string[]; - accounts_proposed?: string[]; - books?: Book[]; + command: 'unsubscribe' + streams?: StreamType[] + accounts?: string[] + accounts_proposed?: string[] + books?: Book[] } export interface UnsubscribeResponse extends BaseResponse { // TODO: figure out if there's a better way to type this // eslint-disable-next-line @typescript-eslint/ban-types -- actually should be an empty object - result: {}; + result: {} } diff --git a/src/models/transactions/accountDelete.ts b/src/models/transactions/accountDelete.ts index 97ec4f49..19ce1bfa 100644 --- a/src/models/transactions/accountDelete.ts +++ b/src/models/transactions/accountDelete.ts @@ -1,11 +1,11 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface AccountDelete extends BaseTransaction { - TransactionType: "AccountDelete"; - Destination: string; - DestinationTag?: number; + TransactionType: 'AccountDelete' + Destination: string + DestinationTag?: number } /** @@ -15,20 +15,20 @@ export interface AccountDelete extends BaseTransaction { * @throws When the AccountDelete is Malformed. */ export function verifyAccountDelete(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Destination === undefined) { - throw new ValidationError("AccountDelete: missing field Destination"); + throw new ValidationError('AccountDelete: missing field Destination') } - if (typeof tx.Destination !== "string") { - throw new ValidationError("AccountDelete: invalid Destination"); + if (typeof tx.Destination !== 'string') { + throw new ValidationError('AccountDelete: invalid Destination') } if ( tx.DestinationTag !== undefined && - typeof tx.DestinationTag !== "number" + typeof tx.DestinationTag !== 'number' ) { - throw new ValidationError("AccountDelete: invalid DestinationTag"); + throw new ValidationError('AccountDelete: invalid DestinationTag') } } diff --git a/src/models/transactions/accountSet.ts b/src/models/transactions/accountSet.ts index 1d77865f..2861fb0b 100644 --- a/src/models/transactions/accountSet.ts +++ b/src/models/transactions/accountSet.ts @@ -1,7 +1,7 @@ /* eslint-disable complexity -- Necessary for verifyAccountSet */ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' enum AccountSetFlagEnum { asfRequireDest = 1, @@ -16,18 +16,18 @@ enum AccountSetFlagEnum { } export interface AccountSet extends BaseTransaction { - TransactionType: "AccountSet"; - ClearFlag?: number; - Domain?: string; - EmailHash?: string; - MessageKey?: string; - SetFlag?: AccountSetFlagEnum; - TransferRate?: number; - TickSize?: number; + TransactionType: 'AccountSet' + ClearFlag?: number + Domain?: string + EmailHash?: string + MessageKey?: string + SetFlag?: AccountSetFlagEnum + TransferRate?: number + TickSize?: number } -const MIN_TICK_SIZE = 3; -const MAX_TICK_SIZE = 15; +const MIN_TICK_SIZE = 3 +const MAX_TICK_SIZE = 15 /** * Verify the form and type of an AccountSet at runtime. @@ -36,51 +36,51 @@ const MAX_TICK_SIZE = 15; * @throws When the AccountSet is Malformed. */ export function verifyAccountSet(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.ClearFlag !== undefined) { - if (typeof tx.ClearFlag !== "number") { - throw new ValidationError("AccountSet: invalid ClearFlag"); + if (typeof tx.ClearFlag !== 'number') { + throw new ValidationError('AccountSet: invalid ClearFlag') } if (!Object.values(AccountSetFlagEnum).includes(tx.ClearFlag)) { - throw new ValidationError("AccountSet: invalid ClearFlag"); + throw new ValidationError('AccountSet: invalid ClearFlag') } } - if (tx.Domain !== undefined && typeof tx.Domain !== "string") { - throw new ValidationError("AccountSet: invalid Domain"); + if (tx.Domain !== undefined && typeof tx.Domain !== 'string') { + throw new ValidationError('AccountSet: invalid Domain') } - if (tx.EmailHash !== undefined && typeof tx.EmailHash !== "string") { - throw new ValidationError("AccountSet: invalid EmailHash"); + if (tx.EmailHash !== undefined && typeof tx.EmailHash !== 'string') { + throw new ValidationError('AccountSet: invalid EmailHash') } - if (tx.MessageKey !== undefined && typeof tx.MessageKey !== "string") { - throw new ValidationError("AccountSet: invalid MessageKey"); + if (tx.MessageKey !== undefined && typeof tx.MessageKey !== 'string') { + throw new ValidationError('AccountSet: invalid MessageKey') } if (tx.SetFlag !== undefined) { - if (typeof tx.SetFlag !== "number") { - throw new ValidationError("AccountSet: invalid SetFlag"); + if (typeof tx.SetFlag !== 'number') { + throw new ValidationError('AccountSet: invalid SetFlag') } if (!Object.values(AccountSetFlagEnum).includes(tx.SetFlag)) { - throw new ValidationError("AccountSet: invalid SetFlag"); + throw new ValidationError('AccountSet: invalid SetFlag') } } - if (tx.TransferRate !== undefined && typeof tx.TransferRate !== "number") { - throw new ValidationError("AccountSet: invalid TransferRate"); + if (tx.TransferRate !== undefined && typeof tx.TransferRate !== 'number') { + throw new ValidationError('AccountSet: invalid TransferRate') } if (tx.TickSize !== undefined) { - if (typeof tx.TickSize !== "number") { - throw new ValidationError("AccountSet: invalid TickSize"); + if (typeof tx.TickSize !== 'number') { + throw new ValidationError('AccountSet: invalid TickSize') } if ( tx.TickSize !== 0 && (tx.TickSize < MIN_TICK_SIZE || tx.TickSize > MAX_TICK_SIZE) ) { - throw new ValidationError("AccountSet: invalid TickSize"); + throw new ValidationError('AccountSet: invalid TickSize') } } } diff --git a/src/models/transactions/checkCancel.ts b/src/models/transactions/checkCancel.ts index cd851ef1..7ed859f5 100644 --- a/src/models/transactions/checkCancel.ts +++ b/src/models/transactions/checkCancel.ts @@ -1,10 +1,10 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface CheckCancel extends BaseTransaction { - TransactionType: "CheckCancel"; - CheckID: string; + TransactionType: 'CheckCancel' + CheckID: string } /** @@ -14,9 +14,9 @@ export interface CheckCancel extends BaseTransaction { * @throws When the CheckCancel is Malformed. */ export function verifyCheckCancel(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) - if (tx.CheckID !== undefined && typeof tx.CheckID !== "string") { - throw new ValidationError("CheckCancel: invalid CheckID"); + if (tx.CheckID !== undefined && typeof tx.CheckID !== 'string') { + throw new ValidationError('CheckCancel: invalid CheckID') } } diff --git a/src/models/transactions/checkCash.ts b/src/models/transactions/checkCash.ts index cb32bc33..b203e817 100644 --- a/src/models/transactions/checkCash.ts +++ b/src/models/transactions/checkCash.ts @@ -1,14 +1,14 @@ /* eslint-disable complexity -- Necessary for verifyCheckCash */ -import { ValidationError } from "../../common/errors"; -import { Amount } from "../common"; +import { ValidationError } from '../../common/errors' +import { Amount } from '../common' -import { BaseTransaction, verifyBaseTransaction, isAmount } from "./common"; +import { BaseTransaction, verifyBaseTransaction, isAmount } from './common' export interface CheckCash extends BaseTransaction { - TransactionType: "CheckCash"; - CheckID: string; - Amount?: Amount; - DeliverMin?: Amount; + TransactionType: 'CheckCash' + CheckID: string + Amount?: Amount + DeliverMin?: Amount } /** @@ -18,22 +18,22 @@ export interface CheckCash extends BaseTransaction { * @throws When the CheckCash is Malformed. */ export function verifyCheckCash(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Amount == null && tx.DeliverMin == null) { throw new ValidationError( - "CheckCash: must have either Amount or DeliverMin" - ); + 'CheckCash: must have either Amount or DeliverMin', + ) } if (tx.Amount != null && tx.DeliverMin != null) { throw new ValidationError( - "CheckCash: cannot have both Amount and DeliverMin" - ); + 'CheckCash: cannot have both Amount and DeliverMin', + ) } if (tx.Amount != null && tx.Amount !== undefined && !isAmount(tx.Amount)) { - throw new ValidationError("CheckCash: invalid Amount"); + throw new ValidationError('CheckCash: invalid Amount') } if ( @@ -41,10 +41,10 @@ export function verifyCheckCash(tx: Record): void { tx.DeliverMin !== undefined && !isAmount(tx.DeliverMin) ) { - throw new ValidationError("CheckCash: invalid DeliverMin"); + throw new ValidationError('CheckCash: invalid DeliverMin') } - if (tx.CheckID !== undefined && typeof tx.CheckID !== "string") { - throw new ValidationError("CheckCash: invalid CheckID"); + if (tx.CheckID !== undefined && typeof tx.CheckID !== 'string') { + throw new ValidationError('CheckCash: invalid CheckID') } } diff --git a/src/models/transactions/checkCreate.ts b/src/models/transactions/checkCreate.ts index c2639003..488b6f8f 100644 --- a/src/models/transactions/checkCreate.ts +++ b/src/models/transactions/checkCreate.ts @@ -1,20 +1,20 @@ /* eslint-disable complexity -- Necessary for verifyCheckCreate */ -import { ValidationError } from "../../common/errors"; -import { Amount } from "../common"; +import { ValidationError } from '../../common/errors' +import { Amount } from '../common' import { BaseTransaction, verifyBaseTransaction, isIssuedCurrency, -} from "./common"; +} from './common' export interface CheckCreate extends BaseTransaction { - TransactionType: "CheckCreate"; - Destination: string; - SendMax: Amount; - DestinationTag?: number; - Expiration?: number; - InvoiceID?: string; + TransactionType: 'CheckCreate' + Destination: string + SendMax: Amount + DestinationTag?: number + Expiration?: number + InvoiceID?: string } /** @@ -24,40 +24,40 @@ export interface CheckCreate extends BaseTransaction { * @throws When the CheckCreate is Malformed. */ export function verifyCheckCreate(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.SendMax === undefined) { - throw new ValidationError("CheckCreate: missing field SendMax"); + throw new ValidationError('CheckCreate: missing field SendMax') } if (tx.Destination === undefined) { - throw new ValidationError("CheckCreate: missing field Destination"); + throw new ValidationError('CheckCreate: missing field Destination') } if ( - typeof tx.SendMax !== "string" && + typeof tx.SendMax !== 'string' && // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS !isIssuedCurrency(tx.SendMax as Record) ) { - throw new ValidationError("CheckCreate: invalid SendMax"); + throw new ValidationError('CheckCreate: invalid SendMax') } - if (typeof tx.Destination !== "string") { - throw new ValidationError("CheckCreate: invalid Destination"); + if (typeof tx.Destination !== 'string') { + throw new ValidationError('CheckCreate: invalid Destination') } if ( tx.DestinationTag !== undefined && - typeof tx.DestinationTag !== "number" + typeof tx.DestinationTag !== 'number' ) { - throw new ValidationError("CheckCreate: invalid DestinationTag"); + throw new ValidationError('CheckCreate: invalid DestinationTag') } - if (tx.Expiration !== undefined && typeof tx.Expiration !== "number") { - throw new ValidationError("CheckCreate: invalid Expiration"); + if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') { + throw new ValidationError('CheckCreate: invalid Expiration') } - if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== "string") { - throw new ValidationError("CheckCreate: invalid InvoiceID"); + if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== 'string') { + throw new ValidationError('CheckCreate: invalid InvoiceID') } } diff --git a/src/models/transactions/common.ts b/src/models/transactions/common.ts index 8db8cc76..03fbc1d5 100644 --- a/src/models/transactions/common.ts +++ b/src/models/transactions/common.ts @@ -1,45 +1,45 @@ /* eslint-disable max-lines-per-function -- Necessary for verifyBaseTransaction */ /* eslint-disable complexity -- Necessary for verifyBaseTransaction */ /* eslint-disable max-statements -- Necessary for verifyBaseTransaction */ -import { ValidationError } from "../../common/errors"; -import { Memo, Signer } from "../common"; -import { onlyHasFields } from "../utils"; +import { ValidationError } from '../../common/errors' +import { Memo, Signer } from '../common' +import { onlyHasFields } from '../utils' const transactionTypes = [ - "AccountSet", - "AccountDelete", - "CheckCancel", - "CheckCash", - "CheckCreate", - "DepositPreauth", - "EscrowCancel", - "EscrowCreate", - "EscrowFinish", - "OfferCancel", - "OfferCreate", - "Payment", - "PaymentChannelClaim", - "PaymentChannelCreate", - "PaymentChannelFund", - "SetRegularKey", - "SignerListSet", - "TicketCreate", - "TrustSet", -]; + 'AccountSet', + 'AccountDelete', + 'CheckCancel', + 'CheckCash', + 'CheckCreate', + 'DepositPreauth', + 'EscrowCancel', + 'EscrowCreate', + 'EscrowFinish', + 'OfferCancel', + 'OfferCreate', + 'Payment', + 'PaymentChannelClaim', + 'PaymentChannelCreate', + 'PaymentChannelFund', + 'SetRegularKey', + 'SignerListSet', + 'TicketCreate', + 'TrustSet', +] -const MEMO_SIZE = 3; +const MEMO_SIZE = 3 function isMemo(obj: { Memo?: unknown }): boolean { if (obj.Memo == null) { - return false; + return false } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS - const memo = obj.Memo as Record; - const size = Object.keys(memo).length; - const validData = memo.MemoData == null || typeof memo.MemoData === "string"; + const memo = obj.Memo as Record + const size = Object.keys(memo).length + const validData = memo.MemoData == null || typeof memo.MemoData === 'string' const validFormat = - memo.MemoFormat == null || typeof memo.MemoFormat === "string"; - const validType = memo.MemoType == null || typeof memo.MemoType === "string"; + memo.MemoFormat == null || typeof memo.MemoFormat === 'string' + const validType = memo.MemoType == null || typeof memo.MemoType === 'string' return ( size >= 1 && @@ -47,24 +47,24 @@ function isMemo(obj: { Memo?: unknown }): boolean { validData && validFormat && validType && - onlyHasFields(memo, ["MemoFormat", "MemoData", "MemoType"]) - ); + onlyHasFields(memo, ['MemoFormat', 'MemoData', 'MemoType']) + ) } -const SIGNER_SIZE = 3; +const SIGNER_SIZE = 3 function isSigner(obj: unknown): boolean { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS - const signer = obj as Record; + const signer = obj as Record return ( Object.keys(signer).length === SIGNER_SIZE && - typeof signer.Account === "string" && - typeof signer.TxnSignature === "string" && - typeof signer.SigningPubKey === "string" - ); + typeof signer.Account === 'string' && + typeof signer.TxnSignature === 'string' && + typeof signer.SigningPubKey === 'string' + ) } -const ISSUED_CURRENCY_SIZE = 3; +const ISSUED_CURRENCY_SIZE = 3 /** * Verify the form and type of an IssuedCurrencyAmount at runtime. @@ -75,10 +75,10 @@ const ISSUED_CURRENCY_SIZE = 3; export function isIssuedCurrency(obj: Record): boolean { return ( Object.keys(obj).length === ISSUED_CURRENCY_SIZE && - typeof obj.value === "string" && - typeof obj.issuer === "string" && - typeof obj.currency === "string" - ); + typeof obj.value === 'string' && + typeof obj.issuer === 'string' && + typeof obj.currency === 'string' + ) } /** @@ -89,30 +89,30 @@ export function isIssuedCurrency(obj: Record): boolean { */ export function isAmount(amount: unknown): boolean { return ( - typeof amount === "string" || + typeof amount === 'string' || // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS isIssuedCurrency(amount as Record) - ); + ) } export interface GlobalFlags { - tfFullyCanonicalSig: boolean; + tfFullyCanonicalSig: boolean } export interface BaseTransaction { - Account: string; - TransactionType: string; - Fee?: string; - Sequence?: number; - AccountTxnID?: string; - Flags?: number | GlobalFlags; - LastLedgerSequence?: number; - Memos?: Array<{ Memo: Memo }>; - Signers?: Signer[]; - SourceTag?: number; - SigningPubKey?: string; - TicketSequence?: number; - TxnSignature?: string; + Account: string + TransactionType: string + Fee?: string + Sequence?: number + AccountTxnID?: string + Flags?: number | GlobalFlags + LastLedgerSequence?: number + Memos?: Array<{ Memo: Memo }> + Signers?: Signer[] + SourceTag?: number + SigningPubKey?: string + TicketSequence?: number + TxnSignature?: string } /** @@ -125,85 +125,85 @@ export interface BaseTransaction { */ export function verifyBaseTransaction(common: Record): void { if (common.Account === undefined) { - throw new ValidationError("BaseTransaction: missing field Account"); + throw new ValidationError('BaseTransaction: missing field Account') } - if (typeof common.Account !== "string") { - throw new ValidationError("BaseTransaction: Account not string"); + if (typeof common.Account !== 'string') { + throw new ValidationError('BaseTransaction: Account not string') } if (common.TransactionType === undefined) { - throw new ValidationError("BaseTransaction: missing field TransactionType"); + throw new ValidationError('BaseTransaction: missing field TransactionType') } - if (typeof common.TransactionType !== "string") { - throw new ValidationError("BaseTransaction: TransactionType not string"); + if (typeof common.TransactionType !== 'string') { + throw new ValidationError('BaseTransaction: TransactionType not string') } if (!transactionTypes.includes(common.TransactionType)) { - throw new ValidationError("BaseTransaction: Unknown TransactionType"); + throw new ValidationError('BaseTransaction: Unknown TransactionType') } - if (common.Fee !== undefined && typeof common.Fee !== "string") { - throw new ValidationError("BaseTransaction: invalid Fee"); + if (common.Fee !== undefined && typeof common.Fee !== 'string') { + throw new ValidationError('BaseTransaction: invalid Fee') } - if (common.Sequence !== undefined && typeof common.Sequence !== "number") { - throw new ValidationError("BaseTransaction: invalid Sequence"); + if (common.Sequence !== undefined && typeof common.Sequence !== 'number') { + throw new ValidationError('BaseTransaction: invalid Sequence') } if ( common.AccountTxnID !== undefined && - typeof common.AccountTxnID !== "string" + typeof common.AccountTxnID !== 'string' ) { - throw new ValidationError("BaseTransaction: invalid AccountTxnID"); + throw new ValidationError('BaseTransaction: invalid AccountTxnID') } if ( common.LastLedgerSequence !== undefined && - typeof common.LastLedgerSequence !== "number" + typeof common.LastLedgerSequence !== 'number' ) { - throw new ValidationError("BaseTransaction: invalid LastLedgerSequence"); + throw new ValidationError('BaseTransaction: invalid LastLedgerSequence') } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS - const memos = common.Memos as Array<{ Memo?: unknown }> | undefined; + const memos = common.Memos as Array<{ Memo?: unknown }> | undefined if (memos !== undefined && !memos.every(isMemo)) { - throw new ValidationError("BaseTransaction: invalid Memos"); + throw new ValidationError('BaseTransaction: invalid Memos') } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS - const signers = common.Signers as Array> | undefined; + const signers = common.Signers as Array> | undefined if ( signers !== undefined && (signers.length === 0 || !signers.every(isSigner)) ) { - throw new ValidationError("BaseTransaction: invalid Signers"); + throw new ValidationError('BaseTransaction: invalid Signers') } - if (common.SourceTag !== undefined && typeof common.SourceTag !== "number") { - throw new ValidationError("BaseTransaction: invalid SourceTag"); + if (common.SourceTag !== undefined && typeof common.SourceTag !== 'number') { + throw new ValidationError('BaseTransaction: invalid SourceTag') } if ( common.SigningPubKey !== undefined && - typeof common.SigningPubKey !== "string" + typeof common.SigningPubKey !== 'string' ) { - throw new ValidationError("BaseTransaction: invalid SigningPubKey"); + throw new ValidationError('BaseTransaction: invalid SigningPubKey') } if ( common.TicketSequence !== undefined && - typeof common.TicketSequence !== "number" + typeof common.TicketSequence !== 'number' ) { - throw new ValidationError("BaseTransaction: invalid TicketSequence"); + throw new ValidationError('BaseTransaction: invalid TicketSequence') } if ( common.TxnSignature !== undefined && - typeof common.TxnSignature !== "string" + typeof common.TxnSignature !== 'string' ) { - throw new ValidationError("BaseTransaction: invalid TxnSignature"); + throw new ValidationError('BaseTransaction: invalid TxnSignature') } } diff --git a/src/models/transactions/depositPreauth.ts b/src/models/transactions/depositPreauth.ts index 427191f1..48044abe 100644 --- a/src/models/transactions/depositPreauth.ts +++ b/src/models/transactions/depositPreauth.ts @@ -1,12 +1,12 @@ /* eslint-disable complexity -- Necessary for verifyDepositPreauth */ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface DepositPreauth extends BaseTransaction { - TransactionType: "DepositPreauth"; - Authorize?: string; - Unauthorize?: string; + TransactionType: 'DepositPreauth' + Authorize?: string + Unauthorize?: string } /** @@ -16,41 +16,41 @@ export interface DepositPreauth extends BaseTransaction { * @throws When the DepositPreauth is malformed. */ export function verifyDepositPreauth(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Authorize !== undefined && tx.Unauthorize !== undefined) { throw new ValidationError( - "DepositPreauth: can't provide both Authorize and Unauthorize fields" - ); + "DepositPreauth: can't provide both Authorize and Unauthorize fields", + ) } if (tx.Authorize === undefined && tx.Unauthorize === undefined) { throw new ValidationError( - "DepositPreauth: must provide either Authorize or Unauthorize field" - ); + 'DepositPreauth: must provide either Authorize or Unauthorize field', + ) } if (tx.Authorize !== undefined) { - if (typeof tx.Authorize !== "string") { - throw new ValidationError("DepositPreauth: Authorize must be a string"); + if (typeof tx.Authorize !== 'string') { + throw new ValidationError('DepositPreauth: Authorize must be a string') } if (tx.Account === tx.Authorize) { throw new ValidationError( - "DepositPreauth: Account can't preauthorize its own address" - ); + "DepositPreauth: Account can't preauthorize its own address", + ) } } if (tx.Unauthorize !== undefined) { - if (typeof tx.Unauthorize !== "string") { - throw new ValidationError("DepositPreauth: Unauthorize must be a string"); + if (typeof tx.Unauthorize !== 'string') { + throw new ValidationError('DepositPreauth: Unauthorize must be a string') } if (tx.Account === tx.Unauthorize) { throw new ValidationError( - "DepositPreauth: Account can't unauthorize its own address" - ); + "DepositPreauth: Account can't unauthorize its own address", + ) } } } diff --git a/src/models/transactions/escrowCancel.ts b/src/models/transactions/escrowCancel.ts index 5c7c4638..9e62ced9 100644 --- a/src/models/transactions/escrowCancel.ts +++ b/src/models/transactions/escrowCancel.ts @@ -1,11 +1,11 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface EscrowCancel extends BaseTransaction { - TransactionType: "EscrowCancel"; - Owner: string; - OfferSequence: number; + TransactionType: 'EscrowCancel' + Owner: string + OfferSequence: number } /** @@ -15,21 +15,21 @@ export interface EscrowCancel extends BaseTransaction { * @throws When the EscrowCancel is Malformed. */ export function verifyEscrowCancel(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Owner === undefined) { - throw new ValidationError("EscrowCancel: missing Owner"); + throw new ValidationError('EscrowCancel: missing Owner') } - if (typeof tx.Owner !== "string") { - throw new ValidationError("EscrowCancel: Owner must be a string"); + if (typeof tx.Owner !== 'string') { + throw new ValidationError('EscrowCancel: Owner must be a string') } if (tx.OfferSequence === undefined) { - throw new ValidationError("EscrowCancel: missing OfferSequence"); + throw new ValidationError('EscrowCancel: missing OfferSequence') } - if (typeof tx.OfferSequence !== "number") { - throw new ValidationError("EscrowCancel: OfferSequence must be a number"); + if (typeof tx.OfferSequence !== 'number') { + throw new ValidationError('EscrowCancel: OfferSequence must be a number') } } diff --git a/src/models/transactions/escrowCreate.ts b/src/models/transactions/escrowCreate.ts index 06a3c714..2ae199f6 100644 --- a/src/models/transactions/escrowCreate.ts +++ b/src/models/transactions/escrowCreate.ts @@ -1,16 +1,16 @@ /* eslint-disable complexity -- Necessary for verifyEscrowCreate */ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface EscrowCreate extends BaseTransaction { - TransactionType: "EscrowCreate"; - Amount: string; - Destination: string; - CancelAfter?: number; - FinishAfter?: number; - Condition?: string; - DestinationTag?: number; + TransactionType: 'EscrowCreate' + Amount: string + Destination: string + CancelAfter?: number + FinishAfter?: number + Condition?: string + DestinationTag?: number } /** @@ -20,52 +20,52 @@ export interface EscrowCreate extends BaseTransaction { * @throws When the EscrowCreate is Malformed. */ export function verifyEscrowCreate(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Amount === undefined) { - throw new ValidationError("EscrowCreate: missing field Amount"); + throw new ValidationError('EscrowCreate: missing field Amount') } - if (typeof tx.Amount !== "string") { - throw new ValidationError("EscrowCreate: Amount must be a string"); + if (typeof tx.Amount !== 'string') { + throw new ValidationError('EscrowCreate: Amount must be a string') } if (tx.Destination === undefined) { - throw new ValidationError("EscrowCreate: missing field Destination"); + throw new ValidationError('EscrowCreate: missing field Destination') } - if (typeof tx.Destination !== "string") { - throw new ValidationError("EscrowCreate: Destination must be a string"); + if (typeof tx.Destination !== 'string') { + throw new ValidationError('EscrowCreate: Destination must be a string') } if (tx.CancelAfter === undefined && tx.FinishAfter === undefined) { throw new ValidationError( - "EscrowCreate: Either CancelAfter or FinishAfter must be specified" - ); + 'EscrowCreate: Either CancelAfter or FinishAfter must be specified', + ) } if (tx.FinishAfter === undefined && tx.Condition === undefined) { throw new ValidationError( - "EscrowCreate: Either Condition or FinishAfter must be specified" - ); + 'EscrowCreate: Either Condition or FinishAfter must be specified', + ) } - if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== "number") { - throw new ValidationError("EscrowCreate: CancelAfter must be a number"); + if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== 'number') { + throw new ValidationError('EscrowCreate: CancelAfter must be a number') } - if (tx.FinishAfter !== undefined && typeof tx.FinishAfter !== "number") { - throw new ValidationError("EscrowCreate: FinishAfter must be a number"); + if (tx.FinishAfter !== undefined && typeof tx.FinishAfter !== 'number') { + throw new ValidationError('EscrowCreate: FinishAfter must be a number') } - if (tx.Condition !== undefined && typeof tx.Condition !== "string") { - throw new ValidationError("EscrowCreate: Condition must be a string"); + if (tx.Condition !== undefined && typeof tx.Condition !== 'string') { + throw new ValidationError('EscrowCreate: Condition must be a string') } if ( tx.DestinationTag !== undefined && - typeof tx.DestinationTag !== "number" + typeof tx.DestinationTag !== 'number' ) { - throw new ValidationError("EscrowCreate: DestinationTag must be a number"); + throw new ValidationError('EscrowCreate: DestinationTag must be a number') } } diff --git a/src/models/transactions/escrowFinish.ts b/src/models/transactions/escrowFinish.ts index 8f46612f..b8f1eccb 100644 --- a/src/models/transactions/escrowFinish.ts +++ b/src/models/transactions/escrowFinish.ts @@ -1,13 +1,13 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface EscrowFinish extends BaseTransaction { - TransactionType: "EscrowFinish"; - Owner: string; - OfferSequence: number; - Condition?: string; - Fulfillment?: string; + TransactionType: 'EscrowFinish' + Owner: string + OfferSequence: number + Condition?: string + Fulfillment?: string } /** @@ -17,29 +17,29 @@ export interface EscrowFinish extends BaseTransaction { * @throws When the EscrowFinish is Malformed. */ export function verifyEscrowFinish(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Owner === undefined) { - throw new ValidationError("EscrowFinish: missing field Owner"); + throw new ValidationError('EscrowFinish: missing field Owner') } - if (typeof tx.Owner !== "string") { - throw new ValidationError("EscrowFinish: Owner must be a string"); + if (typeof tx.Owner !== 'string') { + throw new ValidationError('EscrowFinish: Owner must be a string') } if (tx.OfferSequence === undefined) { - throw new ValidationError("EscrowFinish: missing field OfferSequence"); + throw new ValidationError('EscrowFinish: missing field OfferSequence') } - if (typeof tx.OfferSequence !== "number") { - throw new ValidationError("EscrowFinish: OfferSequence must be a number"); + if (typeof tx.OfferSequence !== 'number') { + throw new ValidationError('EscrowFinish: OfferSequence must be a number') } - if (tx.Condition !== undefined && typeof tx.Condition !== "string") { - throw new ValidationError("EscrowFinish: Condition must be a string"); + if (tx.Condition !== undefined && typeof tx.Condition !== 'string') { + throw new ValidationError('EscrowFinish: Condition must be a string') } - if (tx.Fulfillment !== undefined && typeof tx.Fulfillment !== "string") { - throw new ValidationError("EscrowFinish: Fulfillment must be a string"); + if (tx.Fulfillment !== undefined && typeof tx.Fulfillment !== 'string') { + throw new ValidationError('EscrowFinish: Fulfillment must be a string') } } diff --git a/src/models/transactions/index.ts b/src/models/transactions/index.ts index c784c188..591a7b3a 100644 --- a/src/models/transactions/index.ts +++ b/src/models/transactions/index.ts @@ -1,23 +1,23 @@ /* eslint-disable import/no-unused-modules -- Needs to export all types + verify methods */ /* eslint-disable import/max-dependencies -- Needs to export all types + verify methods */ // TODO: replace * imports with direct imports -export * from "./transaction"; -export * from "./accountSet"; -export * from "./accountDelete"; -export * from "./checkCancel"; -export * from "./checkCash"; -export * from "./checkCreate"; -export * from "./depositPreauth"; -export * from "./escrowCancel"; -export * from "./escrowCreate"; -export * from "./escrowFinish"; -export * from "./offerCancel"; -export * from "./offerCreate"; -export * from "./payment"; -export * from "./paymentChannelClaim"; -export * from "./paymentChannelCreate"; -export * from "./paymentChannelFund"; -export * from "./setRegularKey"; -export * from "./signerListSet"; -export * from "./ticketCreate"; -export * from "./trustSet"; +export * from './transaction' +export * from './accountSet' +export * from './accountDelete' +export * from './checkCancel' +export * from './checkCash' +export * from './checkCreate' +export * from './depositPreauth' +export * from './escrowCancel' +export * from './escrowCreate' +export * from './escrowFinish' +export * from './offerCancel' +export * from './offerCreate' +export * from './payment' +export * from './paymentChannelClaim' +export * from './paymentChannelCreate' +export * from './paymentChannelFund' +export * from './setRegularKey' +export * from './signerListSet' +export * from './ticketCreate' +export * from './trustSet' diff --git a/src/models/transactions/metadata.ts b/src/models/transactions/metadata.ts index dc78b4ca..e1bf03f2 100644 --- a/src/models/transactions/metadata.ts +++ b/src/models/transactions/metadata.ts @@ -1,38 +1,38 @@ -import { Amount } from "../common"; +import { Amount } from '../common' interface CreatedNode { CreatedNode: { - LedgerEntryType: string; - LedgerIndex: string; - NewFields: { [field: string]: unknown }; - }; + LedgerEntryType: string + LedgerIndex: string + NewFields: { [field: string]: unknown } + } } interface ModifiedNode { ModifiedNode: { - LedgerEntryType: string; - LedgerIndex: string; - FinalFields: { [field: string]: unknown }; - PreviousFields: { [field: string]: unknown }; - PreviousTxnID?: string; - PreviouTxnLgrSeq?: number; - }; + LedgerEntryType: string + LedgerIndex: string + FinalFields: { [field: string]: unknown } + PreviousFields: { [field: string]: unknown } + PreviousTxnID?: string + PreviouTxnLgrSeq?: number + } } interface DeletedNode { DeletedNode: { - LedgerEntryType: string; - LedgerIndex: string; - FinalFields: { [field: string]: unknown }; - }; + LedgerEntryType: string + LedgerIndex: string + FinalFields: { [field: string]: unknown } + } } -type Node = CreatedNode | ModifiedNode | DeletedNode; +type Node = CreatedNode | ModifiedNode | DeletedNode export default interface TransactionMetadata { - AffectedNodes: Node[]; - DeliveredAmount?: Amount; - delivered_amount?: Amount; - TransactionIndex: number; - TransactionResult: string; + AffectedNodes: Node[] + DeliveredAmount?: Amount + delivered_amount?: Amount + TransactionIndex: number + TransactionResult: string } diff --git a/src/models/transactions/offerCancel.ts b/src/models/transactions/offerCancel.ts index 74839603..f0c7f85b 100644 --- a/src/models/transactions/offerCancel.ts +++ b/src/models/transactions/offerCancel.ts @@ -1,10 +1,10 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface OfferCancel extends BaseTransaction { - TransactionType: "OfferCancel"; - OfferSequence: number; + TransactionType: 'OfferCancel' + OfferSequence: number } /** @@ -14,13 +14,13 @@ export interface OfferCancel extends BaseTransaction { * @throws When the OfferCancel is Malformed. */ export function verifyOfferCancel(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.OfferSequence === undefined) { - throw new ValidationError("OfferCancel: missing field OfferSequence"); + throw new ValidationError('OfferCancel: missing field OfferSequence') } - if (typeof tx.OfferSequence !== "number") { - throw new ValidationError("OfferCancel: OfferSequence must be a number"); + if (typeof tx.OfferSequence !== 'number') { + throw new ValidationError('OfferCancel: OfferSequence must be a number') } } diff --git a/src/models/transactions/offerCreate.ts b/src/models/transactions/offerCreate.ts index 52fa9df5..5cd427b2 100644 --- a/src/models/transactions/offerCreate.ts +++ b/src/models/transactions/offerCreate.ts @@ -1,28 +1,28 @@ /* eslint-disable complexity -- Necessary for verifyOfferCreate */ -import { ValidationError } from "../../common/errors"; -import { Amount } from "../common"; +import { ValidationError } from '../../common/errors' +import { Amount } from '../common' import { BaseTransaction, GlobalFlags, verifyBaseTransaction, isAmount, -} from "./common"; +} from './common' export interface OfferCreateFlags extends GlobalFlags { - tfPassive?: boolean; - tfImmediateOrCancel?: boolean; - tfFillOrKill?: boolean; - tfSell?: boolean; + tfPassive?: boolean + tfImmediateOrCancel?: boolean + tfFillOrKill?: boolean + tfSell?: boolean } export interface OfferCreate extends BaseTransaction { - TransactionType: "OfferCreate"; - Flags?: number | OfferCreateFlags; - Expiration?: number; - OfferSequence?: number; - TakerGets: Amount; - TakerPays: Amount; + TransactionType: 'OfferCreate' + Flags?: number | OfferCreateFlags + Expiration?: number + OfferSequence?: number + TakerGets: Amount + TakerPays: Amount } /** @@ -32,29 +32,29 @@ export interface OfferCreate extends BaseTransaction { * @throws When the OfferCreate is Malformed. */ export function verifyOfferCreate(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.TakerGets === undefined) { - throw new ValidationError("OfferCreate: missing field TakerGets"); + throw new ValidationError('OfferCreate: missing field TakerGets') } if (tx.TakerPays === undefined) { - throw new ValidationError("OfferCreate: missing field TakerPays"); + throw new ValidationError('OfferCreate: missing field TakerPays') } - if (typeof tx.TakerGets !== "string" && !isAmount(tx.TakerGets)) { - throw new ValidationError("OfferCreate: invalid TakerGets"); + if (typeof tx.TakerGets !== 'string' && !isAmount(tx.TakerGets)) { + throw new ValidationError('OfferCreate: invalid TakerGets') } - if (typeof tx.TakerPays !== "string" && !isAmount(tx.TakerPays)) { - throw new ValidationError("OfferCreate: invalid TakerPays"); + if (typeof tx.TakerPays !== 'string' && !isAmount(tx.TakerPays)) { + throw new ValidationError('OfferCreate: invalid TakerPays') } - if (tx.Expiration !== undefined && typeof tx.Expiration !== "number") { - throw new ValidationError("OfferCreate: invalid Expiration"); + if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') { + throw new ValidationError('OfferCreate: invalid Expiration') } - if (tx.OfferSequence !== undefined && typeof tx.OfferSequence !== "number") { - throw new ValidationError("OfferCreate: invalid OfferSequence"); + if (tx.OfferSequence !== undefined && typeof tx.OfferSequence !== 'number') { + throw new ValidationError('OfferCreate: invalid OfferSequence') } } diff --git a/src/models/transactions/payment.ts b/src/models/transactions/payment.ts index 0926eb5c..10d410d5 100644 --- a/src/models/transactions/payment.ts +++ b/src/models/transactions/payment.ts @@ -1,15 +1,15 @@ /* eslint-disable max-statements -- Necessary for verifyPayment */ /* eslint-disable complexity -- Necessary for verifyPayment */ -import { ValidationError } from "../../common/errors"; -import { Amount, Path } from "../common"; -import { isFlagEnabled } from "../utils"; +import { ValidationError } from '../../common/errors' +import { Amount, Path } from '../common' +import { isFlagEnabled } from '../utils' import { BaseTransaction, isAmount, GlobalFlags, verifyBaseTransaction, -} from "./common"; +} from './common' export enum PaymentTransactionFlagsEnum { tfNoDirectRipple = 0x00010000, @@ -18,20 +18,20 @@ export enum PaymentTransactionFlagsEnum { } export interface PaymentTransactionFlags extends GlobalFlags { - tfNoDirectRipple?: boolean; - tfPartialPayment?: boolean; - tfLimitQuality?: boolean; + tfNoDirectRipple?: boolean + tfPartialPayment?: boolean + tfLimitQuality?: boolean } export interface Payment extends BaseTransaction { - TransactionType: "Payment"; - Amount: Amount; - Destination: string; - DestinationTag?: number; - InvoiceID?: string; - Paths?: Path[]; - SendMax?: Amount; - DeliverMin?: Amount; - Flags?: number | PaymentTransactionFlags; + TransactionType: 'Payment' + Amount: Amount + Destination: string + DestinationTag?: number + InvoiceID?: string + Paths?: Path[] + SendMax?: Amount + DeliverMin?: Amount + Flags?: number | PaymentTransactionFlags } /** @@ -41,35 +41,35 @@ export interface Payment extends BaseTransaction { * @throws When the Payment is malformed. */ export function verifyPayment(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Amount === undefined) { - throw new ValidationError("PaymentTransaction: missing field Amount"); + throw new ValidationError('PaymentTransaction: missing field Amount') } if (!isAmount(tx.Amount)) { - throw new ValidationError("PaymentTransaction: invalid Amount"); + throw new ValidationError('PaymentTransaction: invalid Amount') } if (tx.Destination === undefined) { - throw new ValidationError("PaymentTransaction: missing field Destination"); + throw new ValidationError('PaymentTransaction: missing field Destination') } if (!isAmount(tx.Destination)) { - throw new ValidationError("PaymentTransaction: invalid Destination"); + throw new ValidationError('PaymentTransaction: invalid Destination') } if ( tx.DestinationTag !== undefined && - typeof tx.DestinationTag !== "number" + typeof tx.DestinationTag !== 'number' ) { throw new ValidationError( - "PaymentTransaction: DestinationTag must be a number" - ); + 'PaymentTransaction: DestinationTag must be a number', + ) } - if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== "string") { - throw new ValidationError("PaymentTransaction: InvoiceID must be a string"); + if (tx.InvoiceID !== undefined && typeof tx.InvoiceID !== 'string') { + throw new ValidationError('PaymentTransaction: InvoiceID must be a string') } if ( @@ -77,92 +77,92 @@ export function verifyPayment(tx: Record): void { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS !isPaths(tx.Paths as Array>>) ) { - throw new ValidationError("PaymentTransaction: invalid Paths"); + throw new ValidationError('PaymentTransaction: invalid Paths') } if (tx.SendMax !== undefined && !isAmount(tx.SendMax)) { - throw new ValidationError("PaymentTransaction: invalid SendMax"); + throw new ValidationError('PaymentTransaction: invalid SendMax') } - checkPartialPayment(tx); + checkPartialPayment(tx) } function checkPartialPayment(tx: Record): void { if (tx.DeliverMin != null) { if (tx.Flags == null) { throw new ValidationError( - "PaymentTransaction: tfPartialPayment flag required with DeliverMin" - ); + 'PaymentTransaction: tfPartialPayment flag required with DeliverMin', + ) } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Only used by JS - const flags = tx.Flags as number | PaymentTransactionFlags; + const flags = tx.Flags as number | PaymentTransactionFlags const isTfPartialPayment = - typeof flags === "number" + typeof flags === 'number' ? isFlagEnabled(flags, PaymentTransactionFlagsEnum.tfPartialPayment) - : flags.tfPartialPayment ?? false; + : flags.tfPartialPayment ?? false if (!isTfPartialPayment) { throw new ValidationError( - "PaymentTransaction: tfPartialPayment flag required with DeliverMin" - ); + 'PaymentTransaction: tfPartialPayment flag required with DeliverMin', + ) } if (!isAmount(tx.DeliverMin)) { - throw new ValidationError("PaymentTransaction: invalid DeliverMin"); + throw new ValidationError('PaymentTransaction: invalid DeliverMin') } } } function isPathStep(pathStep: Record): boolean { - if (pathStep.account !== undefined && typeof pathStep.account !== "string") { - return false; + if (pathStep.account !== undefined && typeof pathStep.account !== 'string') { + return false } if ( pathStep.currency !== undefined && - typeof pathStep.currency !== "string" + typeof pathStep.currency !== 'string' ) { - return false; + return false } - if (pathStep.issuer !== undefined && typeof pathStep.issuer !== "string") { - return false; + if (pathStep.issuer !== undefined && typeof pathStep.issuer !== 'string') { + return false } if ( pathStep.account !== undefined && pathStep.currency === undefined && pathStep.issuer === undefined ) { - return true; + return true } if (pathStep.currency !== undefined || pathStep.issuer !== undefined) { - return true; + return true } - return false; + return false } function isPath(path: Array>): boolean { for (const pathStep of path) { if (!isPathStep(pathStep)) { - return false; + return false } } - return true; + return true } function isPaths(paths: Array>>): boolean { if (!Array.isArray(paths) || paths.length === 0) { - return false; + return false } for (const path of paths) { if (!Array.isArray(path) || path.length === 0) { - return false; + return false } if (!isPath(path)) { - return false; + return false } } - return true; + return true } diff --git a/src/models/transactions/paymentChannelClaim.ts b/src/models/transactions/paymentChannelClaim.ts index 89d65bfb..424dee3f 100644 --- a/src/models/transactions/paymentChannelClaim.ts +++ b/src/models/transactions/paymentChannelClaim.ts @@ -1,21 +1,21 @@ /* eslint-disable complexity -- Necessary for verifyPaymentChannelClaim */ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, GlobalFlags, verifyBaseTransaction } from "./common"; +import { BaseTransaction, GlobalFlags, verifyBaseTransaction } from './common' export interface PaymentChannelClaimFlags extends GlobalFlags { - tfRenew?: boolean; - tfClose?: boolean; + tfRenew?: boolean + tfClose?: boolean } export interface PaymentChannelClaim extends BaseTransaction { - TransactionType: "PaymentChannelClaim"; - Flags?: number | PaymentChannelClaimFlags; - Channel: string; - Balance?: string; - Amount?: string; - Signature?: string; - PublicKey?: string; + TransactionType: 'PaymentChannelClaim' + Flags?: number | PaymentChannelClaimFlags + Channel: string + Balance?: string + Amount?: string + Signature?: string + PublicKey?: string } /** @@ -25,33 +25,29 @@ export interface PaymentChannelClaim extends BaseTransaction { * @throws When the PaymentChannelClaim is Malformed. */ export function verifyPaymentChannelClaim(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Channel === undefined) { - throw new ValidationError("PaymentChannelClaim: missing Channel"); + throw new ValidationError('PaymentChannelClaim: missing Channel') } - if (typeof tx.Channel !== "string") { - throw new ValidationError("PaymentChannelClaim: Channel must be a string"); + if (typeof tx.Channel !== 'string') { + throw new ValidationError('PaymentChannelClaim: Channel must be a string') } - if (tx.Balance !== undefined && typeof tx.Balance !== "string") { - throw new ValidationError("PaymentChannelClaim: Balance must be a string"); + if (tx.Balance !== undefined && typeof tx.Balance !== 'string') { + throw new ValidationError('PaymentChannelClaim: Balance must be a string') } - if (tx.Amount !== undefined && typeof tx.Amount !== "string") { - throw new ValidationError("PaymentChannelClaim: Amount must be a string"); + if (tx.Amount !== undefined && typeof tx.Amount !== 'string') { + throw new ValidationError('PaymentChannelClaim: Amount must be a string') } - if (tx.Signature !== undefined && typeof tx.Signature !== "string") { - throw new ValidationError( - "PaymentChannelClaim: Signature must be a string" - ); + if (tx.Signature !== undefined && typeof tx.Signature !== 'string') { + throw new ValidationError('PaymentChannelClaim: Signature must be a string') } - if (tx.PublicKey !== undefined && typeof tx.PublicKey !== "string") { - throw new ValidationError( - "PaymentChannelClaim: PublicKey must be a string" - ); + if (tx.PublicKey !== undefined && typeof tx.PublicKey !== 'string') { + throw new ValidationError('PaymentChannelClaim: PublicKey must be a string') } } diff --git a/src/models/transactions/paymentChannelCreate.ts b/src/models/transactions/paymentChannelCreate.ts index 4fac858c..1ddabdfb 100644 --- a/src/models/transactions/paymentChannelCreate.ts +++ b/src/models/transactions/paymentChannelCreate.ts @@ -1,16 +1,16 @@ /* eslint-disable complexity -- Necessary for verifyPaymentChannelCreate */ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface PaymentChannelCreate extends BaseTransaction { - TransactionType: "PaymentChannelCreate"; - Amount: string; - Destination: string; - SettleDelay: number; - PublicKey: string; - CancelAfter?: number; - DestinationTag?: number; + TransactionType: 'PaymentChannelCreate' + Amount: string + Destination: string + SettleDelay: number + PublicKey: string + CancelAfter?: number + DestinationTag?: number } /** @@ -20,58 +20,58 @@ export interface PaymentChannelCreate extends BaseTransaction { * @throws When the PaymentChannelCreate is Malformed. */ export function verifyPaymentChannelCreate(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Amount === undefined) { - throw new ValidationError("PaymentChannelCreate: missing Amount"); + throw new ValidationError('PaymentChannelCreate: missing Amount') } - if (typeof tx.Amount !== "string") { - throw new ValidationError("PaymentChannelCreate: Amount must be a string"); + if (typeof tx.Amount !== 'string') { + throw new ValidationError('PaymentChannelCreate: Amount must be a string') } if (tx.Destination === undefined) { - throw new ValidationError("PaymentChannelCreate: missing Destination"); + throw new ValidationError('PaymentChannelCreate: missing Destination') } - if (typeof tx.Destination !== "string") { + if (typeof tx.Destination !== 'string') { throw new ValidationError( - "PaymentChannelCreate: Destination must be a string" - ); + 'PaymentChannelCreate: Destination must be a string', + ) } if (tx.SettleDelay === undefined) { - throw new ValidationError("PaymentChannelCreate: missing SettleDelay"); + throw new ValidationError('PaymentChannelCreate: missing SettleDelay') } - if (typeof tx.SettleDelay !== "number") { + if (typeof tx.SettleDelay !== 'number') { throw new ValidationError( - "PaymentChannelCreate: SettleDelay must be a number" - ); + 'PaymentChannelCreate: SettleDelay must be a number', + ) } if (tx.PublicKey === undefined) { - throw new ValidationError("PaymentChannelCreate: missing PublicKey"); + throw new ValidationError('PaymentChannelCreate: missing PublicKey') } - if (typeof tx.PublicKey !== "string") { + if (typeof tx.PublicKey !== 'string') { throw new ValidationError( - "PaymentChannelCreate: PublicKey must be a string" - ); + 'PaymentChannelCreate: PublicKey must be a string', + ) } - if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== "number") { + if (tx.CancelAfter !== undefined && typeof tx.CancelAfter !== 'number') { throw new ValidationError( - "PaymentChannelCreate: CancelAfter must be a number" - ); + 'PaymentChannelCreate: CancelAfter must be a number', + ) } if ( tx.DestinationTag !== undefined && - typeof tx.DestinationTag !== "number" + typeof tx.DestinationTag !== 'number' ) { throw new ValidationError( - "PaymentChannelCreate: DestinationTag must be a number" - ); + 'PaymentChannelCreate: DestinationTag must be a number', + ) } } diff --git a/src/models/transactions/paymentChannelFund.ts b/src/models/transactions/paymentChannelFund.ts index 5558fb04..abbddbf5 100644 --- a/src/models/transactions/paymentChannelFund.ts +++ b/src/models/transactions/paymentChannelFund.ts @@ -1,12 +1,12 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface PaymentChannelFund extends BaseTransaction { - TransactionType: "PaymentChannelFund"; - Channel: string; - Amount: string; - Expiration?: number; + TransactionType: 'PaymentChannelFund' + Channel: string + Amount: string + Expiration?: number } /** @@ -16,27 +16,25 @@ export interface PaymentChannelFund extends BaseTransaction { * @throws When the PaymentChannelFund is Malformed. */ export function verifyPaymentChannelFund(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.Channel === undefined) { - throw new ValidationError("PaymentChannelFund: missing Channel"); + throw new ValidationError('PaymentChannelFund: missing Channel') } - if (typeof tx.Channel !== "string") { - throw new ValidationError("PaymentChannelFund: Channel must be a string"); + if (typeof tx.Channel !== 'string') { + throw new ValidationError('PaymentChannelFund: Channel must be a string') } if (tx.Amount === undefined) { - throw new ValidationError("PaymentChannelFund: missing Amount"); + throw new ValidationError('PaymentChannelFund: missing Amount') } - if (typeof tx.Amount !== "string") { - throw new ValidationError("PaymentChannelFund: Amount must be a string"); + if (typeof tx.Amount !== 'string') { + throw new ValidationError('PaymentChannelFund: Amount must be a string') } - if (tx.Expiration !== undefined && typeof tx.Expiration !== "number") { - throw new ValidationError( - "PaymentChannelFund: Expiration must be a number" - ); + if (tx.Expiration !== undefined && typeof tx.Expiration !== 'number') { + throw new ValidationError('PaymentChannelFund: Expiration must be a number') } } diff --git a/src/models/transactions/setRegularKey.ts b/src/models/transactions/setRegularKey.ts index 31481e71..17124aa4 100644 --- a/src/models/transactions/setRegularKey.ts +++ b/src/models/transactions/setRegularKey.ts @@ -1,10 +1,10 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface SetRegularKey extends BaseTransaction { - TransactionType: "SetRegularKey"; - RegularKey?: string; + TransactionType: 'SetRegularKey' + RegularKey?: string } /** @@ -14,9 +14,9 @@ export interface SetRegularKey extends BaseTransaction { * @throws When the SetRegularKey is malformed. */ export function verifySetRegularKey(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) - if (tx.RegularKey !== undefined && typeof tx.RegularKey !== "string") { - throw new ValidationError("SetRegularKey: RegularKey must be a string"); + if (tx.RegularKey !== undefined && typeof tx.RegularKey !== 'string') { + throw new ValidationError('SetRegularKey: RegularKey must be a string') } } diff --git a/src/models/transactions/signerListSet.ts b/src/models/transactions/signerListSet.ts index e0eb86ed..cebbfa31 100644 --- a/src/models/transactions/signerListSet.ts +++ b/src/models/transactions/signerListSet.ts @@ -1,15 +1,15 @@ -import { ValidationError } from "../../common/errors"; -import { SignerEntry } from "../common"; +import { ValidationError } from '../../common/errors' +import { SignerEntry } from '../common' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface SignerListSet extends BaseTransaction { - TransactionType: "SignerListSet"; - SignerQuorum: number; - SignerEntries: SignerEntry[]; + TransactionType: 'SignerListSet' + SignerQuorum: number + SignerEntries: SignerEntry[] } -const MAX_SIGNERS = 8; +const MAX_SIGNERS = 8 /** * Verify the form and type of an SignerListSet at runtime. @@ -18,33 +18,33 @@ const MAX_SIGNERS = 8; * @throws When the SignerListSet is Malformed. */ export function verifySignerListSet(tx: Record): void { - verifyBaseTransaction(tx); + verifyBaseTransaction(tx) if (tx.SignerQuorum === undefined) { - throw new ValidationError("SignerListSet: missing field SignerQuorum"); + throw new ValidationError('SignerListSet: missing field SignerQuorum') } - if (typeof tx.SignerQuorum !== "number") { - throw new ValidationError("SignerListSet: invalid SignerQuorum"); + if (typeof tx.SignerQuorum !== 'number') { + throw new ValidationError('SignerListSet: invalid SignerQuorum') } if (tx.SignerEntries === undefined) { - throw new ValidationError("SignerListSet: missing field SignerEntries"); + throw new ValidationError('SignerListSet: missing field SignerEntries') } if (!Array.isArray(tx.SignerEntries)) { - throw new ValidationError("SignerListSet: invalid SignerEntries"); + throw new ValidationError('SignerListSet: invalid SignerEntries') } if (tx.SignerEntries.length === 0) { throw new ValidationError( - "SignerListSet: need atleast 1 member in SignerEntries" - ); + 'SignerListSet: need atleast 1 member in SignerEntries', + ) } if (tx.SignerEntries.length > MAX_SIGNERS) { throw new ValidationError( - "SignerListSet: maximum of 8 members allowed in SignerEntries" - ); + 'SignerListSet: maximum of 8 members allowed in SignerEntries', + ) } } diff --git a/src/models/transactions/ticketCreate.ts b/src/models/transactions/ticketCreate.ts index d8be778f..fd83da07 100644 --- a/src/models/transactions/ticketCreate.ts +++ b/src/models/transactions/ticketCreate.ts @@ -1,13 +1,13 @@ -import { ValidationError } from "../../common/errors"; +import { ValidationError } from '../../common/errors' -import { BaseTransaction, verifyBaseTransaction } from "./common"; +import { BaseTransaction, verifyBaseTransaction } from './common' export interface TicketCreate extends BaseTransaction { - TransactionType: "TicketCreate"; - TicketCount: number; + TransactionType: 'TicketCreate' + TicketCount: number } -const MAX_TICKETS = 250; +const MAX_TICKETS = 250 /** * Verify the form and type of a TicketCreate at runtime. @@ -16,15 +16,15 @@ const MAX_TICKETS = 250; * @throws When the TicketCreate is malformed. */ export function verifyTicketCreate(tx: Record): void { - verifyBaseTransaction(tx); - const { TicketCount } = tx; + verifyBaseTransaction(tx) + const { TicketCount } = tx if (TicketCount === undefined) { - throw new ValidationError("TicketCreate: missing field TicketCount"); + throw new ValidationError('TicketCreate: missing field TicketCount') } - if (typeof TicketCount !== "number") { - throw new ValidationError("TicketCreate: TicketCount must be a number"); + if (typeof TicketCount !== 'number') { + throw new ValidationError('TicketCreate: TicketCount must be a number') } if ( @@ -33,7 +33,7 @@ export function verifyTicketCreate(tx: Record): void { TicketCount > MAX_TICKETS ) { throw new ValidationError( - "TicketCreate: TicketCount must be an integer from 1 to 250" - ); + 'TicketCreate: TicketCount must be an integer from 1 to 250', + ) } } diff --git a/src/models/transactions/transaction.ts b/src/models/transactions/transaction.ts index 09385d53..badf6777 100644 --- a/src/models/transactions/transaction.ts +++ b/src/models/transactions/transaction.ts @@ -1,25 +1,25 @@ /* eslint-disable import/max-dependencies -- All methods need to be exported */ -import { AccountDelete } from "./accountDelete"; -import { AccountSet } from "./accountSet"; -import { CheckCancel } from "./checkCancel"; -import { CheckCash } from "./checkCash"; -import { CheckCreate } from "./checkCreate"; -import { DepositPreauth } from "./depositPreauth"; -import { EscrowCancel } from "./escrowCancel"; -import { EscrowCreate } from "./escrowCreate"; -import { EscrowFinish } from "./escrowFinish"; -import Metadata from "./metadata"; -import { OfferCancel } from "./offerCancel"; -import { OfferCreate } from "./offerCreate"; -import { Payment } from "./payment"; -import { PaymentChannelClaim } from "./paymentChannelClaim"; -import { PaymentChannelCreate } from "./paymentChannelCreate"; -import { PaymentChannelFund } from "./paymentChannelFund"; -import { SetRegularKey } from "./setRegularKey"; -import { SignerListSet } from "./signerListSet"; -import { TicketCreate } from "./ticketCreate"; -import { TrustSet } from "./trustSet"; +import { AccountDelete } from './accountDelete' +import { AccountSet } from './accountSet' +import { CheckCancel } from './checkCancel' +import { CheckCash } from './checkCash' +import { CheckCreate } from './checkCreate' +import { DepositPreauth } from './depositPreauth' +import { EscrowCancel } from './escrowCancel' +import { EscrowCreate } from './escrowCreate' +import { EscrowFinish } from './escrowFinish' +import Metadata from './metadata' +import { OfferCancel } from './offerCancel' +import { OfferCreate } from './offerCreate' +import { Payment } from './payment' +import { PaymentChannelClaim } from './paymentChannelClaim' +import { PaymentChannelCreate } from './paymentChannelCreate' +import { PaymentChannelFund } from './paymentChannelFund' +import { SetRegularKey } from './setRegularKey' +import { SignerListSet } from './signerListSet' +import { TicketCreate } from './ticketCreate' +import { TrustSet } from './trustSet' export type Transaction = | AccountDelete @@ -40,9 +40,9 @@ export type Transaction = | SetRegularKey | SignerListSet | TicketCreate - | TrustSet; + | TrustSet export interface TransactionAndMetadata { - transaction: Transaction; - metadata: Metadata; + transaction: Transaction + metadata: Metadata } diff --git a/src/models/transactions/trustSet.ts b/src/models/transactions/trustSet.ts index e149de6e..84d29b24 100644 --- a/src/models/transactions/trustSet.ts +++ b/src/models/transactions/trustSet.ts @@ -1,12 +1,12 @@ -import { ValidationError } from "../../common/errors"; -import { Amount } from "../common"; +import { ValidationError } from '../../common/errors' +import { Amount } from '../common' import { BaseTransaction, GlobalFlags, isAmount, verifyBaseTransaction, -} from "./common"; +} from './common' export enum TrustSetFlagsEnum { tfSetfAuth = 0x00010000, @@ -17,19 +17,19 @@ export enum TrustSetFlagsEnum { } export interface TrustSetFlags extends GlobalFlags { - tfSetfAuth?: boolean; - tfSetNoRipple?: boolean; - tfClearNoRipple?: boolean; - tfSetFreeze?: boolean; - tfClearFreeze?: boolean; + tfSetfAuth?: boolean + tfSetNoRipple?: boolean + tfClearNoRipple?: boolean + tfSetFreeze?: boolean + tfClearFreeze?: boolean } export interface TrustSet extends BaseTransaction { - TransactionType: "TrustSet"; - LimitAmount: Amount; - QualityIn?: number; - QualityOut?: number; - Flags?: number | TrustSetFlags; + TransactionType: 'TrustSet' + LimitAmount: Amount + QualityIn?: number + QualityOut?: number + Flags?: number | TrustSetFlags } /** @@ -39,22 +39,22 @@ export interface TrustSet extends BaseTransaction { * @throws When the TrustSet is malformed. */ export function verifyTrustSet(tx: Record): void { - verifyBaseTransaction(tx); - const { LimitAmount, QualityIn, QualityOut } = tx; + verifyBaseTransaction(tx) + const { LimitAmount, QualityIn, QualityOut } = tx if (LimitAmount === undefined) { - throw new ValidationError("TrustSet: missing field LimitAmount"); + throw new ValidationError('TrustSet: missing field LimitAmount') } if (!isAmount(LimitAmount)) { - throw new ValidationError("TrustSet: invalid LimitAmount"); + throw new ValidationError('TrustSet: invalid LimitAmount') } - if (QualityIn !== undefined && typeof QualityIn !== "number") { - throw new ValidationError("TrustSet: QualityIn must be a number"); + if (QualityIn !== undefined && typeof QualityIn !== 'number') { + throw new ValidationError('TrustSet: QualityIn must be a number') } - if (QualityOut !== undefined && typeof QualityOut !== "number") { - throw new ValidationError("TrustSet: QualityOut must be a number"); + if (QualityOut !== undefined && typeof QualityOut !== 'number') { + throw new ValidationError('TrustSet: QualityOut must be a number') } } diff --git a/src/models/utils/index.ts b/src/models/utils/index.ts index 5c1ce128..04101078 100644 --- a/src/models/utils/index.ts +++ b/src/models/utils/index.ts @@ -7,9 +7,9 @@ */ export function onlyHasFields( obj: Record, - fields: string[] + fields: string[], ): boolean { - return Object.keys(obj).every((key: string) => fields.includes(key)); + return Object.keys(obj).every((key: string) => fields.includes(key)) } /** @@ -21,5 +21,5 @@ export function onlyHasFields( */ export function isFlagEnabled(Flags: number, checkFlag: number): boolean { // eslint-disable-next-line no-bitwise -- Flags require bitwise operations - return (checkFlag & Flags) === checkFlag; + return (checkFlag & Flags) === checkFlag } diff --git a/src/transaction/check-cancel.ts b/src/transaction/check-cancel.ts index bac05091..ec0b8430 100644 --- a/src/transaction/check-cancel.ts +++ b/src/transaction/check-cancel.ts @@ -1,37 +1,37 @@ -import type { Client } from ".."; +import type { Client } from '..' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import { prepareTransaction } from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import { prepareTransaction } from './utils' export interface CheckCancelParameters { - checkID: string; + checkID: string } function createCheckCancelTransaction( account: string, - cancel: CheckCancelParameters + cancel: CheckCancelParameters, ): TransactionJSON { const txJSON = { Account: account, - TransactionType: "CheckCancel", + TransactionType: 'CheckCancel', CheckID: cancel.checkID, - }; + } - return txJSON; + return txJSON } async function prepareCheckCancel( this: Client, address: string, checkCancel: CheckCancelParameters, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createCheckCancelTransaction(address, checkCancel); - return await prepareTransaction(txJSON, this, instructions); + const txJSON = createCheckCancelTransaction(address, checkCancel) + return await prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareCheckCancel; +export default prepareCheckCancel diff --git a/src/transaction/check-cash.ts b/src/transaction/check-cash.ts index 4cc51c0d..6d6476dd 100644 --- a/src/transaction/check-cash.ts +++ b/src/transaction/check-cash.ts @@ -1,57 +1,57 @@ -import type { Client } from ".."; -import { ValidationError } from "../common/errors"; -import { Amount } from "../common/types/objects"; -import { toRippledAmount } from "../utils"; +import type { Client } from '..' +import { ValidationError } from '../common/errors' +import { Amount } from '../common/types/objects' +import { toRippledAmount } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' export interface CheckCashParameters { - checkID: string; - amount?: Amount; - deliverMin?: Amount; + checkID: string + amount?: Amount + deliverMin?: Amount } function createCheckCashTransaction( account: string, - checkCash: CheckCashParameters + checkCash: CheckCashParameters, ): TransactionJSON { if (checkCash.amount && checkCash.deliverMin) { throw new ValidationError( '"amount" and "deliverMin" properties on ' + - "CheckCash are mutually exclusive" - ); + 'CheckCash are mutually exclusive', + ) } const txJSON: any = { Account: account, - TransactionType: "CheckCash", + TransactionType: 'CheckCash', CheckID: checkCash.checkID, - }; + } if (checkCash.amount != null) { - txJSON.Amount = toRippledAmount(checkCash.amount); + txJSON.Amount = toRippledAmount(checkCash.amount) } if (checkCash.deliverMin != null) { - txJSON.DeliverMin = toRippledAmount(checkCash.deliverMin); + txJSON.DeliverMin = toRippledAmount(checkCash.deliverMin) } - return txJSON; + return txJSON } async function prepareCheckCash( this: Client, address: string, checkCash: CheckCashParameters, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createCheckCashTransaction(address, checkCash); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createCheckCashTransaction(address, checkCash) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareCheckCash; +export default prepareCheckCash diff --git a/src/transaction/check-create.ts b/src/transaction/check-create.ts index 4bb777f6..dbdecb29 100644 --- a/src/transaction/check-create.ts +++ b/src/transaction/check-create.ts @@ -1,56 +1,56 @@ -import type { Client } from ".."; -import { Amount } from "../common/types/objects"; -import { ISOTimeToRippleTime, toRippledAmount } from "../utils"; +import type { Client } from '..' +import { Amount } from '../common/types/objects' +import { ISOTimeToRippleTime, toRippledAmount } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' export interface CheckCreateParameters { - destination: string; - sendMax: Amount; - destinationTag?: number; - expiration?: string; - invoiceID?: string; + destination: string + sendMax: Amount + destinationTag?: number + expiration?: string + invoiceID?: string } function createCheckCreateTransaction( account: string, - check: CheckCreateParameters + check: CheckCreateParameters, ): TransactionJSON { const txJSON: any = { Account: account, - TransactionType: "CheckCreate", + TransactionType: 'CheckCreate', Destination: check.destination, SendMax: toRippledAmount(check.sendMax), - }; + } if (check.destinationTag != null) { - txJSON.DestinationTag = check.destinationTag; + txJSON.DestinationTag = check.destinationTag } if (check.expiration != null) { - txJSON.Expiration = ISOTimeToRippleTime(check.expiration); + txJSON.Expiration = ISOTimeToRippleTime(check.expiration) } if (check.invoiceID != null) { - txJSON.InvoiceID = check.invoiceID; + txJSON.InvoiceID = check.invoiceID } - return txJSON; + return txJSON } async function prepareCheckCreate( this: Client, address: string, checkCreate: CheckCreateParameters, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createCheckCreateTransaction(address, checkCreate); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createCheckCreateTransaction(address, checkCreate) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareCheckCreate; +export default prepareCheckCreate diff --git a/src/transaction/combine.ts b/src/transaction/combine.ts index 5380c7f2..006c34fb 100644 --- a/src/transaction/combine.ts +++ b/src/transaction/combine.ts @@ -1,11 +1,11 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; -import { decodeAccountID } from "ripple-address-codec"; -import binary from "ripple-binary-codec"; -import { JsonObject } from "ripple-binary-codec/dist/types/serialized-type"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' +import { decodeAccountID } from 'ripple-address-codec' +import binary from 'ripple-binary-codec' +import { JsonObject } from 'ripple-binary-codec/dist/types/serialized-type' -import { ValidationError } from "../common/errors"; -import { computeBinaryTransactionHash } from "../utils/hashes"; +import { ValidationError } from '../common/errors' +import { computeBinaryTransactionHash } from '../utils/hashes' /** * The transactions should all be equal except for the 'Signers' field. @@ -16,23 +16,23 @@ function validateTransactionEquivalence(transactions: JsonObject[]) { const exampleTransaction = JSON.stringify({ ...transactions[0], Signers: null, - }); + }) if ( transactions .slice(1) .some( - (tx) => JSON.stringify({ ...tx, Signers: null }) !== exampleTransaction + (tx) => JSON.stringify({ ...tx, Signers: null }) !== exampleTransaction, ) ) { throw new ValidationError( - "txJSON is not the same for all signedTransactions" - ); + 'txJSON is not the same for all signedTransactions', + ) } } function addressToBigNumber(address) { - const hex = Buffer.from(decodeAccountID(address)).toString("hex"); - return new BigNumber(hex, 16); + const hex = Buffer.from(decodeAccountID(address)).toString('hex') + return new BigNumber(hex, 16) } /** @@ -46,17 +46,17 @@ function addressToBigNumber(address) { */ function compareSigners(a, b) { return addressToBigNumber(a.Signer.Account).comparedTo( - addressToBigNumber(b.Signer.Account) - ); + addressToBigNumber(b.Signer.Account), + ) } function getTransactionWithAllSigners(transactions: JsonObject[]): JsonObject { // Signers must be sorted - see compareSigners for more details const sortedSigners = _.flatMap(transactions, (tx) => tx.Signers) .filter((signer) => signer) - .sort(compareSigners); + .sort(compareSigners) - return { ...transactions[0], Signers: sortedSigners }; + return { ...transactions[0], Signers: sortedSigners } } /** @@ -67,16 +67,16 @@ function getTransactionWithAllSigners(transactions: JsonObject[]): JsonObject { * with a transaction id based on the combined transaction. */ function combine(signedTransactions: string[]): object { - const transactions: JsonObject[] = signedTransactions.map(binary.decode); - validateTransactionEquivalence(transactions); + const transactions: JsonObject[] = signedTransactions.map(binary.decode) + validateTransactionEquivalence(transactions) const signedTransaction = binary.encode( - getTransactionWithAllSigners(transactions) - ); + getTransactionWithAllSigners(transactions), + ) return { signedTransaction, id: computeBinaryTransactionHash(signedTransaction), - }; + } } -export default combine; +export default combine diff --git a/src/transaction/escrow-cancellation.ts b/src/transaction/escrow-cancellation.ts index 3ecae7e6..7063e239 100644 --- a/src/transaction/escrow-cancellation.ts +++ b/src/transaction/escrow-cancellation.ts @@ -1,45 +1,45 @@ -import type { Client } from ".."; -import { Memo } from "../common/types/objects"; +import type { Client } from '..' +import { Memo } from '../common/types/objects' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' export interface EscrowCancellation { - owner: string; - escrowSequence: number; + owner: string + escrowSequence: number // TODO: This ripple-lib memo format should be deprecated in favor of rippled's format. // If necessary, expose a public method for converting between the two formats. - memos?: Memo[]; + memos?: Memo[] } function createEscrowCancellationTransaction( account: string, - payment: EscrowCancellation + payment: EscrowCancellation, ): TransactionJSON { const txJSON: any = { - TransactionType: "EscrowCancel", + TransactionType: 'EscrowCancel', Account: account, Owner: payment.owner, OfferSequence: payment.escrowSequence, - }; - if (payment.memos != null) { - txJSON.Memos = payment.memos.map(utils.convertMemo); } - return txJSON; + if (payment.memos != null) { + txJSON.Memos = payment.memos.map(utils.convertMemo) + } + return txJSON } async function prepareEscrowCancellation( this: Client, address: string, escrowCancellation: EscrowCancellation, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { const txJSON = createEscrowCancellationTransaction( address, - escrowCancellation - ); - return utils.prepareTransaction(txJSON, this, instructions); + escrowCancellation, + ) + return utils.prepareTransaction(txJSON, this, instructions) } -export default prepareEscrowCancellation; +export default prepareEscrowCancellation diff --git a/src/transaction/escrow-creation.ts b/src/transaction/escrow-creation.ts index 454050d4..300518af 100644 --- a/src/transaction/escrow-creation.ts +++ b/src/transaction/escrow-creation.ts @@ -1,51 +1,51 @@ -import type { Client } from ".."; -import { Memo } from "../common/types/objects"; -import { ISOTimeToRippleTime, xrpToDrops } from "../utils"; +import type { Client } from '..' +import { Memo } from '../common/types/objects' +import { ISOTimeToRippleTime, xrpToDrops } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' -const ValidationError = utils.common.errors.ValidationError; +const ValidationError = utils.common.errors.ValidationError export interface EscrowCreation { - amount: string; - destination: string; - memos?: Memo[]; - condition?: string; - allowCancelAfter?: string; - allowExecuteAfter?: string; - sourceTag?: number; - destinationTag?: number; + amount: string + destination: string + memos?: Memo[] + condition?: string + allowCancelAfter?: string + allowExecuteAfter?: string + sourceTag?: number + destinationTag?: number } function createEscrowCreationTransaction( account: string, - payment: EscrowCreation + payment: EscrowCreation, ): TransactionJSON { const txJSON: any = { - TransactionType: "EscrowCreate", + TransactionType: 'EscrowCreate', Account: account, Destination: payment.destination, Amount: xrpToDrops(payment.amount), - }; + } if (payment.condition != null) { - txJSON.Condition = payment.condition; + txJSON.Condition = payment.condition } if (payment.allowCancelAfter != null) { - txJSON.CancelAfter = ISOTimeToRippleTime(payment.allowCancelAfter); + txJSON.CancelAfter = ISOTimeToRippleTime(payment.allowCancelAfter) } if (payment.allowExecuteAfter != null) { - txJSON.FinishAfter = ISOTimeToRippleTime(payment.allowExecuteAfter); + txJSON.FinishAfter = ISOTimeToRippleTime(payment.allowExecuteAfter) } if (payment.sourceTag != null) { - txJSON.SourceTag = payment.sourceTag; + txJSON.SourceTag = payment.sourceTag } if (payment.destinationTag != null) { - txJSON.DestinationTag = payment.destinationTag; + txJSON.DestinationTag = payment.destinationTag } if (payment.memos != null) { - txJSON.Memos = payment.memos.map(utils.convertMemo); + txJSON.Memos = payment.memos.map(utils.convertMemo) } if ( Boolean(payment.allowCancelAfter) && @@ -53,25 +53,25 @@ function createEscrowCreationTransaction( txJSON.CancelAfter <= txJSON.FinishAfter ) { throw new ValidationError( - "prepareEscrowCreation: " + - '"allowCancelAfter" must be after "allowExecuteAfter"' - ); + 'prepareEscrowCreation: ' + + '"allowCancelAfter" must be after "allowExecuteAfter"', + ) } - return txJSON; + return txJSON } async function prepareEscrowCreation( this: Client, address: string, escrowCreation: EscrowCreation, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createEscrowCreationTransaction(address, escrowCreation); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createEscrowCreationTransaction(address, escrowCreation) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareEscrowCreation; +export default prepareEscrowCreation diff --git a/src/transaction/escrow-execution.ts b/src/transaction/escrow-execution.ts index e39a0bff..57ba56ce 100644 --- a/src/transaction/escrow-execution.ts +++ b/src/transaction/escrow-execution.ts @@ -1,61 +1,61 @@ -import type { Client } from ".."; -import { Memo } from "../common/types/objects"; +import type { Client } from '..' +import { Memo } from '../common/types/objects' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' -const ValidationError = utils.common.errors.ValidationError; +const ValidationError = utils.common.errors.ValidationError export interface EscrowExecution { - owner: string; - escrowSequence: number; - memos?: Memo[]; - condition?: string; - fulfillment?: string; + owner: string + escrowSequence: number + memos?: Memo[] + condition?: string + fulfillment?: string } function createEscrowExecutionTransaction( account: string, - payment: EscrowExecution + payment: EscrowExecution, ): TransactionJSON { const txJSON: any = { - TransactionType: "EscrowFinish", + TransactionType: 'EscrowFinish', Account: account, Owner: payment.owner, OfferSequence: payment.escrowSequence, - }; + } if (Boolean(payment.condition) !== Boolean(payment.fulfillment)) { throw new ValidationError( '"condition" and "fulfillment" fields on' + - " EscrowFinish must only be specified together." - ); + ' EscrowFinish must only be specified together.', + ) } if (payment.condition != null) { - txJSON.Condition = payment.condition; + txJSON.Condition = payment.condition } if (payment.fulfillment != null) { - txJSON.Fulfillment = payment.fulfillment; + txJSON.Fulfillment = payment.fulfillment } if (payment.memos != null) { - txJSON.Memos = payment.memos.map(utils.convertMemo); + txJSON.Memos = payment.memos.map(utils.convertMemo) } - return txJSON; + return txJSON } async function prepareEscrowExecution( this: Client, address: string, escrowExecution: EscrowExecution, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createEscrowExecutionTransaction(address, escrowExecution); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createEscrowExecutionTransaction(address, escrowExecution) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareEscrowExecution; +export default prepareEscrowExecution diff --git a/src/transaction/order.ts b/src/transaction/order.ts index a8abac39..43b98538 100644 --- a/src/transaction/order.ts +++ b/src/transaction/order.ts @@ -1,67 +1,67 @@ -import type { Client } from ".."; -import { FormattedOrderSpecification } from "../common/types/objects/index"; -import { ISOTimeToRippleTime, toRippledAmount } from "../utils"; +import type { Client } from '..' +import { FormattedOrderSpecification } from '../common/types/objects/index' +import { ISOTimeToRippleTime, toRippledAmount } from '../utils' -import { Instructions, Prepare, OfferCreateTransaction } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, OfferCreateTransaction } from './types' +import * as utils from './utils' -const offerFlags = utils.common.txFlags.OfferCreate; +const offerFlags = utils.common.txFlags.OfferCreate function createOrderTransaction( account: string, - order: FormattedOrderSpecification + order: FormattedOrderSpecification, ): OfferCreateTransaction { const takerPays = toRippledAmount( - order.direction === "buy" ? order.quantity : order.totalPrice - ); + order.direction === 'buy' ? order.quantity : order.totalPrice, + ) const takerGets = toRippledAmount( - order.direction === "buy" ? order.totalPrice : order.quantity - ); + order.direction === 'buy' ? order.totalPrice : order.quantity, + ) const txJSON: Partial = { - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', Account: account, TakerGets: takerGets, TakerPays: takerPays, - }; + } - txJSON.Flags = 0; - if (order.direction === "sell") { - txJSON.Flags |= offerFlags.Sell; + txJSON.Flags = 0 + if (order.direction === 'sell') { + txJSON.Flags |= offerFlags.Sell } if (order.passive) { - txJSON.Flags |= offerFlags.Passive; + txJSON.Flags |= offerFlags.Passive } if (order.immediateOrCancel) { - txJSON.Flags |= offerFlags.ImmediateOrCancel; + txJSON.Flags |= offerFlags.ImmediateOrCancel } if (order.fillOrKill) { - txJSON.Flags |= offerFlags.FillOrKill; + txJSON.Flags |= offerFlags.FillOrKill } if (order.expirationTime != null) { - txJSON.Expiration = ISOTimeToRippleTime(order.expirationTime); + txJSON.Expiration = ISOTimeToRippleTime(order.expirationTime) } if (order.orderToReplace != null) { - txJSON.OfferSequence = order.orderToReplace; + txJSON.OfferSequence = order.orderToReplace } if (order.memos != null) { - txJSON.Memos = order.memos.map(utils.convertMemo); + txJSON.Memos = order.memos.map(utils.convertMemo) } - return txJSON as OfferCreateTransaction; + return txJSON as OfferCreateTransaction } async function prepareOrder( this: Client, address: string, order: FormattedOrderSpecification, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createOrderTransaction(address, order); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createOrderTransaction(address, order) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareOrder; +export default prepareOrder diff --git a/src/transaction/ordercancellation.ts b/src/transaction/ordercancellation.ts index eda78c20..34f86c62 100644 --- a/src/transaction/ordercancellation.ts +++ b/src/transaction/ordercancellation.ts @@ -1,38 +1,38 @@ -import type { Client } from ".."; +import type { Client } from '..' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' function createOrderCancellationTransaction( account: string, - orderCancellation: any + orderCancellation: any, ): TransactionJSON { const txJSON: any = { - TransactionType: "OfferCancel", + TransactionType: 'OfferCancel', Account: account, OfferSequence: orderCancellation.orderSequence, - }; - if (orderCancellation.memos != null) { - txJSON.Memos = orderCancellation.memos.map(utils.convertMemo); } - return txJSON; + if (orderCancellation.memos != null) { + txJSON.Memos = orderCancellation.memos.map(utils.convertMemo) + } + return txJSON } -function prepareOrderCancellation( +async function prepareOrderCancellation( this: Client, address: string, orderCancellation: object, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { const txJSON = createOrderCancellationTransaction( address, - orderCancellation - ); - return utils.prepareTransaction(txJSON, this, instructions); + orderCancellation, + ) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareOrderCancellation; +export default prepareOrderCancellation diff --git a/src/transaction/payment-channel-claim.ts b/src/transaction/payment-channel-claim.ts index 420c5d7a..c1107f65 100644 --- a/src/transaction/payment-channel-claim.ts +++ b/src/transaction/payment-channel-claim.ts @@ -1,87 +1,87 @@ -import type { Client } from ".."; -import { xrpToDrops } from "../utils"; +import type { Client } from '..' +import { xrpToDrops } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' -const ValidationError = utils.common.errors.ValidationError; -const claimFlags = utils.common.txFlags.PaymentChannelClaim; +const ValidationError = utils.common.errors.ValidationError +const claimFlags = utils.common.txFlags.PaymentChannelClaim export interface PaymentChannelClaim { - channel: string; - balance?: string; - amount?: string; - signature?: string; - publicKey?: string; - renew?: boolean; - close?: boolean; + channel: string + balance?: string + amount?: string + signature?: string + publicKey?: string + renew?: boolean + close?: boolean } function createPaymentChannelClaimTransaction( account: string, - claim: PaymentChannelClaim + claim: PaymentChannelClaim, ): TransactionJSON { const txJSON: TransactionJSON = { Account: account, - TransactionType: "PaymentChannelClaim", + TransactionType: 'PaymentChannelClaim', Channel: claim.channel, Flags: 0, - }; + } if (claim.balance != null) { - txJSON.Balance = xrpToDrops(claim.balance); + txJSON.Balance = xrpToDrops(claim.balance) } if (claim.amount != null) { - txJSON.Amount = xrpToDrops(claim.amount); + txJSON.Amount = xrpToDrops(claim.amount) } if (Boolean(claim.signature) !== Boolean(claim.publicKey)) { throw new ValidationError( '"signature" and "publicKey" fields on' + - " PaymentChannelClaim must only be specified together." - ); + ' PaymentChannelClaim must only be specified together.', + ) } if (claim.signature != null) { - txJSON.Signature = claim.signature; + txJSON.Signature = claim.signature } if (claim.publicKey != null) { - txJSON.PublicKey = claim.publicKey; + txJSON.PublicKey = claim.publicKey } if (claim.renew && claim.close) { throw new ValidationError( '"renew" and "close" flags on PaymentChannelClaim' + - " are mutually exclusive" - ); + ' are mutually exclusive', + ) } - txJSON.Flags = 0; + txJSON.Flags = 0 if (claim.renew) { - txJSON.Flags |= claimFlags.Renew; + txJSON.Flags |= claimFlags.Renew } if (claim.close) { - txJSON.Flags |= claimFlags.Close; + txJSON.Flags |= claimFlags.Close } - return txJSON; + return txJSON } async function preparePaymentChannelClaim( this: Client, address: string, paymentChannelClaim: PaymentChannelClaim, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { const txJSON = createPaymentChannelClaimTransaction( address, - paymentChannelClaim - ); - return await utils.prepareTransaction(txJSON, this, instructions); + paymentChannelClaim, + ) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default preparePaymentChannelClaim; +export default preparePaymentChannelClaim diff --git a/src/transaction/payment-channel-create.ts b/src/transaction/payment-channel-create.ts index d261a39f..6a729ea1 100644 --- a/src/transaction/payment-channel-create.ts +++ b/src/transaction/payment-channel-create.ts @@ -1,60 +1,60 @@ -import type { Client } from ".."; -import { ISOTimeToRippleTime, xrpToDrops } from "../utils"; +import type { Client } from '..' +import { ISOTimeToRippleTime, xrpToDrops } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' export interface PaymentChannelCreate { - amount: string; - destination: string; - settleDelay: number; - publicKey: string; - cancelAfter?: string; - sourceTag?: number; - destinationTag?: number; + amount: string + destination: string + settleDelay: number + publicKey: string + cancelAfter?: string + sourceTag?: number + destinationTag?: number } function createPaymentChannelCreateTransaction( account: string, - paymentChannel: PaymentChannelCreate + paymentChannel: PaymentChannelCreate, ): TransactionJSON { const txJSON: any = { Account: account, - TransactionType: "PaymentChannelCreate", + TransactionType: 'PaymentChannelCreate', Amount: xrpToDrops(paymentChannel.amount), Destination: paymentChannel.destination, SettleDelay: paymentChannel.settleDelay, PublicKey: paymentChannel.publicKey.toUpperCase(), - }; + } if (paymentChannel.cancelAfter != null) { - txJSON.CancelAfter = ISOTimeToRippleTime(paymentChannel.cancelAfter); + txJSON.CancelAfter = ISOTimeToRippleTime(paymentChannel.cancelAfter) } if (paymentChannel.sourceTag != null) { - txJSON.SourceTag = paymentChannel.sourceTag; + txJSON.SourceTag = paymentChannel.sourceTag } if (paymentChannel.destinationTag != null) { - txJSON.DestinationTag = paymentChannel.destinationTag; + txJSON.DestinationTag = paymentChannel.destinationTag } - return txJSON; + return txJSON } async function preparePaymentChannelCreate( this: Client, address: string, paymentChannelCreate: PaymentChannelCreate, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { const txJSON = createPaymentChannelCreateTransaction( address, - paymentChannelCreate - ); - return await utils.prepareTransaction(txJSON, this, instructions); + paymentChannelCreate, + ) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default preparePaymentChannelCreate; +export default preparePaymentChannelCreate diff --git a/src/transaction/payment-channel-fund.ts b/src/transaction/payment-channel-fund.ts index d3370e44..3a443a4f 100644 --- a/src/transaction/payment-channel-fund.ts +++ b/src/transaction/payment-channel-fund.ts @@ -1,48 +1,48 @@ -import type { Client } from ".."; -import { ISOTimeToRippleTime, xrpToDrops } from "../utils"; +import type { Client } from '..' +import { ISOTimeToRippleTime, xrpToDrops } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' export interface PaymentChannelFund { - channel: string; - amount: string; - expiration?: string; + channel: string + amount: string + expiration?: string } function createPaymentChannelFundTransaction( account: string, - fund: PaymentChannelFund + fund: PaymentChannelFund, ): TransactionJSON { const txJSON: TransactionJSON = { Account: account, - TransactionType: "PaymentChannelFund", + TransactionType: 'PaymentChannelFund', Channel: fund.channel, Amount: xrpToDrops(fund.amount), - }; - - if (fund.expiration != null) { - txJSON.Expiration = ISOTimeToRippleTime(fund.expiration); } - return txJSON; + if (fund.expiration != null) { + txJSON.Expiration = ISOTimeToRippleTime(fund.expiration) + } + + return txJSON } async function preparePaymentChannelFund( this: Client, address: string, paymentChannelFund: PaymentChannelFund, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { const txJSON = createPaymentChannelFundTransaction( address, - paymentChannelFund - ); - return await utils.prepareTransaction(txJSON, this, instructions); + paymentChannelFund, + ) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default preparePaymentChannelFund; +export default preparePaymentChannelFund diff --git a/src/transaction/payment.ts b/src/transaction/payment.ts index af034e94..467bd9a4 100644 --- a/src/transaction/payment.ts +++ b/src/transaction/payment.ts @@ -1,109 +1,109 @@ -import _ from "lodash"; +import _ from 'lodash' -import type { Client } from "../client"; +import type { Client } from '../client' import { Amount, Adjustment, MaxAdjustment, MinAdjustment, Memo, -} from "../common/types/objects"; -import { toRippledAmount, xrpToDrops } from "../utils"; +} from '../common/types/objects' +import { toRippledAmount, xrpToDrops } from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; -import { getClassicAccountAndTag, ClassicAccountAndTag } from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' +import { getClassicAccountAndTag, ClassicAccountAndTag } from './utils' -const paymentFlags = utils.common.txFlags.Payment; -const ValidationError = utils.common.errors.ValidationError; +const paymentFlags = utils.common.txFlags.Payment +const ValidationError = utils.common.errors.ValidationError export interface Payment { - source: Adjustment | MaxAdjustment; - destination: Adjustment | MinAdjustment; - paths?: string; - memos?: Memo[]; + source: Adjustment | MaxAdjustment + destination: Adjustment | MinAdjustment + paths?: string + memos?: Memo[] // A 256-bit hash that can be used to identify a particular payment - invoiceID?: string; + invoiceID?: string // A boolean that, if set to true, indicates that this payment should go // through even if the whole amount cannot be delivered because of a lack of // liquidity or funds in the source_account account - allowPartialPayment?: boolean; + allowPartialPayment?: boolean // A boolean that can be set to true if paths are specified and the sender // would like the Ripple Network to disregard any direct paths from // the source_account to the destination_account. This may be used to take // advantage of an arbitrage opportunity or by gateways wishing to issue // balances from a hot wallet to a user who has mistakenly set a trustline // directly to the hot wallet - noDirectRipple?: boolean; - limitQuality?: boolean; + noDirectRipple?: boolean + limitQuality?: boolean } function isMaxAdjustment( - source: Adjustment | MaxAdjustment + source: Adjustment | MaxAdjustment, ): source is MaxAdjustment { - return (source as MaxAdjustment).maxAmount != null; + return (source as MaxAdjustment).maxAmount != null } function isMinAdjustment( - destination: Adjustment | MinAdjustment + destination: Adjustment | MinAdjustment, ): destination is MinAdjustment { - return (destination as MinAdjustment).minAmount != null; + return (destination as MinAdjustment).minAmount != null } function isXRPToXRPPayment(payment: Payment): boolean { - const { source, destination } = payment; + const { source, destination } = payment const sourceCurrency = isMaxAdjustment(source) ? source.maxAmount.currency - : source.amount.currency; + : source.amount.currency const destinationCurrency = isMinAdjustment(destination) ? destination.minAmount.currency - : destination.amount.currency; + : destination.amount.currency return ( - (sourceCurrency === "XRP" || sourceCurrency === "drops") && - (destinationCurrency === "XRP" || destinationCurrency === "drops") - ); + (sourceCurrency === 'XRP' || sourceCurrency === 'drops') && + (destinationCurrency === 'XRP' || destinationCurrency === 'drops') + ) } function isIOUWithoutCounterparty(amount: Amount): boolean { return ( amount && - amount.currency !== "XRP" && - amount.currency !== "drops" && + amount.currency !== 'XRP' && + amount.currency !== 'drops' && amount.counterparty == null - ); + ) } 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 - [payment.source, payment.destination].forEach((adjustment) => { - ["amount", "minAmount", "maxAmount"].forEach((key) => { + ;[payment.source, payment.destination].forEach((adjustment) => { + ;['amount', 'minAmount', 'maxAmount'].forEach((key) => { if (isIOUWithoutCounterparty(adjustment[key])) { - adjustment[key].counterparty = adjustment.address; + adjustment[key].counterparty = adjustment.address } - }); - }); + }) + }) } function createMaximalAmount(amount: Amount): Amount { - const maxXRPValue = "100000000000"; + const maxXRPValue = '100000000000' // Equivalent to '9999999999999999e80' but we cannot use that because sign() // now checks that the encoded representation exactly matches the transaction // as it was originally provided. const maxIOUValue = - "999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000"; + '999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000' - let maxValue; - if (amount.currency === "XRP") { - maxValue = maxXRPValue; - } else if (amount.currency === "drops") { - maxValue = xrpToDrops(maxXRPValue); + let maxValue + if (amount.currency === 'XRP') { + maxValue = maxXRPValue + } else if (amount.currency === 'drops') { + maxValue = xrpToDrops(maxXRPValue) } else { - maxValue = maxIOUValue; + maxValue = maxIOUValue } - return { ...amount, value: maxValue }; + return { ...amount, value: maxValue } } /** @@ -124,33 +124,30 @@ function createMaximalAmount(amount: Amount): Amount { */ function validateAndNormalizeAddress( address: string, - expectedTag: number | undefined + expectedTag: number | undefined, ): ClassicAccountAndTag { - const classicAddress = getClassicAccountAndTag(address, expectedTag); + const classicAddress = getClassicAccountAndTag(address, expectedTag) classicAddress.tag = - classicAddress.tag === false ? undefined : classicAddress.tag; - return classicAddress; + classicAddress.tag === false ? undefined : classicAddress.tag + return classicAddress } function createPaymentTransaction( address: string, - paymentArgument: Payment + paymentArgument: Payment, ): TransactionJSON { - const payment = _.cloneDeep(paymentArgument); - applyAnyCounterpartyEncoding(payment); + const payment = _.cloneDeep(paymentArgument) + applyAnyCounterpartyEncoding(payment) const sourceAddressAndTag = validateAndNormalizeAddress( payment.source.address, - payment.source.tag - ); - const addressToVerifyAgainst = validateAndNormalizeAddress( - address, - undefined - ); + payment.source.tag, + ) + const addressToVerifyAgainst = validateAndNormalizeAddress(address, undefined) if ( addressToVerifyAgainst.classicAccount !== sourceAddressAndTag.classicAccount ) { - throw new ValidationError("address must match payment.source.address"); + throw new ValidationError('address must match payment.source.address') } if ( @@ -159,31 +156,31 @@ function createPaymentTransaction( addressToVerifyAgainst.tag !== sourceAddressAndTag.tag ) { throw new ValidationError( - "address includes a tag that does not match payment.source.tag" - ); + 'address includes a tag that does not match payment.source.tag', + ) } const destinationAddressAndTag = validateAndNormalizeAddress( payment.destination.address, - payment.destination.tag - ); + payment.destination.tag, + ) if ( (isMaxAdjustment(payment.source) && isMinAdjustment(payment.destination)) || (!isMaxAdjustment(payment.source) && !isMinAdjustment(payment.destination)) ) { throw new ValidationError( - "payment must specify either (source.maxAmount " + - "and destination.amount) or (source.amount and destination.minAmount)" - ); + 'payment must specify either (source.maxAmount ' + + 'and destination.amount) or (source.amount and destination.minAmount)', + ) } const destinationAmount = isMinAdjustment(payment.destination) ? payment.destination.minAmount - : payment.destination.amount; + : payment.destination.amount const sourceAmount = isMaxAdjustment(payment.source) ? payment.source.maxAmount - : payment.source.amount; + : payment.source.amount // when using destination.minAmount, rippled still requires that we set // a destination amount in addition to DeliverMin. the destination amount @@ -194,33 +191,33 @@ function createPaymentTransaction( const amount = isMinAdjustment(payment.destination) && !isXRPToXRPPayment(payment) ? createMaximalAmount(destinationAmount) - : destinationAmount; + : destinationAmount const txJSON: any = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: sourceAddressAndTag.classicAccount, Destination: destinationAddressAndTag.classicAccount, Amount: toRippledAmount(amount), Flags: 0, - }; + } if (payment.invoiceID != null) { - txJSON.InvoiceID = payment.invoiceID; + txJSON.InvoiceID = payment.invoiceID } if (sourceAddressAndTag.tag != null) { - txJSON.SourceTag = sourceAddressAndTag.tag; + txJSON.SourceTag = sourceAddressAndTag.tag } if (destinationAddressAndTag.tag != null) { - txJSON.DestinationTag = destinationAddressAndTag.tag; + txJSON.DestinationTag = destinationAddressAndTag.tag } if (payment.memos != null) { - txJSON.Memos = payment.memos.map(utils.convertMemo); + txJSON.Memos = payment.memos.map(utils.convertMemo) } if (payment.noDirectRipple) { - txJSON.Flags |= paymentFlags.NoRippleDirect; + txJSON.Flags |= paymentFlags.NoRippleDirect } if (payment.limitQuality) { - txJSON.Flags |= paymentFlags.LimitQuality; + txJSON.Flags |= paymentFlags.LimitQuality } if (!isXRPToXRPPayment(payment)) { // Don't set SendMax for XRP->XRP payment @@ -228,37 +225,37 @@ function createPaymentTransaction( // https://github.com/ripple/rippled/commit/ // c522ffa6db2648f1d8a987843e7feabf1a0b7de8/ if (payment.allowPartialPayment || isMinAdjustment(payment.destination)) { - txJSON.Flags |= paymentFlags.PartialPayment; + txJSON.Flags |= paymentFlags.PartialPayment } - txJSON.SendMax = toRippledAmount(sourceAmount); + txJSON.SendMax = toRippledAmount(sourceAmount) if (isMinAdjustment(payment.destination)) { - txJSON.DeliverMin = toRippledAmount(destinationAmount); + txJSON.DeliverMin = toRippledAmount(destinationAmount) } if (payment.paths != null) { - txJSON.Paths = JSON.parse(payment.paths); + txJSON.Paths = JSON.parse(payment.paths) } } else if (payment.allowPartialPayment) { - throw new ValidationError("XRP to XRP payments cannot be partial payments"); + throw new ValidationError('XRP to XRP payments cannot be partial payments') } - return txJSON; + return txJSON } async function preparePayment( this: Client, address: string, payment: Payment, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createPaymentTransaction(address, payment); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createPaymentTransaction(address, payment) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default preparePayment; +export default preparePayment diff --git a/src/transaction/settings.ts b/src/transaction/settings.ts index 332232f6..4e16b35d 100644 --- a/src/transaction/settings.ts +++ b/src/transaction/settings.ts @@ -1,40 +1,35 @@ -import * as assert from "assert"; +import * as assert from 'assert' -import BigNumber from "bignumber.js"; +import BigNumber from 'bignumber.js' -import type { Client } from ".."; -import { FormattedSettings, WeightedSigner } from "../common/types/objects"; +import type { Client } from '..' +import { FormattedSettings, WeightedSigner } from '../common/types/objects' import { Instructions, Prepare, SettingsTransaction, TransactionJSON, -} from "./types"; -import * as utils from "./utils"; +} from './types' +import * as utils from './utils' -const AccountSetFlags = utils.common.constants.AccountSetFlags; -const AccountFields = utils.common.constants.AccountFields; +const AccountSetFlags = utils.common.constants.AccountSetFlags +const AccountFields = utils.common.constants.AccountFields function setTransactionFlags( txJSON: TransactionJSON, - values: FormattedSettings + values: FormattedSettings, ) { - const keys = Object.keys(values).filter( - (key) => AccountSetFlags[key] != null - ); - assert.ok( - keys.length <= 1, - "ERROR: can only set one setting per transaction" - ); - const flagName = keys[0]; - const value = values[flagName]; - const index = AccountSetFlags[flagName]; + const keys = Object.keys(values).filter((key) => AccountSetFlags[key] != null) + assert.ok(keys.length <= 1, 'ERROR: can only set one setting per transaction') + const flagName = keys[0] + const value = values[flagName] + const index = AccountSetFlags[flagName] if (index != null) { if (value) { - txJSON.SetFlag = index; + txJSON.SetFlag = index } else { - txJSON.ClearFlag = index; + txJSON.ClearFlag = index } } } @@ -42,28 +37,28 @@ function setTransactionFlags( // Sets `null` fields to their `default`. function setTransactionFields( txJSON: TransactionJSON, - input: FormattedSettings + input: FormattedSettings, ) { - const fieldSchema = AccountFields; + const fieldSchema = AccountFields for (const fieldName in fieldSchema) { - const field = fieldSchema[fieldName]; - let value = input[field.name]; + const field = fieldSchema[fieldName] + let value = input[field.name] if (value === undefined) { - continue; + continue } // The value required to clear an account root field varies - if (value === null && field.hasOwnProperty("defaults")) { - value = field.defaults; + if (value === null && field.hasOwnProperty('defaults')) { + value = field.defaults } - if (field.encoding === "hex" && !field.length) { + if (field.encoding === 'hex' && !field.length) { // This is currently only used for Domain field - value = Buffer.from(value, "ascii").toString("hex").toUpperCase(); + value = Buffer.from(value, 'ascii').toString('hex').toUpperCase() } - txJSON[fieldName] = value; + txJSON[fieldName] = value } } @@ -81,7 +76,7 @@ function setTransactionFields( */ function convertTransferRate(transferRate: number): number { - return new BigNumber(transferRate).shiftedBy(9).toNumber(); + return new BigNumber(transferRate).shiftedBy(9).toNumber() } function formatSignerEntry(signer: WeightedSigner): object { @@ -90,79 +85,79 @@ function formatSignerEntry(signer: WeightedSigner): object { Account: signer.address, SignerWeight: signer.weight, }, - }; + } } function createSettingsTransactionWithoutMemos( account: string, - settings: FormattedSettings + settings: FormattedSettings, ): SettingsTransaction { if (settings.regularKey !== undefined) { const removeRegularKey = { - TransactionType: "SetRegularKey", + TransactionType: 'SetRegularKey', Account: account, - }; - if (settings.regularKey === null) { - return removeRegularKey; } - return { ...removeRegularKey, RegularKey: settings.regularKey }; + if (settings.regularKey === null) { + return removeRegularKey + } + return { ...removeRegularKey, RegularKey: settings.regularKey } } if (settings.signers != null) { const setSignerList: SettingsTransaction = { - TransactionType: "SignerListSet", + TransactionType: 'SignerListSet', Account: account, SignerEntries: [], SignerQuorum: settings.signers.threshold, - }; + } if (settings.signers.weights != null) { setSignerList.SignerEntries = - settings.signers.weights.map(formatSignerEntry); + settings.signers.weights.map(formatSignerEntry) } - return setSignerList; + return setSignerList } const txJSON: SettingsTransaction = { - TransactionType: "AccountSet", + TransactionType: 'AccountSet', Account: account, - }; + } - const settingsWithoutMemos = { ...settings }; - delete settingsWithoutMemos.memos; - setTransactionFlags(txJSON, settingsWithoutMemos); - setTransactionFields(txJSON, settings); // Sets `null` fields to their `default`. + const settingsWithoutMemos = { ...settings } + delete settingsWithoutMemos.memos + setTransactionFlags(txJSON, settingsWithoutMemos) + setTransactionFields(txJSON, settings) // Sets `null` fields to their `default`. if (txJSON.TransferRate != null) { - txJSON.TransferRate = convertTransferRate(txJSON.TransferRate); + txJSON.TransferRate = convertTransferRate(txJSON.TransferRate) } - return txJSON; + return txJSON } function createSettingsTransaction( account: string, - settings: FormattedSettings + settings: FormattedSettings, ): SettingsTransaction { - const txJSON = createSettingsTransactionWithoutMemos(account, settings); + const txJSON = createSettingsTransactionWithoutMemos(account, settings) if (settings.memos != null) { - txJSON.Memos = settings.memos.map(utils.convertMemo); + txJSON.Memos = settings.memos.map(utils.convertMemo) } - return txJSON; + return txJSON } async function prepareSettings( this: Client, address: string, settings: FormattedSettings, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createSettingsTransaction(address, settings); + const txJSON = createSettingsTransaction(address, settings) - return await utils.prepareTransaction(txJSON, this, instructions); + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareSettings; +export default prepareSettings diff --git a/src/transaction/sign.ts b/src/transaction/sign.ts index 21a77eb9..1ce284cb 100644 --- a/src/transaction/sign.ts +++ b/src/transaction/sign.ts @@ -1,21 +1,21 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; -import binaryCodec from "ripple-binary-codec"; -import keypairs from "ripple-keypairs"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' +import binaryCodec from 'ripple-binary-codec' +import keypairs from 'ripple-keypairs' -import type { Client, Wallet } from ".."; -import { SignedTransaction } from "../common/types/objects"; -import { xrpToDrops } from "../utils"; -import { computeBinaryTransactionHash } from "../utils/hashes"; +import type { Client, Wallet } from '..' +import { SignedTransaction } from '../common/types/objects' +import { xrpToDrops } from '../utils' +import { computeBinaryTransactionHash } from '../utils/hashes' -import { SignOptions, KeyPair, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { SignOptions, KeyPair, TransactionJSON } from './types' +import * as utils from './utils' function computeSignature(tx: object, privateKey: string, signAs?: string) { const signingData = signAs ? binaryCodec.encodeForMultisigning(tx, signAs) - : binaryCodec.encodeForSigning(tx); - return keypairs.sign(signingData, privateKey); + : binaryCodec.encodeForSigning(tx) + return keypairs.sign(signingData, privateKey) } function signWithKeypair( @@ -23,23 +23,23 @@ function signWithKeypair( txJSON: string, keypair: KeyPair, options: SignOptions = { - signAs: "", - } + signAs: '', + }, ): SignedTransaction { - const tx = JSON.parse(txJSON); + const tx = JSON.parse(txJSON) if (tx.TxnSignature || tx.Signers) { throw new utils.common.errors.ValidationError( - 'txJSON must not contain "TxnSignature" or "Signers" properties' - ); + 'txJSON must not contain "TxnSignature" or "Signers" properties', + ) } if (client != null) { - checkFee(client, tx.Fee); + checkFee(client, tx.Fee) } - const txToSignAndEncode = { ...tx }; + const txToSignAndEncode = { ...tx } - txToSignAndEncode.SigningPubKey = options.signAs ? "" : keypair.publicKey; + txToSignAndEncode.SigningPubKey = options.signAs ? '' : keypair.publicKey if (options.signAs) { const signer = { @@ -48,22 +48,22 @@ function signWithKeypair( TxnSignature: computeSignature( txToSignAndEncode, keypair.privateKey, - options.signAs + options.signAs, ), - }; - txToSignAndEncode.Signers = [{ Signer: signer }]; + } + txToSignAndEncode.Signers = [{ Signer: signer }] } else { txToSignAndEncode.TxnSignature = computeSignature( txToSignAndEncode, - keypair.privateKey - ); + keypair.privateKey, + ) } - const serialized = binaryCodec.encode(txToSignAndEncode); - checkTxSerialization(serialized, tx); + const serialized = binaryCodec.encode(txToSignAndEncode) + checkTxSerialization(serialized, tx) return { signedTransaction: serialized, id: computeBinaryTransactionHash(serialized), - }; + } } /** @@ -75,48 +75,48 @@ function signWithKeypair( * @returns An object containing the differences between the two objects. */ function objectDiff(a: object, b: object): object { - const diffs = {}; + const diffs = {} // Compare two items and push non-matches to object const compare = function (i1: any, i2: any, k: string): void { - const type1 = Object.prototype.toString.call(i1); - const type2 = Object.prototype.toString.call(i2); - if (type2 === "[object Undefined]") { - diffs[k] = null; // Indicate that the item has been removed - return; + const type1 = Object.prototype.toString.call(i1) + const type2 = Object.prototype.toString.call(i2) + if (type2 === '[object Undefined]') { + diffs[k] = null // Indicate that the item has been removed + return } if (type1 !== type2) { - diffs[k] = i2; // Indicate that the item has changed types - return; + diffs[k] = i2 // Indicate that the item has changed types + return } - if (type1 === "[object Object]") { - const objDiff = objectDiff(i1, i2); + if (type1 === '[object Object]') { + const objDiff = objectDiff(i1, i2) if (Object.keys(objDiff).length > 0) { - diffs[k] = objDiff; + diffs[k] = objDiff } - return; + return } - if (type1 === "[object Array]") { + if (type1 === '[object Array]') { if (!_.isEqual(i1, i2)) { - diffs[k] = i2; // If arrays do not match, add second item to diffs + diffs[k] = i2 // If arrays do not match, add second item to diffs } - return; + return } - if (type1 === "[object Function]") { + if (type1 === '[object Function]') { if (i1.toString() !== i2.toString()) { - diffs[k] = i2; // If functions differ, add second one to diffs + diffs[k] = i2 // If functions differ, add second one to diffs } - return; + return } if (i1 !== i2) { - diffs[k] = i2; + diffs[k] = i2 } - }; + } // Check items in first object for (const key in a) { if (a.hasOwnProperty(key)) { - compare(a[key], b[key], key); + compare(a[key], b[key], key) } } @@ -124,12 +124,12 @@ function objectDiff(a: object, b: object): object { for (const key in b) { if (b.hasOwnProperty(key)) { if (!a[key] && a[key] !== b[key]) { - diffs[key] = b[key]; + diffs[key] = b[key] } } } - return diffs; + return diffs } /** @@ -143,54 +143,54 @@ function objectDiff(a: object, b: object): object { */ function checkTxSerialization(serialized: string, tx: TransactionJSON): void { // Decode the serialized transaction: - const decoded = binaryCodec.decode(serialized); + const decoded = binaryCodec.decode(serialized) // ...And ensure it is equal to the original tx, except: // - It must have a TxnSignature or Signers (multisign). if (!decoded.TxnSignature && !decoded.Signers) { throw new utils.common.errors.ValidationError( - "Serialized transaction must have a TxnSignature or Signers property" - ); + 'Serialized transaction must have a TxnSignature or Signers property', + ) } // - We know that the original tx did not have TxnSignature, so we should delete it: - delete decoded.TxnSignature; + delete decoded.TxnSignature // - We know that the original tx did not have Signers, so if it exists, we should delete it: - delete decoded.Signers; + delete decoded.Signers // - If SigningPubKey was not in the original tx, then we should delete it. // But if it was in the original tx, then we should ensure that it has not been changed. if (!tx.SigningPubKey) { - delete decoded.SigningPubKey; + delete decoded.SigningPubKey } // - Memos have exclusively hex data which should ignore case. // Since decode goes to upper case, we set all tx memos to be uppercase for the comparison. tx.Memos?.map((memo) => { if (memo.Memo.MemoData) { - memo.Memo.MemoData = memo.Memo.MemoData.toUpperCase(); + memo.Memo.MemoData = memo.Memo.MemoData.toUpperCase() } if (memo.Memo.MemoType) { - memo.Memo.MemoType = memo.Memo.MemoType.toUpperCase(); + memo.Memo.MemoType = memo.Memo.MemoType.toUpperCase() } if (memo.Memo.MemoFormat) { - memo.Memo.MemoFormat = memo.Memo.MemoFormat.toUpperCase(); + memo.Memo.MemoFormat = memo.Memo.MemoFormat.toUpperCase() } - return memo; - }); + return memo + }) if (!_.isEqual(decoded, tx)) { const error = new utils.common.errors.ValidationError( - "Serialized transaction does not match original txJSON. See `error.data`" - ); + 'Serialized transaction does not match original txJSON. See `error.data`', + ) error.data = { decoded, tx, diff: objectDiff(tx, decoded), - }; - throw error; + } + throw error } } @@ -205,13 +205,13 @@ function checkTxSerialization(serialized: string, tx: TransactionJSON): void { * @returns This method does not return a value, but throws an error if the check fails. */ function checkFee(client: Client, txFee: string): void { - const fee = new BigNumber(txFee); - const maxFeeDrops = xrpToDrops(client.maxFeeXRP); + const fee = new BigNumber(txFee) + const maxFeeDrops = xrpToDrops(client.maxFeeXRP) if (fee.isGreaterThan(maxFeeDrops)) { throw new utils.common.errors.ValidationError( `"Fee" should not exceed "${maxFeeDrops}". ` + - "To use a higher fee, set `maxFeeXRP` in the Client constructor." - ); + 'To use a higher fee, set `maxFeeXRP` in the Client constructor.', + ) } } @@ -220,35 +220,35 @@ function sign( txJSON: string, secret?: any, options?: SignOptions, - keypair?: KeyPair + keypair?: KeyPair, ): SignedTransaction { - if (typeof secret === "string") { + if (typeof secret === 'string') { // we can't validate that the secret matches the account because // the secret could correspond to the regular key return signWithKeypair( this, txJSON, keypairs.deriveKeypair(secret), - options - ); + options, + ) } if (!keypair && !secret) { // Clearer message than 'ValidationError: instance is not exactly one from [subschema 0],[subschema 1]' throw new utils.common.errors.ValidationError( - "sign: Missing secret or keypair." - ); + 'sign: Missing secret or keypair.', + ) } - return signWithKeypair(this, txJSON, keypair || secret, options); + return signWithKeypair(this, txJSON, keypair || secret, options) } // TODO: move this to Wallet class function signOffline( wallet: Wallet, txJSON: string, - options?: SignOptions + options?: SignOptions, ): SignedTransaction { - const { publicKey, privateKey } = wallet; - return signWithKeypair(null, txJSON, { publicKey, privateKey }, options); + const { publicKey, privateKey } = wallet + return signWithKeypair(null, txJSON, { publicKey, privateKey }, options) } -export { sign, signOffline }; +export { sign, signOffline } diff --git a/src/transaction/ticket.ts b/src/transaction/ticket.ts index 7b4a1421..4c91125d 100644 --- a/src/transaction/ticket.ts +++ b/src/transaction/ticket.ts @@ -1,46 +1,46 @@ -import _ from "lodash"; +import _ from 'lodash' -import type { Client } from ".."; +import type { Client } from '..' -import { Prepare, TransactionJSON, Instructions } from "./types"; -import * as utils from "./utils"; +import { Prepare, TransactionJSON, Instructions } from './types' +import * as utils from './utils' -const ValidationError = utils.common.errors.ValidationError; +const ValidationError = utils.common.errors.ValidationError export interface Ticket { - account: string; - sequence: number; + account: string + sequence: number } function createTicketTransaction( account: string, - ticketCount: number + ticketCount: number, ): TransactionJSON { if (!ticketCount || ticketCount === 0) { - throw new ValidationError("Ticket count must be greater than 0."); + throw new ValidationError('Ticket count must be greater than 0.') } const txJSON: any = { - TransactionType: "TicketCreate", + TransactionType: 'TicketCreate', Account: account, TicketCount: ticketCount, - }; + } - return txJSON; + return txJSON } -function prepareTicketCreate( +async function prepareTicketCreate( this: Client, address: string, ticketCount: number, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createTicketTransaction(address, ticketCount); - return utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createTicketTransaction(address, ticketCount) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareTicketCreate; +export default prepareTicketCreate diff --git a/src/transaction/trustline.ts b/src/transaction/trustline.ts index b99fd1b7..db633570 100644 --- a/src/transaction/trustline.ts +++ b/src/transaction/trustline.ts @@ -1,73 +1,73 @@ -import BigNumber from "bignumber.js"; +import BigNumber from 'bignumber.js' -import type { Client } from ".."; -import { FormattedTrustlineSpecification } from "../common/types/objects/trustlines"; +import type { Client } from '..' +import { FormattedTrustlineSpecification } from '../common/types/objects/trustlines' -import { Instructions, Prepare, TransactionJSON } from "./types"; -import * as utils from "./utils"; +import { Instructions, Prepare, TransactionJSON } from './types' +import * as utils from './utils' -const trustlineFlags = utils.common.txFlags.TrustSet; +const trustlineFlags = utils.common.txFlags.TrustSet function convertQuality(quality) { return new BigNumber(quality) .shiftedBy(9) .integerValue(BigNumber.ROUND_DOWN) - .toNumber(); + .toNumber() } function createTrustlineTransaction( account: string, - trustline: FormattedTrustlineSpecification + trustline: FormattedTrustlineSpecification, ): TransactionJSON { const limit = { currency: trustline.currency, issuer: trustline.counterparty, value: trustline.limit, - }; + } const txJSON: any = { - TransactionType: "TrustSet", + TransactionType: 'TrustSet', Account: account, LimitAmount: limit, Flags: 0, - }; + } if (trustline.qualityIn != null) { - txJSON.QualityIn = convertQuality(trustline.qualityIn); + txJSON.QualityIn = convertQuality(trustline.qualityIn) } if (trustline.qualityOut != null) { - txJSON.QualityOut = convertQuality(trustline.qualityOut); + txJSON.QualityOut = convertQuality(trustline.qualityOut) } if (trustline.authorized) { - txJSON.Flags |= trustlineFlags.SetAuth; + txJSON.Flags |= trustlineFlags.SetAuth } if (trustline.ripplingDisabled != null) { txJSON.Flags |= trustline.ripplingDisabled ? trustlineFlags.NoRipple - : trustlineFlags.ClearNoRipple; + : trustlineFlags.ClearNoRipple } if (trustline.frozen != null) { txJSON.Flags |= trustline.frozen ? trustlineFlags.SetFreeze - : trustlineFlags.ClearFreeze; + : trustlineFlags.ClearFreeze } if (trustline.memos != null) { - txJSON.Memos = trustline.memos.map(utils.convertMemo); + txJSON.Memos = trustline.memos.map(utils.convertMemo) } - return txJSON; + return txJSON } async function prepareTrustline( this: Client, address: string, trustline: FormattedTrustlineSpecification, - instructions: Instructions = {} + instructions: Instructions = {}, ): Promise { try { - const txJSON = createTrustlineTransaction(address, trustline); - return await utils.prepareTransaction(txJSON, this, instructions); + const txJSON = createTrustlineTransaction(address, trustline) + return await utils.prepareTransaction(txJSON, this, instructions) } catch (e) { - return Promise.reject(e); + return Promise.reject(e) } } -export default prepareTrustline; +export default prepareTrustline diff --git a/src/transaction/types.ts b/src/transaction/types.ts index 3eabc39e..9a41fdc0 100644 --- a/src/transaction/types.ts +++ b/src/transaction/types.ts @@ -5,155 +5,155 @@ import { RippledAmount, Memo, FormattedSettings, -} from "../common/types/objects"; +} from '../common/types/objects' -import { ApiMemo } from "./utils"; +import { ApiMemo } from './utils' export interface TransactionJSON { - Account: string; - TransactionType: string; - Memos?: Array<{ Memo: ApiMemo }>; - Flags?: number; - Fulfillment?: string; - [Field: string]: string | number | any[] | RippledAmount | undefined; + Account: string + TransactionType: string + Memos?: Array<{ Memo: ApiMemo }> + Flags?: number + Fulfillment?: string + [Field: string]: string | number | any[] | RippledAmount | undefined } export interface Instructions { - sequence?: number; - ticketSequence?: number; - fee?: string; + sequence?: number + ticketSequence?: number + fee?: string // @deprecated - maxFee?: string; - maxLedgerVersion?: number; - maxLedgerVersionOffset?: number; - signersCount?: number; + maxFee?: string + maxLedgerVersion?: number + maxLedgerVersionOffset?: number + signersCount?: number } export interface Prepare { - txJSON: string; + txJSON: string instructions: { - fee: string; - sequence?: number; - ticketSequence?: number; - maxLedgerVersion?: number; - }; + fee: string + sequence?: number + ticketSequence?: number + maxLedgerVersion?: number + } } export interface Submit { - success: boolean; - engineResult: string; - engineResultCode: number; - engineResultMessage?: string; - txBlob?: string; - txJson?: object; + success: boolean + engineResult: string + engineResultCode: number + engineResultMessage?: string + txBlob?: string + txJson?: object } export interface OfferCreateTransaction extends TransactionJSON { - TransactionType: "OfferCreate"; - Account: string; - Fee: string; - Flags: number; - LastLedgerSequence: number; - Sequence: number; - TakerGets: RippledAmount; - TakerPays: RippledAmount; - Expiration?: number; - OfferSequence?: number; - Memos?: Array<{ Memo: ApiMemo }>; + TransactionType: 'OfferCreate' + Account: string + Fee: string + Flags: number + LastLedgerSequence: number + Sequence: number + TakerGets: RippledAmount + TakerPays: RippledAmount + Expiration?: number + OfferSequence?: number + Memos?: Array<{ Memo: ApiMemo }> } export interface SettingsTransaction extends TransactionJSON { - TransferRate?: number; + TransferRate?: number } export interface KeyPair { - publicKey: string; - privateKey: string; + publicKey: string + privateKey: string } export interface SignOptions { - signAs: string; + signAs: string } export interface Outcome { - result: string; - ledgerVersion: number; - indexInLedger: number; - fee: string; + result: string + ledgerVersion: number + indexInLedger: number + fee: string balanceChanges: { [key: string]: Array<{ - currency: string; - counterparty?: string; - value: string; - }>; - }; - orderbookChanges: object; + currency: string + counterparty?: string + value: string + }> + } + orderbookChanges: object deliveredAmount?: { - currency: string; - counterparty?: string; - value: string; - }; - timestamp?: string; + currency: string + counterparty?: string + value: string + } + timestamp?: string } export interface FormattedOrderCancellation { - orderSequence: number; + orderSequence: number } export interface FormattedPayment { - source: Adjustment; - destination: Adjustment; - paths?: string; - memos?: Memo[]; - invoiceID?: string; - allowPartialPayment?: boolean; - noDirectRipple?: boolean; - limitQuality?: boolean; + source: Adjustment + destination: Adjustment + paths?: string + memos?: Memo[] + invoiceID?: string + allowPartialPayment?: boolean + noDirectRipple?: boolean + limitQuality?: boolean } export interface FormattedPaymentTransaction { - type: string; - specification: FormattedPayment; - outcome: Outcome; - id: string; - address: string; - sequence: number; + type: string + specification: FormattedPayment + outcome: Outcome + id: string + address: string + sequence: number } export interface FormattedOrderTransaction { - type: string; - specification: FormattedOrderSpecification; - outcome: Outcome; - id: string; - address: string; - sequence: number; + type: string + specification: FormattedOrderSpecification + outcome: Outcome + id: string + address: string + sequence: number } export interface FormattedOrderCancellationTransaction { - type: string; - specification: FormattedOrderCancellation; - outcome: Outcome; - id: string; - address: string; - sequence: number; + type: string + specification: FormattedOrderCancellation + outcome: Outcome + id: string + address: string + sequence: number } export interface FormattedTrustlineTransaction { - type: string; - specification: FormattedTrustlineSpecification; - outcome: Outcome; - id: string; - address: string; - sequence: number; + type: string + specification: FormattedTrustlineSpecification + outcome: Outcome + id: string + address: string + sequence: number } export interface FormattedSettingsTransaction { - type: string; - specification: FormattedSettings; - outcome: Outcome; - id: string; - address: string; - sequence: number; + type: string + specification: FormattedSettings + outcome: Outcome + id: string + address: string + sequence: number } export type FormattedTransactionType = @@ -161,4 +161,4 @@ export type FormattedTransactionType = | FormattedOrderTransaction | FormattedOrderCancellationTransaction | FormattedTrustlineTransaction - | FormattedSettingsTransaction; + | FormattedSettingsTransaction diff --git a/src/transaction/utils.ts b/src/transaction/utils.ts index 02cb1dce..c6fef06e 100644 --- a/src/transaction/utils.ts +++ b/src/transaction/utils.ts @@ -1,34 +1,31 @@ -import BigNumber from "bignumber.js"; -import { - xAddressToClassicAddress, - isValidXAddress, -} from "ripple-address-codec"; +import BigNumber from 'bignumber.js' +import { xAddressToClassicAddress, isValidXAddress } from 'ripple-address-codec' -import type { Client } from ".."; -import * as common from "../common"; -import { ValidationError } from "../common/errors"; -import { Memo } from "../common/types/objects"; +import type { Client } from '..' +import * as common from '../common' +import { ValidationError } from '../common/errors' +import { Memo } from '../common/types/objects' import { toRippledAmount, dropsToXrp, removeUndefined, xrpToDrops, -} from "../utils"; +} from '../utils' -import { Instructions, Prepare, TransactionJSON } from "./types"; +import { Instructions, Prepare, TransactionJSON } from './types' -const txFlags = common.txFlags; +const txFlags = common.txFlags const TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD = [ - "Payment", - "CheckCreate", - "EscrowCreate", - "PaymentChannelCreate", -]; + 'Payment', + 'CheckCreate', + 'EscrowCreate', + 'PaymentChannelCreate', +] export interface ApiMemo { - MemoData?: string; - MemoType?: string; - MemoFormat?: string; + MemoData?: string + MemoType?: string + MemoFormat?: string } // TODO: move relevant methods from here to `src/utils` (such as `convertStringToHex`?) @@ -38,16 +35,16 @@ function formatPrepareResponse(txJSON: any): Prepare { fee: dropsToXrp(txJSON.Fee), maxLedgerVersion: txJSON.LastLedgerSequence == null ? null : txJSON.LastLedgerSequence, - }; + } if (txJSON.TicketSequence != null) { - instructions.ticketSequence = txJSON.TicketSequence; + instructions.ticketSequence = txJSON.TicketSequence } else { - instructions.sequence = txJSON.Sequence; + instructions.sequence = txJSON.Sequence } return { txJSON: JSON.stringify(txJSON), instructions, - }; + } } /** @@ -62,18 +59,18 @@ function formatPrepareResponse(txJSON: any): Prepare { */ function setCanonicalFlag(txJSON: TransactionJSON): void { if (txJSON.Flags == null) { - txJSON.Flags = 0; + txJSON.Flags = 0 } - txJSON.Flags |= txFlags.Universal.FullyCanonicalSig; + txJSON.Flags |= txFlags.Universal.FullyCanonicalSig // JavaScript converts operands to 32-bit signed ints before doing bitwise // operations. We need to convert it back to an unsigned int. - txJSON.Flags >>>= 0; + txJSON.Flags >>>= 0 } function scaleValue(value, multiplier, extra = 0) { - return new BigNumber(value).times(multiplier).plus(extra).toString(); + return new BigNumber(value).times(multiplier).plus(extra).toString() } /** @@ -84,8 +81,8 @@ function scaleValue(value, multiplier, extra = 0) { * `undefined` if the input could not specify whether a tag should be used. */ export interface ClassicAccountAndTag { - classicAccount: string; - tag: number | false | undefined; + classicAccount: string + tag: number | false | undefined } /** @@ -103,148 +100,148 @@ export interface ClassicAccountAndTag { */ function getClassicAccountAndTag( Account: string, - expectedTag?: number + expectedTag?: number, ): ClassicAccountAndTag { if (isValidXAddress(Account)) { - const classic = xAddressToClassicAddress(Account); + const classic = xAddressToClassicAddress(Account) if (expectedTag != null && classic.tag !== expectedTag) { throw new ValidationError( - "address includes a tag that does not match the tag specified in the transaction" - ); + 'address includes a tag that does not match the tag specified in the transaction', + ) } return { classicAccount: classic.classicAddress, tag: classic.tag, - }; + } } return { classicAccount: Account, tag: expectedTag, - }; + } } async function prepareTransaction( txJSON: TransactionJSON, client: Client, - instructions: Instructions + instructions: Instructions, ): Promise { // 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 != null && instructions.sequence === 0) { - return Promise.reject(new ValidationError("`sequence` cannot be 0")); + return Promise.reject(new ValidationError('`sequence` cannot be 0')) } const disallowedFieldsInTxJSON = [ - "maxLedgerVersion", - "maxLedgerVersionOffset", - "fee", - "sequence", - "ticketSequence", - ]; - const badFields = disallowedFieldsInTxJSON.filter((field) => txJSON[field]); + 'maxLedgerVersion', + 'maxLedgerVersionOffset', + 'fee', + 'sequence', + 'ticketSequence', + ] + const badFields = disallowedFieldsInTxJSON.filter((field) => txJSON[field]) if (badFields.length) { return Promise.reject( new ValidationError( - `txJSON additionalProperty "${badFields[0]}" exists in instance when not allowed` - ) - ); + `txJSON additionalProperty "${badFields[0]}" exists in instance when not allowed`, + ), + ) } - const newTxJSON = { ...txJSON }; + const newTxJSON = { ...txJSON } // To remove the signer list, `SignerEntries` field should be omitted. if (txJSON.SignerQuorum === 0) { - delete newTxJSON.SignerEntries; + delete newTxJSON.SignerEntries } // Sender: const { classicAccount, tag: sourceTag } = getClassicAccountAndTag( - txJSON.Account - ); - newTxJSON.Account = classicAccount; + txJSON.Account, + ) + newTxJSON.Account = classicAccount if (sourceTag != null) { if (txJSON.SourceTag && txJSON.SourceTag !== sourceTag) { return Promise.reject( new ValidationError( - "The `SourceTag`, if present, must match the tag of the `Account` X-address" - ) - ); + 'The `SourceTag`, if present, must match the tag of the `Account` X-address', + ), + ) } if (sourceTag) { - newTxJSON.SourceTag = sourceTag; + newTxJSON.SourceTag = sourceTag } } // Destination: - if (typeof txJSON.Destination === "string") { + if (typeof txJSON.Destination === 'string') { const { classicAccount: destinationAccount, tag: destinationTag } = - getClassicAccountAndTag(txJSON.Destination); - newTxJSON.Destination = destinationAccount; + getClassicAccountAndTag(txJSON.Destination) + newTxJSON.Destination = destinationAccount if (destinationTag != null) { if ( TRANSACTION_TYPES_WITH_DESTINATION_TAG_FIELD.includes( - txJSON.TransactionType + txJSON.TransactionType, ) ) { if (txJSON.DestinationTag && txJSON.DestinationTag !== destinationTag) { return Promise.reject( new ValidationError( - "The Payment `DestinationTag`, if present, must match the tag of the `Destination` X-address" - ) - ); + 'The Payment `DestinationTag`, if present, must match the tag of the `Destination` X-address', + ), + ) } if (destinationTag) { - newTxJSON.DestinationTag = destinationTag; + newTxJSON.DestinationTag = destinationTag } } } } function convertToClassicAccountIfPresent(fieldName: string): void { - const account = txJSON[fieldName]; - if (typeof account === "string") { - const { classicAccount: ca } = getClassicAccountAndTag(account); - newTxJSON[fieldName] = ca; + const account = txJSON[fieldName] + if (typeof account === 'string') { + const { classicAccount: ca } = getClassicAccountAndTag(account) + newTxJSON[fieldName] = ca } } function convertIssuedCurrencyToAccountIfPresent(fieldName: string): void { - const amount = txJSON[fieldName]; + const amount = txJSON[fieldName] if ( - typeof amount === "number" || + typeof amount === 'number' || amount instanceof Array || amount == null ) { - return; + return } - newTxJSON[fieldName] = toRippledAmount(amount); + newTxJSON[fieldName] = toRippledAmount(amount) } // DepositPreauth: - convertToClassicAccountIfPresent("Authorize"); - convertToClassicAccountIfPresent("Unauthorize"); + convertToClassicAccountIfPresent('Authorize') + convertToClassicAccountIfPresent('Unauthorize') // EscrowCancel, EscrowFinish: - convertToClassicAccountIfPresent("Owner"); + convertToClassicAccountIfPresent('Owner') // SetRegularKey: - convertToClassicAccountIfPresent("RegularKey"); + convertToClassicAccountIfPresent('RegularKey') // Payment - convertIssuedCurrencyToAccountIfPresent("Amount"); - convertIssuedCurrencyToAccountIfPresent("SendMax"); - convertIssuedCurrencyToAccountIfPresent("DeliverMin"); + convertIssuedCurrencyToAccountIfPresent('Amount') + convertIssuedCurrencyToAccountIfPresent('SendMax') + convertIssuedCurrencyToAccountIfPresent('DeliverMin') // OfferCreate - convertIssuedCurrencyToAccountIfPresent("TakerPays"); - convertIssuedCurrencyToAccountIfPresent("TakerGets"); + convertIssuedCurrencyToAccountIfPresent('TakerPays') + convertIssuedCurrencyToAccountIfPresent('TakerGets') // TrustSet - convertIssuedCurrencyToAccountIfPresent("LimitAmount"); + convertIssuedCurrencyToAccountIfPresent('LimitAmount') - setCanonicalFlag(newTxJSON); + setCanonicalFlag(newTxJSON) async function prepareMaxLedgerVersion(): Promise { // Up to one of the following is allowed: @@ -254,38 +251,38 @@ async function prepareTransaction( if (newTxJSON.LastLedgerSequence && instructions.maxLedgerVersion) { return Promise.reject( new ValidationError( - "`LastLedgerSequence` in txJSON and `maxLedgerVersion`" + - " in `instructions` cannot both be set" - ) - ); + '`LastLedgerSequence` in txJSON and `maxLedgerVersion`' + + ' in `instructions` cannot both be set', + ), + ) } if (newTxJSON.LastLedgerSequence && instructions.maxLedgerVersionOffset) { return Promise.reject( new ValidationError( - "`LastLedgerSequence` in txJSON and `maxLedgerVersionOffset`" + - " in `instructions` cannot both be set" - ) - ); + '`LastLedgerSequence` in txJSON and `maxLedgerVersionOffset`' + + ' in `instructions` cannot both be set', + ), + ) } if (newTxJSON.LastLedgerSequence) { - return Promise.resolve(); + return Promise.resolve() } if (instructions.maxLedgerVersion !== undefined) { if (instructions.maxLedgerVersion !== null) { - newTxJSON.LastLedgerSequence = instructions.maxLedgerVersion; + newTxJSON.LastLedgerSequence = instructions.maxLedgerVersion } - return Promise.resolve(); + return Promise.resolve() } const offset = instructions.maxLedgerVersionOffset != null ? instructions.maxLedgerVersionOffset - : 3; + : 3 return client - .request({ command: "ledger_current" }) + .request({ command: 'ledger_current' }) .then((response) => response.result.ledger_current_index) .then((ledgerVersion) => { - newTxJSON.LastLedgerSequence = ledgerVersion + offset; - }); + newTxJSON.LastLedgerSequence = ledgerVersion + offset + }) } async function prepareFee(): Promise { @@ -297,56 +294,56 @@ async function prepareTransaction( if (newTxJSON.Fee && instructions.fee) { return Promise.reject( new ValidationError( - "`Fee` in txJSON and `fee` in `instructions` cannot both be set" - ) - ); + '`Fee` in txJSON and `fee` in `instructions` cannot both be set', + ), + ) } if (newTxJSON.Fee) { // txJSON.Fee is set. Use this value and do not scale it. - return Promise.resolve(); + return Promise.resolve() } const multiplier = - instructions.signersCount == null ? 1 : instructions.signersCount + 1; + instructions.signersCount == null ? 1 : instructions.signersCount + 1 if (instructions.fee != null) { - const fee = new BigNumber(instructions.fee); + const fee = new BigNumber(instructions.fee) if (fee.isGreaterThan(client.maxFeeXRP)) { return Promise.reject( new ValidationError( `Fee of ${fee.toString(10)} XRP exceeds ` + `max of ${client.maxFeeXRP} XRP. To use this fee, increase ` + - "`maxFeeXRP` in the Client constructor." - ) - ); + '`maxFeeXRP` in the Client constructor.', + ), + ) } - newTxJSON.Fee = scaleValue(xrpToDrops(instructions.fee), multiplier); - return Promise.resolve(); + newTxJSON.Fee = scaleValue(xrpToDrops(instructions.fee), multiplier) + return Promise.resolve() } - const cushion = client.feeCushion; + const cushion = client.feeCushion return client.getFee(cushion).then(async (fee) => { return client - .request({ command: "fee" }) + .request({ command: 'fee' }) .then((response) => Number(response.result.drops.minimum_fee)) .then((feeRef) => { // feeRef is the reference transaction cost in "fee units" const extraFee = - newTxJSON.TransactionType !== "EscrowFinish" || + newTxJSON.TransactionType !== 'EscrowFinish' || newTxJSON.Fulfillment == null ? 0 : cushion * feeRef * (32 + Math.floor( - Buffer.from(newTxJSON.Fulfillment, "hex").length / 16 - )); - const feeDrops = xrpToDrops(fee); + Buffer.from(newTxJSON.Fulfillment, 'hex').length / 16, + )) + const feeDrops = xrpToDrops(fee) const maxFeeXRP = instructions.maxFee ? BigNumber.min(client.maxFeeXRP, instructions.maxFee) - : client.maxFeeXRP; - const maxFeeDrops = xrpToDrops(maxFeeXRP); - const normalFee = scaleValue(feeDrops, multiplier, extraFee); - newTxJSON.Fee = BigNumber.min(normalFee, maxFeeDrops).toString(10); - }); - }); + : client.maxFeeXRP + const maxFeeDrops = xrpToDrops(maxFeeXRP) + const normalFee = scaleValue(feeDrops, multiplier, extraFee) + newTxJSON.Fee = BigNumber.min(normalFee, maxFeeDrops).toString(10) + }) + }) } async function prepareSequence(): Promise { @@ -355,38 +352,38 @@ async function prepareTransaction( newTxJSON.Sequence == null || instructions.sequence === newTxJSON.Sequence ) { - newTxJSON.Sequence = instructions.sequence; - return Promise.resolve(); + newTxJSON.Sequence = instructions.sequence + return Promise.resolve() } // Both txJSON.Sequence and instructions.sequence are defined, and they are NOT equal return Promise.reject( new ValidationError( - "`Sequence` in txJSON must match `sequence` in `instructions`" - ) - ); + '`Sequence` in txJSON must match `sequence` in `instructions`', + ), + ) } if (newTxJSON.Sequence != null) { - return Promise.resolve(); + return Promise.resolve() } // Ticket Sequence if (instructions.ticketSequence != null) { - newTxJSON.Sequence = 0; - newTxJSON.TicketSequence = instructions.ticketSequence; - return Promise.resolve(); + newTxJSON.Sequence = 0 + newTxJSON.TicketSequence = instructions.ticketSequence + return Promise.resolve() } try { const response = await client.request({ - command: "account_info", + command: 'account_info', account: classicAccount, - ledger_index: "current", // Fix #999 - }); - newTxJSON.Sequence = response.result.account_data.Sequence; - return await Promise.resolve(); + ledger_index: 'current', // Fix #999 + }) + newTxJSON.Sequence = response.result.account_data.Sequence + return await Promise.resolve() } catch (e) { - return await Promise.reject(e); + return await Promise.reject(e) } } @@ -394,11 +391,11 @@ async function prepareTransaction( prepareMaxLedgerVersion(), prepareFee(), prepareSequence(), - ]).then(() => formatPrepareResponse(newTxJSON)); + ]).then(() => formatPrepareResponse(newTxJSON)) } function convertStringToHex(string: string): string { - return Buffer.from(string, "utf8").toString("hex").toUpperCase(); + return Buffer.from(string, 'utf8').toString('hex').toUpperCase() } function convertMemo(memo: Memo): { Memo: ApiMemo } { @@ -408,7 +405,7 @@ function convertMemo(memo: Memo): { Memo: ApiMemo } { MemoType: memo.type ? convertStringToHex(memo.type) : undefined, MemoFormat: memo.format ? convertStringToHex(memo.format) : undefined, }), - }; + } } export { @@ -418,4 +415,4 @@ export { common, setCanonicalFlag, getClassicAccountAndTag, -}; +} diff --git a/src/utils/derive.ts b/src/utils/derive.ts index 14682414..ab8f0da5 100644 --- a/src/utils/derive.ts +++ b/src/utils/derive.ts @@ -1,13 +1,13 @@ -import { classicAddressToXAddress } from "ripple-address-codec"; -import { deriveKeypair, deriveAddress } from "ripple-keypairs"; +import { classicAddressToXAddress } from 'ripple-address-codec' +import { deriveKeypair, deriveAddress } from 'ripple-keypairs' function deriveXAddress(options: { - publicKey: string; - tag: number | false; - test: boolean; + publicKey: string + tag: number | false + test: boolean }): string { - const classicAddress = deriveAddress(options.publicKey); - return classicAddressToXAddress(classicAddress, options.tag, options.test); + const classicAddress = deriveAddress(options.publicKey) + return classicAddressToXAddress(classicAddress, options.tag, options.test) } -export { deriveKeypair, deriveAddress, deriveXAddress }; +export { deriveKeypair, deriveAddress, deriveXAddress } diff --git a/src/utils/generateAddress.ts b/src/utils/generateAddress.ts index ee8f44c3..e5a769c9 100644 --- a/src/utils/generateAddress.ts +++ b/src/utils/generateAddress.ts @@ -1,65 +1,65 @@ -import { classicAddressToXAddress } from "ripple-address-codec"; -import keypairs from "ripple-keypairs"; +import { classicAddressToXAddress } from 'ripple-address-codec' +import keypairs from 'ripple-keypairs' -import { errors } from "../common"; -import ECDSA from "../common/ecdsa"; +import { errors } from '../common' +import ECDSA from '../common/ecdsa' export interface GeneratedAddress { - xAddress: string; - classicAddress?: string; - address?: string; // @deprecated Use `classicAddress` instead. - secret: string; + xAddress: string + classicAddress?: string + address?: string // @deprecated Use `classicAddress` instead. + secret: string } export interface GenerateAddressOptions { // The entropy to use to generate the seed. - entropy?: Uint8Array | number[]; + entropy?: Uint8Array | number[] // The digital signature algorithm to generate an address for. Can be `ecdsa-secp256k1` (default) or `ed25519`. - algorithm?: ECDSA; + algorithm?: ECDSA // Specifies whether the address is intended for use on a test network such as Testnet or Devnet. // If `true`, the address should only be used for testing, and will start with `T`. // If `false` (default), the address should only be used on mainnet, and will start with `X`. - test?: boolean; + test?: boolean // If `true`, return the classic address, in addition to the X-address. - includeClassicAddress?: boolean; + includeClassicAddress?: boolean } // TODO: move this function to be a static function of the Wallet class (Along with its helper data types) function generateXAddress( - options: GenerateAddressOptions = {} + options: GenerateAddressOptions = {}, ): GeneratedAddress { try { const generateSeedOptions: { - entropy?: Uint8Array; - algorithm?: ECDSA; + entropy?: Uint8Array + algorithm?: ECDSA } = { algorithm: options.algorithm, - }; - if (options.entropy) { - generateSeedOptions.entropy = Uint8Array.from(options.entropy); } - const secret = keypairs.generateSeed(generateSeedOptions); - const keypair = keypairs.deriveKeypair(secret); - const classicAddress = keypairs.deriveAddress(keypair.publicKey); + if (options.entropy) { + generateSeedOptions.entropy = Uint8Array.from(options.entropy) + } + const secret = keypairs.generateSeed(generateSeedOptions) + const keypair = keypairs.deriveKeypair(secret) + const classicAddress = keypairs.deriveAddress(keypair.publicKey) const returnValue: any = { xAddress: classicAddressToXAddress( classicAddress, false, - options.test ?? false + options.test ?? false, ), secret, - }; - if (options.includeClassicAddress) { - returnValue.classicAddress = classicAddress; - returnValue.address = classicAddress; } - return returnValue; + if (options.includeClassicAddress) { + returnValue.classicAddress = classicAddress + returnValue.address = classicAddress + } + return returnValue } catch (error) { - throw new errors.UnexpectedError(error.message); + throw new errors.UnexpectedError(error.message) } } -export { generateXAddress }; +export { generateXAddress } diff --git a/src/utils/hashes/hashPrefix.ts b/src/utils/hashes/hashPrefix.ts index 33fe5618..7bba4d15 100644 --- a/src/utils/hashes/hashPrefix.ts +++ b/src/utils/hashes/hashPrefix.ts @@ -37,4 +37,4 @@ enum HashPrefix { LEDGER = 0x4c575200, // 'LWR' } -export default HashPrefix; +export default HashPrefix diff --git a/src/utils/hashes/index.ts b/src/utils/hashes/index.ts index 5f38e97c..9b27a302 100644 --- a/src/utils/hashes/index.ts +++ b/src/utils/hashes/index.ts @@ -1,75 +1,75 @@ -import BigNumber from "bignumber.js"; -import { decodeAccountID } from "ripple-address-codec"; -import { encode } from "ripple-binary-codec"; +import BigNumber from 'bignumber.js' +import { decodeAccountID } from 'ripple-address-codec' +import { encode } from 'ripple-binary-codec' -import HashPrefix from "./hashPrefix"; -import ledgerSpaces from "./ledgerSpaces"; -import sha512Half from "./sha512Half"; -import { SHAMap, NodeType } from "./shamap"; +import HashPrefix from './hashPrefix' +import ledgerSpaces from './ledgerSpaces' +import sha512Half from './sha512Half' +import { SHAMap, NodeType } from './shamap' const padLeftZero = (string: string, length: number): string => { - return Array(length - string.length + 1).join("0") + string; -}; + return Array(length - string.length + 1).join('0') + string +} const intToHex = (integer: number, byteLength: number): string => { - return padLeftZero(Number(integer).toString(16), byteLength * 2); -}; + return padLeftZero(Number(integer).toString(16), byteLength * 2) +} const bytesToHex = (bytes: number[]): string => { - return Buffer.from(bytes).toString("hex"); -}; + return Buffer.from(bytes).toString('hex') +} const bigintToHex = ( integerString: string | number | BigNumber, - byteLength: number + byteLength: number, ): string => { - const hex = new BigNumber(integerString).toString(16); - return padLeftZero(hex, byteLength * 2); -}; + const hex = new BigNumber(integerString).toString(16) + return padLeftZero(hex, byteLength * 2) +} const ledgerSpaceHex = (name: string): string => { - return intToHex(ledgerSpaces[name].charCodeAt(0), 2); -}; + return intToHex(ledgerSpaces[name].charCodeAt(0), 2) +} const addressToHex = (address: string): string => { - return Buffer.from(decodeAccountID(address)).toString("hex"); -}; + return Buffer.from(decodeAccountID(address)).toString('hex') +} const currencyToHex = (currency: string): string => { if (currency.length === 3) { - const bytes = new Array(20 + 1).join("0").split("").map(parseFloat); - bytes[12] = currency.charCodeAt(0) & 0xff; - bytes[13] = currency.charCodeAt(1) & 0xff; - bytes[14] = currency.charCodeAt(2) & 0xff; - return bytesToHex(bytes); + const bytes = new Array(20 + 1).join('0').split('').map(parseFloat) + bytes[12] = currency.charCodeAt(0) & 0xff + bytes[13] = currency.charCodeAt(1) & 0xff + bytes[14] = currency.charCodeAt(2) & 0xff + return bytesToHex(bytes) } - return currency; -}; + return currency +} const addLengthPrefix = (hex: string): string => { - const length = hex.length / 2; + const length = hex.length / 2 if (length <= 192) { - return bytesToHex([length]) + hex; + return bytesToHex([length]) + hex } if (length <= 12480) { - const x = length - 193; - return bytesToHex([193 + (x >>> 8), x & 0xff]) + hex; + const x = length - 193 + return bytesToHex([193 + (x >>> 8), x & 0xff]) + hex } if (length <= 918744) { - const x = length - 12481; - return bytesToHex([241 + (x >>> 16), (x >>> 8) & 0xff, x & 0xff]) + hex; + const x = length - 12481 + return bytesToHex([241 + (x >>> 16), (x >>> 8) & 0xff, x & 0xff]) + hex } - throw new Error("Variable integer overflow."); -}; + throw new Error('Variable integer overflow.') +} export const computeBinaryTransactionHash = (txBlobHex: string): string => { - const prefix = HashPrefix.TRANSACTION_ID.toString(16).toUpperCase(); - return sha512Half(prefix + txBlobHex); -}; + const prefix = HashPrefix.TRANSACTION_ID.toString(16).toUpperCase() + return sha512Half(prefix + txBlobHex) +} export const computeTransactionHash = (txJSON: any): string => { - return computeBinaryTransactionHash(encode(txJSON)); -}; + return computeBinaryTransactionHash(encode(txJSON)) +} /** * Hash the given binary transaction data with the single-signing prefix. @@ -80,11 +80,11 @@ export const computeTransactionHash = (txJSON: any): string => { * @returns The hash to sign. */ export const computeBinaryTransactionSigningHash = ( - txBlobHex: string + txBlobHex: string, ): string => { - const prefix = HashPrefix.TRANSACTION_SIGN.toString(16).toUpperCase(); - return sha512Half(prefix + txBlobHex); -}; + const prefix = HashPrefix.TRANSACTION_SIGN.toString(16).toUpperCase() + return sha512Half(prefix + txBlobHex) +} /** * Compute Account Root Index. @@ -100,8 +100,8 @@ export const computeBinaryTransactionSigningHash = ( * @returns The Ledger Object Index for the account. */ export const computeAccountRootIndex = (address: string): string => { - return sha512Half(ledgerSpaceHex("account") + addressToHex(address)); -}; + return sha512Half(ledgerSpaceHex('account') + addressToHex(address)) +} /** * [SignerList ID Format](https://xrpl.org/signerlist.html#signerlist-id-format). @@ -118,9 +118,9 @@ export const computeAccountRootIndex = (address: string): string => { */ export const computeSignerListIndex = (address: string): string => { return sha512Half( - `${ledgerSpaceHex("signerList") + addressToHex(address)}00000000` - ); // uint32(0) signer list index -}; + `${ledgerSpaceHex('signerList') + addressToHex(address)}00000000`, + ) // uint32(0) signer list index +} /** * [Offer ID Format](https://xrpl.org/offer.html#offer-id-format). @@ -138,60 +138,60 @@ export const computeSignerListIndex = (address: string): string => { */ export const computeOfferIndex = ( address: string, - sequence: number + sequence: number, ): string => { - const prefix = `00${intToHex(ledgerSpaces.offer.charCodeAt(0), 1)}`; - return sha512Half(prefix + addressToHex(address) + intToHex(sequence, 4)); -}; + const prefix = `00${intToHex(ledgerSpaces.offer.charCodeAt(0), 1)}` + return sha512Half(prefix + addressToHex(address) + intToHex(sequence, 4)) +} export const computeTrustlineHash = ( address1: string, address2: string, - currency: string + currency: string, ): string => { - const address1Hex = addressToHex(address1); - const address2Hex = addressToHex(address2); + const address1Hex = addressToHex(address1) + const address2Hex = addressToHex(address2) const swap = new BigNumber(address1Hex, 16).isGreaterThan( - new BigNumber(address2Hex, 16) - ); - const lowAddressHex = swap ? address2Hex : address1Hex; - const highAddressHex = swap ? address1Hex : address2Hex; + new BigNumber(address2Hex, 16), + ) + const lowAddressHex = swap ? address2Hex : address1Hex + const highAddressHex = swap ? address1Hex : address2Hex - const prefix = ledgerSpaceHex("rippleState"); + const prefix = ledgerSpaceHex('rippleState') return sha512Half( - prefix + lowAddressHex + highAddressHex + currencyToHex(currency) - ); -}; + prefix + lowAddressHex + highAddressHex + currencyToHex(currency), + ) +} export const computeTransactionTreeHash = (transactions: any[]): string => { - const shamap = new SHAMap(); + const shamap = new SHAMap() transactions.forEach((txJSON) => { - const txBlobHex = encode(txJSON); - const metaHex = encode(txJSON.metaData); - const txHash = computeBinaryTransactionHash(txBlobHex); - const data = addLengthPrefix(txBlobHex) + addLengthPrefix(metaHex); - shamap.addItem(txHash, data, NodeType.TRANSACTION_METADATA); - }); + const txBlobHex = encode(txJSON) + const metaHex = encode(txJSON.metaData) + const txHash = computeBinaryTransactionHash(txBlobHex) + const data = addLengthPrefix(txBlobHex) + addLengthPrefix(metaHex) + shamap.addItem(txHash, data, NodeType.TRANSACTION_METADATA) + }) - return shamap.hash; -}; + return shamap.hash +} export const computeStateTreeHash = (entries: any[]): string => { - const shamap = new SHAMap(); + const shamap = new SHAMap() entries.forEach((ledgerEntry) => { - const data = encode(ledgerEntry); - shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE); - }); + const data = encode(ledgerEntry) + shamap.addItem(ledgerEntry.index, data, NodeType.ACCOUNT_STATE) + }) - return shamap.hash; -}; + return shamap.hash +} // see rippled Ledger::updateHash() export const computeLedgerHash = (ledgerHeader): string => { - const prefix = HashPrefix.LEDGER.toString(16).toUpperCase(); + const prefix = HashPrefix.LEDGER.toString(16).toUpperCase() return sha512Half( prefix + intToHex(ledgerHeader.ledger_index, 4) + @@ -202,25 +202,25 @@ export const computeLedgerHash = (ledgerHeader): string => { intToHex(ledgerHeader.parent_close_time, 4) + intToHex(ledgerHeader.close_time, 4) + intToHex(ledgerHeader.close_time_resolution, 1) + - intToHex(ledgerHeader.close_flags, 1) - ); -}; + intToHex(ledgerHeader.close_flags, 1), + ) +} export const computeEscrowHash = (address, sequence): string => { return sha512Half( - ledgerSpaceHex("escrow") + addressToHex(address) + intToHex(sequence, 4) - ); -}; + ledgerSpaceHex('escrow') + addressToHex(address) + intToHex(sequence, 4), + ) +} export const computePaymentChannelHash = ( address, dstAddress, - sequence + sequence, ): string => { return sha512Half( - ledgerSpaceHex("paychan") + + ledgerSpaceHex('paychan') + addressToHex(address) + addressToHex(dstAddress) + - intToHex(sequence, 4) - ); -}; + intToHex(sequence, 4), + ) +} diff --git a/src/utils/hashes/ledgerSpaces.ts b/src/utils/hashes/ledgerSpaces.ts index 14de8386..66477691 100644 --- a/src/utils/hashes/ledgerSpaces.ts +++ b/src/utils/hashes/ledgerSpaces.ts @@ -9,21 +9,21 @@ * See [LedgerNameSpace enum](https://github.com/ripple/rippled/blob/master/src/ripple/protocol/LedgerFormats.h#L100). */ export default { - account: "a", - dirNode: "d", - generatorMap: "g", - rippleState: "r", - offer: "o", // Entry for an offer. - ownerDir: "O", // Directory of things owned by an account. - bookDir: "B", // Directory of order books. - contract: "c", - skipList: "s", - escrow: "u", - amendment: "f", - feeSettings: "e", - ticket: "T", - signerList: "S", - paychan: "x", - check: "C", - depositPreauth: "p", -}; + account: 'a', + dirNode: 'd', + generatorMap: 'g', + rippleState: 'r', + offer: 'o', // Entry for an offer. + ownerDir: 'O', // Directory of things owned by an account. + bookDir: 'B', // Directory of order books. + contract: 'c', + skipList: 's', + escrow: 'u', + amendment: 'f', + feeSettings: 'e', + ticket: 'T', + signerList: 'S', + paychan: 'x', + check: 'C', + depositPreauth: 'p', +} diff --git a/src/utils/hashes/sha512Half.ts b/src/utils/hashes/sha512Half.ts index b327a098..52f51fde 100644 --- a/src/utils/hashes/sha512Half.ts +++ b/src/utils/hashes/sha512Half.ts @@ -1,11 +1,11 @@ -import { createHash } from "crypto"; +import { createHash } from 'crypto' const sha512Half = (hex: string): string => { - return createHash("sha512") - .update(Buffer.from(hex, "hex")) - .digest("hex") + return createHash('sha512') + .update(Buffer.from(hex, 'hex')) + .digest('hex') .toUpperCase() - .slice(0, 64); -}; + .slice(0, 64) +} -export default sha512Half; +export default sha512Half diff --git a/src/utils/hashes/shamap.ts b/src/utils/hashes/shamap.ts index dbf792b0..eff97ca8 100644 --- a/src/utils/hashes/shamap.ts +++ b/src/utils/hashes/shamap.ts @@ -1,8 +1,8 @@ -import hashPrefix from "./hashPrefix"; -import sha512Half from "./sha512Half"; +import hashPrefix from './hashPrefix' +import sha512Half from './sha512Half' const HEX_ZERO = - "0000000000000000000000000000000000000000000000000000000000000000"; + '0000000000000000000000000000000000000000000000000000000000000000' export enum NodeType { INNER = 1, @@ -22,20 +22,20 @@ export abstract class Node { public addItem(_tag: string, _node: Node): void { throw new Error( - "Called unimplemented virtual method SHAMapTreeNode#addItem." - ); + 'Called unimplemented virtual method SHAMapTreeNode#addItem.', + ) } public get hash(): string | void { - throw new Error("Called unimplemented virtual method SHAMapTreeNode#hash."); + throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.') } } export class InnerNode extends Node { - public leaves: { [slot: number]: Node }; - public type: NodeType; - public depth: number; - public empty: boolean; + public leaves: { [slot: number]: Node } + public type: NodeType + public depth: number + public empty: boolean /** * Define an Inner (non-leaf) node in a SHAMap tree. @@ -44,11 +44,11 @@ export class InnerNode extends Node { * @class */ public constructor(depth = 0) { - super(); - this.leaves = {}; - this.type = NodeType.INNER; - this.depth = depth; - this.empty = true; + super() + this.leaves = {} + this.type = NodeType.INNER + this.depth = depth + this.empty = true } /** @@ -58,33 +58,33 @@ export class InnerNode extends Node { */ public addItem(tag: string, node: Node): void { - const existingNode = this.getNode(parseInt(tag[this.depth], 16)); + const existingNode = this.getNode(parseInt(tag[this.depth], 16)) if (existingNode) { // A node already exists in this slot if (existingNode instanceof InnerNode) { // There is an inner node, so we need to go deeper - existingNode.addItem(tag, node); + existingNode.addItem(tag, node) } else if (existingNode instanceof Leaf) { if (existingNode.tag === tag) { // Collision throw new Error( - "Tried to add a node to a SHAMap that was already in there." - ); + 'Tried to add a node to a SHAMap that was already in there.', + ) } else { // Turn it into an inner node - const newInnerNode = new InnerNode(this.depth + 1); + const newInnerNode = new InnerNode(this.depth + 1) // Parent new and existing node - newInnerNode.addItem(existingNode.tag, existingNode); - newInnerNode.addItem(tag, node); + newInnerNode.addItem(existingNode.tag, existingNode) + newInnerNode.addItem(tag, node) // And place the newly created inner node in the slot - this.setNode(parseInt(tag[this.depth], 16), newInnerNode); + this.setNode(parseInt(tag[this.depth], 16), newInnerNode) } } } else { // Neat, we have a nice open spot for the new node - this.setNode(parseInt(tag[this.depth], 16), node); + this.setNode(parseInt(tag[this.depth], 16), node) } } @@ -97,10 +97,10 @@ export class InnerNode extends Node { */ public setNode(slot: number, node: Node): void { if (slot < 0 || slot > 15) { - throw new Error("Invalid slot: slot must be between 0-15."); + throw new Error('Invalid slot: slot must be between 0-15.') } - this.leaves[slot] = node; - this.empty = false; + this.leaves[slot] = node + this.empty = false } /** @@ -111,28 +111,28 @@ export class InnerNode extends Node { */ public getNode(slot: number): Node { if (slot < 0 || slot > 15) { - throw new Error("Invalid slot: slot must be between 0-15."); + throw new Error('Invalid slot: slot must be between 0-15.') } - return this.leaves[slot]; + return this.leaves[slot] } public get hash(): string { if (this.empty) { - return HEX_ZERO; + return HEX_ZERO } - let hex = ""; + let hex = '' for (let i = 0; i < 16; i++) { - hex += this.leaves[i] ? this.leaves[i].hash : HEX_ZERO; + hex += this.leaves[i] ? this.leaves[i].hash : HEX_ZERO } - const prefix = hashPrefix.INNER_NODE.toString(16); - return sha512Half(prefix + hex); + const prefix = hashPrefix.INNER_NODE.toString(16) + return sha512Half(prefix + hex) } } export class Leaf extends Node { - public tag: string; - public type: NodeType; - public data: string; + public tag: string + public type: NodeType + public data: string /** * Leaf node in a SHAMap tree. @@ -143,34 +143,34 @@ export class Leaf extends Node { * @class */ public constructor(tag: string, data: string, type: NodeType) { - super(); - this.tag = tag; - this.type = type; - this.data = data; + super() + this.tag = tag + this.type = type + this.data = data } public get hash(): string | void { switch (this.type) { case NodeType.ACCOUNT_STATE: { - const leafPrefix = hashPrefix.LEAF_NODE.toString(16); - return sha512Half(leafPrefix + this.data + this.tag); + const leafPrefix = hashPrefix.LEAF_NODE.toString(16) + return sha512Half(leafPrefix + this.data + this.tag) } case NodeType.TRANSACTION_NO_METADATA: { - const txIDPrefix = hashPrefix.TRANSACTION_ID.toString(16); - return sha512Half(txIDPrefix + this.data); + const txIDPrefix = hashPrefix.TRANSACTION_ID.toString(16) + return sha512Half(txIDPrefix + this.data) } case NodeType.TRANSACTION_METADATA: { - const txNodePrefix = hashPrefix.TRANSACTION_NODE.toString(16); - return sha512Half(txNodePrefix + this.data + this.tag); + const txNodePrefix = hashPrefix.TRANSACTION_NODE.toString(16) + return sha512Half(txNodePrefix + this.data + this.tag) } default: - throw new Error("Tried to hash a SHAMap node of unknown type."); + throw new Error('Tried to hash a SHAMap node of unknown type.') } } } export class SHAMap { - public root: InnerNode; + public root: InnerNode /** * SHAMap tree. @@ -178,14 +178,14 @@ export class SHAMap { * @class */ public constructor() { - this.root = new InnerNode(0); + this.root = new InnerNode(0) } public addItem(tag: string, data: string, type: NodeType): void { - this.root.addItem(tag, new Leaf(tag, data, type)); + this.root.addItem(tag, new Leaf(tag, data, type)) } public get hash(): string { - return this.root.hash; + return this.root.hash } } diff --git a/src/utils/index.ts b/src/utils/index.ts index 7212d9e8..43cc4db9 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,12 +1,12 @@ -import BigNumber from "bignumber.js"; -import _ from "lodash"; -import { xAddressToClassicAddress } from "ripple-address-codec"; +import BigNumber from 'bignumber.js' +import _ from 'lodash' +import { xAddressToClassicAddress } from 'ripple-address-codec' -import { ValidationError } from "../common/errors"; -import { RippledAmount } from "../common/types/objects"; +import { ValidationError } from '../common/errors' +import { RippledAmount } from '../common/types/objects' -import { deriveKeypair, deriveAddress, deriveXAddress } from "./derive"; -import { generateXAddress } from "./generateAddress"; +import { deriveKeypair, deriveAddress, deriveXAddress } from './derive' +import { generateXAddress } from './generateAddress' import { computeBinaryTransactionHash, computeTransactionHash, @@ -20,166 +20,166 @@ import { computeLedgerHash, computeEscrowHash, computePaymentChannelHash, -} from "./hashes"; -import computeLedgerHeaderHash from "./ledgerHash"; -import signPaymentChannelClaim from "./signPaymentChannelClaim"; -import verifyPaymentChannelClaim from "./verifyPaymentChannelClaim"; +} from './hashes' +import computeLedgerHeaderHash from './ledgerHash' +import signPaymentChannelClaim from './signPaymentChannelClaim' +import verifyPaymentChannelClaim from './verifyPaymentChannelClaim' function isValidSecret(secret: string): boolean { try { - deriveKeypair(secret); - return true; + deriveKeypair(secret) + return true } catch (err) { - return false; + return false } } function dropsToXrp(drops: BigNumber.Value): string { - if (typeof drops === "string") { - if (!drops.match(/^-?[0-9]*\.?[0-9]*$/)) { + if (typeof drops === 'string') { + if (!/^-?[0-9]*\.?[0-9]*$/.exec(drops)) { throw new ValidationError( `dropsToXrp: invalid value '${drops}',` + - ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).` - ); - } else if (drops === ".") { + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`, + ) + } else if (drops === '.') { throw new ValidationError( `dropsToXrp: invalid value '${drops}',` + - ` should be a BigNumber or string-encoded number.` - ); + ` should be a BigNumber or string-encoded number.`, + ) } } // Converting to BigNumber and then back to string should remove any // decimal point followed by zeros, e.g. '1.00'. // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. - drops = new BigNumber(drops).toString(10); + drops = new BigNumber(drops).toString(10) // drops are only whole units - if (drops.includes(".")) { + if (drops.includes('.')) { throw new ValidationError( - `dropsToXrp: value '${drops}' has` + ` too many decimal places.` - ); + `dropsToXrp: value '${drops}' has` + ` too many decimal places.`, + ) } // This should never happen; the value has already been // validated above. This just ensures BigNumber did not do // something unexpected. - if (!drops.match(/^-?[0-9]+$/)) { + if (!/^-?[0-9]+$/.exec(drops)) { throw new ValidationError( `dropsToXrp: failed sanity check -` + ` value '${drops}',` + - ` does not match (^-?[0-9]+$).` - ); + ` does not match (^-?[0-9]+$).`, + ) } - return new BigNumber(drops).dividedBy(1000000.0).toString(10); + return new BigNumber(drops).dividedBy(1000000.0).toString(10) } function xrpToDrops(xrp: BigNumber.Value): string { - if (typeof xrp === "string") { - if (!xrp.match(/^-?[0-9]*\.?[0-9]*$/)) { + if (typeof xrp === 'string') { + if (!/^-?[0-9]*\.?[0-9]*$/.exec(xrp)) { throw new ValidationError( `xrpToDrops: invalid value '${xrp}',` + - ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).` - ); - } else if (xrp === ".") { + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`, + ) + } else if (xrp === '.') { throw new ValidationError( `xrpToDrops: invalid value '${xrp}',` + - ` should be a BigNumber or string-encoded number.` - ); + ` should be a BigNumber or string-encoded number.`, + ) } } // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. - xrp = new BigNumber(xrp).toString(10); + xrp = new BigNumber(xrp).toString(10) // This should never happen; the value has already been // validated above. This just ensures BigNumber did not do // something unexpected. - if (!xrp.match(/^-?[0-9.]+$/)) { + if (!/^-?[0-9.]+$/.exec(xrp)) { throw new ValidationError( `xrpToDrops: failed sanity check -` + ` value '${xrp}',` + - ` does not match (^-?[0-9.]+$).` - ); + ` does not match (^-?[0-9.]+$).`, + ) } - const components = xrp.split("."); + const components = xrp.split('.') if (components.length > 2) { throw new ValidationError( `xrpToDrops: failed sanity check -` + ` value '${xrp}' has` + - ` too many decimal points.` - ); + ` too many decimal points.`, + ) } - const fraction = components[1] || "0"; + const fraction = components[1] || '0' if (fraction.length > 6) { throw new ValidationError( - `xrpToDrops: value '${xrp}' has` + ` too many decimal places.` - ); + `xrpToDrops: value '${xrp}' has` + ` too many decimal places.`, + ) } return new BigNumber(xrp) .times(1000000.0) .integerValue(BigNumber.ROUND_FLOOR) - .toString(10); + .toString(10) } function toRippledAmount(amount: RippledAmount): RippledAmount { - if (typeof amount === "string") { - return amount; + if (typeof amount === 'string') { + return amount } - if (amount.currency === "XRP") { - return xrpToDrops(amount.value); + if (amount.currency === 'XRP') { + return xrpToDrops(amount.value) } - if (amount.currency === "drops") { - return amount.value; + if (amount.currency === 'drops') { + return amount.value } - let issuer = amount.counterparty || amount.issuer; - let tag: number | false = false; + let issuer = amount.counterparty || amount.issuer + let tag: number | false = false try { if (issuer) { - ({ classicAddress: issuer, tag } = xAddressToClassicAddress(issuer)); + ;({ classicAddress: issuer, tag } = xAddressToClassicAddress(issuer)) } } catch (e) { /* not an X-address */ } if (tag !== false) { - throw new ValidationError("Issuer X-address includes a tag"); + throw new ValidationError('Issuer X-address includes a tag') } return { currency: amount.currency, issuer, value: amount.value, - }; + } } function convertKeysFromSnakeCaseToCamelCase(obj: any): any { - if (typeof obj === "object") { - const accumulator = Array.isArray(obj) ? [] : {}; - let newKey; + if (typeof obj === 'object') { + const accumulator = Array.isArray(obj) ? [] : {} + let newKey return Object.entries(obj).reduce((result, [key, value]) => { - newKey = key; + newKey = key // taking this out of function leads to error in PhantomJS - const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g; + const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g if (FINDSNAKE.test(key)) { - newKey = key.replace(FINDSNAKE, (r) => r[0] + r[2].toUpperCase()); + newKey = key.replace(FINDSNAKE, (r) => r[0] + r[2].toUpperCase()) } - result[newKey] = convertKeysFromSnakeCaseToCamelCase(value); - return result; - }, accumulator); + result[newKey] = convertKeysFromSnakeCaseToCamelCase(value) + return result + }, accumulator) } - return obj; + return obj } function removeUndefined(obj: T): T { - return _.omitBy(obj, (value) => value == null) as T; + return _.omitBy(obj, (value) => value == null) as T } /** @@ -187,7 +187,7 @@ function removeUndefined(obj: T): T { * @returns Milliseconds since unix epoch. */ function rippleToUnixTimestamp(rpepoch: number): number { - return (rpepoch + 0x386d4380) * 1000; + return (rpepoch + 0x386d4380) * 1000 } /** @@ -195,7 +195,7 @@ function rippleToUnixTimestamp(rpepoch: number): number { * @returns Seconds since Ripple Epoch (1/1/2000 GMT). */ function unixToRippleTimestamp(timestamp: number): number { - return Math.round(timestamp / 1000) - 0x386d4380; + return Math.round(timestamp / 1000) - 0x386d4380 } /** @@ -203,7 +203,7 @@ function unixToRippleTimestamp(timestamp: number): number { * @returns Iso8601 international standard date format. */ function rippleTimeToISOTime(rippleTime: number): string { - return new Date(rippleToUnixTimestamp(rippleTime)).toISOString(); + return new Date(rippleToUnixTimestamp(rippleTime)).toISOString() } /** @@ -211,7 +211,7 @@ function rippleTimeToISOTime(rippleTime: number): string { * @returns Seconds since ripple epoch (1/1/2000 GMT). */ function ISOTimeToRippleTime(iso8601: string): number { - return unixToRippleTimestamp(Date.parse(iso8601)); + return unixToRippleTimestamp(Date.parse(iso8601)) } export { @@ -242,4 +242,4 @@ export { deriveXAddress, signPaymentChannelClaim, verifyPaymentChannelClaim, -}; +} diff --git a/src/utils/ledgerHash.ts b/src/utils/ledgerHash.ts index c49fd733..d807ee00 100644 --- a/src/utils/ledgerHash.ts +++ b/src/utils/ledgerHash.ts @@ -1,14 +1,14 @@ -import _ from "lodash"; +import _ from 'lodash' -import { ValidationError } from "../common/errors"; +import { ValidationError } from '../common/errors' import { computeLedgerHash, computeTransactionTreeHash, computeStateTreeHash, -} from "./hashes"; +} from './hashes' -import { ISOTimeToRippleTime } from "."; +import { ISOTimeToRippleTime } from '.' function convertLedgerHeader(header): any { return { @@ -23,101 +23,101 @@ function convertLedgerHeader(header): any { parent_close_time: ISOTimeToRippleTime(header.parentCloseTime), total_coins: header.totalDrops, transaction_hash: header.transactionHash, - }; + } } function hashLedgerHeader(ledgerHeader) { - const header = convertLedgerHeader(ledgerHeader); - return computeLedgerHash(header); + const header = convertLedgerHeader(ledgerHeader) + return computeLedgerHash(header) } function computeTransactionHash( ledger, - options: ComputeLedgerHeaderHashOptions + options: ComputeLedgerHeaderHashOptions, ) { - let transactions: any[] = []; + let transactions: any[] = [] if (ledger.rawTransactions) { - transactions = JSON.parse(ledger.rawTransactions); + transactions = JSON.parse(ledger.rawTransactions) } else if (ledger.transactions) { try { transactions = ledger.transactions.map((tx) => - JSON.parse(tx.rawTransaction) - ); + JSON.parse(tx.rawTransaction), + ) } catch (e) { if ( e.toString() === - "SyntaxError: Unexpected" + " token u in JSON at position 0" + 'SyntaxError: Unexpected' + ' token u in JSON at position 0' ) { // one or more of the `tx.rawTransaction`s is undefined - throw new ValidationError("ledger" + " is missing raw transactions"); + throw new ValidationError('ledger' + ' is missing raw transactions') } } } else { if (options.computeTreeHashes) { throw new ValidationError( - "transactions" + " property is missing from the ledger" - ); + 'transactions' + ' property is missing from the ledger', + ) } - return ledger.transactionHash; + return ledger.transactionHash } const txs = transactions.map((tx) => { - const mergeTx = { ..._.omit(tx, "tx"), ...(tx.tx || {}) }; + const mergeTx = { ..._.omit(tx, 'tx'), ...(tx.tx || {}) } // rename `meta` back to `metaData` const renameMeta = { - ..._.omit(mergeTx, "meta"), + ..._.omit(mergeTx, 'meta'), ...(tx.meta ? { metaData: tx.meta } : {}), - }; - return renameMeta; - }); - const transactionHash = computeTransactionTreeHash(txs); + } + return renameMeta + }) + const transactionHash = computeTransactionTreeHash(txs) if ( ledger.transactionHash != null && ledger.transactionHash !== transactionHash ) { throw new ValidationError( - "transactionHash in header" + - " does not match computed hash of transactions", + 'transactionHash in header' + + ' does not match computed hash of transactions', { transactionHashInHeader: ledger.transactionHash, computedHashOfTransactions: transactionHash, - } - ); + }, + ) } - return transactionHash; + return transactionHash } function computeStateHash(ledger, options: ComputeLedgerHeaderHashOptions) { if (ledger.rawState == null) { if (options.computeTreeHashes) { throw new ValidationError( - "rawState" + " property is missing from the ledger" - ); + 'rawState' + ' property is missing from the ledger', + ) } - return ledger.stateHash; + return ledger.stateHash } - const state = JSON.parse(ledger.rawState); - const stateHash = computeStateTreeHash(state); + const state = JSON.parse(ledger.rawState) + const stateHash = computeStateTreeHash(state) if (ledger.stateHash != null && ledger.stateHash !== stateHash) { throw new ValidationError( - "stateHash in header" + " does not match computed hash of state" - ); + 'stateHash in header' + ' does not match computed hash of state', + ) } - return stateHash; + return stateHash } export interface ComputeLedgerHeaderHashOptions { - computeTreeHashes?: boolean; + computeTreeHashes?: boolean } function computeLedgerHeaderHash( ledger: any, - options: ComputeLedgerHeaderHashOptions = {} + options: ComputeLedgerHeaderHashOptions = {}, ): string { const subhashes = { transactionHash: computeTransactionHash(ledger, options), stateHash: computeStateHash(ledger, options), - }; - return hashLedgerHeader({ ...ledger, ...subhashes }); + } + return hashLedgerHeader({ ...ledger, ...subhashes }) } -export default computeLedgerHeaderHash; +export default computeLedgerHeaderHash diff --git a/src/utils/signPaymentChannelClaim.ts b/src/utils/signPaymentChannelClaim.ts index f5c46356..564c8767 100644 --- a/src/utils/signPaymentChannelClaim.ts +++ b/src/utils/signPaymentChannelClaim.ts @@ -1,18 +1,18 @@ -import binary from "ripple-binary-codec"; -import keypairs from "ripple-keypairs"; +import binary from 'ripple-binary-codec' +import keypairs from 'ripple-keypairs' -import { xrpToDrops } from "."; +import { xrpToDrops } from '.' function signPaymentChannelClaim( channel: string, amount: string, - privateKey: string + privateKey: string, ): string { const signingData = binary.encodeForSigningClaim({ channel, amount: xrpToDrops(amount), - }); - return keypairs.sign(signingData, privateKey); + }) + return keypairs.sign(signingData, privateKey) } -export default signPaymentChannelClaim; +export default signPaymentChannelClaim diff --git a/src/utils/verifyPaymentChannelClaim.ts b/src/utils/verifyPaymentChannelClaim.ts index 4a4e0b73..ba4d7d2a 100644 --- a/src/utils/verifyPaymentChannelClaim.ts +++ b/src/utils/verifyPaymentChannelClaim.ts @@ -1,19 +1,19 @@ -import binary from "ripple-binary-codec"; -import keypairs from "ripple-keypairs"; +import binary from 'ripple-binary-codec' +import keypairs from 'ripple-keypairs' -import { xrpToDrops } from "."; +import { xrpToDrops } from '.' function verifyPaymentChannelClaim( channel: string, amount: string, signature: string, - publicKey: string + publicKey: string, ): boolean { const signingData = binary.encodeForSigningClaim({ channel, amount: xrpToDrops(amount), - }); - return keypairs.verify(signingData, signature, publicKey); + }) + return keypairs.verify(signingData, signature, publicKey) } -export default verifyPaymentChannelClaim; +export default verifyPaymentChannelClaim diff --git a/src/utils/xrpConversion.ts b/src/utils/xrpConversion.ts new file mode 100644 index 00000000..f5501b7c --- /dev/null +++ b/src/utils/xrpConversion.ts @@ -0,0 +1,115 @@ +import BigNumber from 'bignumber.js' + +import { ValidationError } from '../common/errors' + +const DROPS_PER_XRP = 1000000.0 +const MAX_FRACTION_LENGTH = 6 +const BASE_TEN = 10 +const SANITY_CHECK = /^-?[0-9.]+$/u + +/** + * Convert Drops to XRP. + * + * @param dropsToConvert - Drops to convert to XRP. + * @returns Amount in XRP. + * @throws When drops amount is invalid. + */ +export function dropsToXrp(dropsToConvert: BigNumber.Value): string { + let drops = dropsToConvert + if (typeof drops === 'string') { + if (!/^-?[0-9]*\.?[0-9]*$/u.exec(drops)) { + throw new ValidationError( + `dropsToXrp: invalid value '${drops}',` + + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`, + ) + } else if (drops === '.') { + throw new ValidationError( + `dropsToXrp: invalid value '${drops}',` + + ` should be a BigNumber or string-encoded number.`, + ) + } + } + + // Converting to BigNumber and then back to string should remove any + // decimal point followed by zeros, e.g. '1.00'. + // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. + drops = new BigNumber(drops).toString(BASE_TEN) + + // drops are only whole units + if (drops.includes('.')) { + throw new ValidationError( + `dropsToXrp: value '${drops}' has too many decimal places.`, + ) + } + + // This should never happen; the value has already been + // validated above. This just ensures BigNumber did not do + // something unexpected. + if (!SANITY_CHECK.exec(drops)) { + throw new ValidationError( + `dropsToXrp: failed sanity check -` + + ` value '${drops}',` + + ` does not match (^-?[0-9]+$).`, + ) + } + + return new BigNumber(drops).dividedBy(DROPS_PER_XRP).toString(BASE_TEN) +} + +/** + * Convert an amount in XRP to an amount in drops. + * + * @param xrpToConvert - Amount in XRP. + * @returns Amount in drops. + * @throws When amount in xrp is invalid. + */ +export function xrpToDrops(xrpToConvert: BigNumber.Value): string { + let xrp = xrpToConvert + if (typeof xrp === 'string') { + if (!/^-?[0-9]*\.?[0-9]*$/u.exec(xrp)) { + throw new ValidationError( + `xrpToDrops: invalid value '${xrp}',` + + ` should be a number matching (^-?[0-9]*\\.?[0-9]*$).`, + ) + } else if (xrp === '.') { + throw new ValidationError( + `xrpToDrops: invalid value '${xrp}',` + + ` should be a BigNumber or string-encoded number.`, + ) + } + } + + // Important: specify base 10 to avoid exponential notation, e.g. '1e-7'. + xrp = new BigNumber(xrp).toString(10) + // This should never happen; the value has already been + // validated above. This just ensures BigNumber did not do + // something unexpected. + if (!SANITY_CHECK.exec(xrp)) { + throw new ValidationError( + `xrpToDrops: failed sanity check -` + + ` value '${xrp}',` + + ` does not match (^-?[0-9.]+$).`, + ) + } + + const components = xrp.split('.') + if (components.length > 2) { + throw new ValidationError( + `xrpToDrops: failed sanity check -` + + ` value '${xrp}' has` + + ` too many decimal points.`, + ) + } + + const fraction = components[1] || '0' + if (fraction.length > MAX_FRACTION_LENGTH) { + throw new ValidationError( + `xrpToDrops: value '${xrp}' has too many decimal places.`, + ) + } + + return new BigNumber(xrp) + .times(DROPS_PER_XRP) + .integerValue(BigNumber.ROUND_FLOOR) + .toString(BASE_TEN) +} diff --git a/src/wallet/generateFaucetWallet.ts b/src/wallet/generateFaucetWallet.ts index d90fda29..e0f4a0ed 100644 --- a/src/wallet/generateFaucetWallet.ts +++ b/src/wallet/generateFaucetWallet.ts @@ -1,27 +1,27 @@ -import https = require("https"); +import https = require('https') -import { isValidClassicAddress } from "ripple-address-codec"; +import { isValidClassicAddress } from 'ripple-address-codec' -import type { Client } from ".."; -import { errors } from "../common"; -import { RippledError } from "../common/errors"; -import { GeneratedAddress } from "../utils/generateAddress"; +import type { Client } from '..' +import { errors } from '../common' +import { RippledError } from '../common/errors' +import { GeneratedAddress } from '../utils/generateAddress' -import Wallet from "."; +import Wallet from '.' export interface FaucetWallet { - account: GeneratedAddress; - amount: number; - balance: number; + account: GeneratedAddress + amount: number + balance: number } export enum FaucetNetwork { - Testnet = "faucet.altnet.rippletest.net", - Devnet = "faucet.devnet.rippletest.net", + Testnet = 'faucet.altnet.rippletest.net', + Devnet = 'faucet.devnet.rippletest.net', } -const INTERVAL_SECONDS = 1; // Interval to check an account balance -const MAX_ATTEMPTS = 20; // Maximum attempts to retrieve a balance +const INTERVAL_SECONDS = 1 // Interval to check an account balance +const MAX_ATTEMPTS = 20 // Maximum attempts to retrieve a balance // // Generates a random wallet with some amount of XRP (usually 1000 XRP). @@ -33,63 +33,63 @@ const MAX_ATTEMPTS = 20; // Maximum attempts to retrieve a balance // z async function generateFaucetWallet( client: Client, - wallet?: Wallet + wallet?: Wallet, ): Promise { if (!client.isConnected()) { - throw new RippledError("Client not connected, cannot call faucet"); + throw new RippledError('Client not connected, cannot call faucet') } // Generate a new Wallet if no existing Wallet is provided or its address is invalid to fund const fundWallet = wallet && isValidClassicAddress(wallet.classicAddress) ? wallet - : Wallet.generate(); + : Wallet.generate() // Create the POST request body const body: Uint8Array | undefined = new TextEncoder().encode( JSON.stringify({ destination: fundWallet.classicAddress, - }) - ); + }), + ) // Retrieve the existing account balance const addressToFundBalance = await getAddressXrpBalance( client, - fundWallet.classicAddress - ); + fundWallet.classicAddress, + ) // Check the address balance is not undefined and is a number const startingBalance = addressToFundBalance && !isNaN(Number(addressToFundBalance)) ? Number(addressToFundBalance) - : 0; + : 0 - const faucetUrl = getFaucetUrl(client); + const faucetUrl = getFaucetUrl(client) // Options to pass to https.request const options = { hostname: faucetUrl, port: 443, - path: "/accounts", - method: "POST", + path: '/accounts', + method: 'POST', headers: { - "Content-Type": "application/json", - "Content-Length": body ? body.length : 0, + 'Content-Type': 'application/json', + 'Content-Length': body ? body.length : 0, }, - }; + } return new Promise((resolve, reject) => { const request = https.request(options, (response) => { - const chunks: any[] = []; - response.on("data", (d) => { - chunks.push(d); - }); - response.on("end", async () => { - const body = Buffer.concat(chunks).toString(); + const chunks: any[] = [] + response.on('data', (d) => { + chunks.push(d) + }) + response.on('end', async () => { + const body = Buffer.concat(chunks).toString() // "application/json; charset=utf-8" - if (response.headers["content-type"]?.startsWith("application/json")) { - const faucetWallet: FaucetWallet = JSON.parse(body); - const classicAddress = faucetWallet.account.classicAddress; + if (response.headers['content-type']?.startsWith('application/json')) { + const faucetWallet: FaucetWallet = JSON.parse(body) + const classicAddress = faucetWallet.account.classicAddress if (classicAddress) { try { @@ -97,48 +97,48 @@ async function generateFaucetWallet( const isFunded = await hasAddressBalanceIncreased( client, classicAddress, - startingBalance - ); + startingBalance, + ) if (isFunded) { - resolve(fundWallet); + resolve(fundWallet) } else { reject( new errors.XRPLFaucetError( `Unable to fund address with faucet after waiting ${ INTERVAL_SECONDS * MAX_ATTEMPTS - } seconds` - ) - ); + } seconds`, + ), + ) } } catch (err) { - reject(new errors.XRPLFaucetError(err)); + reject(new errors.XRPLFaucetError(err)) } } else { reject( new errors.XRPLFaucetError( - `The faucet account classic address is undefined` - ) - ); + `The faucet account classic address is undefined`, + ), + ) } } else { reject({ statusCode: response.statusCode, - contentType: response.headers["content-type"], + contentType: response.headers['content-type'], body, - }); + }) } - }); - }); + }) + }) // POST the body - request.write(body || ""); + request.write(body || '') - request.on("error", (error) => { - reject(error); - }); + request.on('error', (error) => { + reject(error) + }) - request.end(); - }); + request.end() + }) } /** @@ -150,19 +150,19 @@ async function generateFaucetWallet( */ async function getAddressXrpBalance( client: Client, - address: string + address: string, ): Promise { // Get all the account balances try { - const balances = await client.getBalances(address); + const balances = await client.getBalances(address) // Retrieve the XRP balance const xrpBalance = balances.filter( - (balance) => balance.currency.toUpperCase() === "XRP" - ); - return xrpBalance[0].value; + (balance) => balance.currency.toUpperCase() === 'XRP', + ) + return xrpBalance[0].value } catch (err) { - return `Unable to retrieve ${address} balance. Error: ${err}`; + return `Unable to retrieve ${address} balance. Error: ${err}` } } @@ -177,34 +177,34 @@ async function getAddressXrpBalance( async function hasAddressBalanceIncreased( client: Client, address: string, - originalBalance: number + originalBalance: number, ): Promise { return new Promise((resolve, reject) => { - let attempts = MAX_ATTEMPTS; + let attempts = MAX_ATTEMPTS const interval = setInterval(async () => { if (attempts < 0) { - clearInterval(interval); - resolve(false); + clearInterval(interval) + resolve(false) } else { - attempts--; + attempts-- } try { - const newBalance = Number(await getAddressXrpBalance(client, address)); + const newBalance = Number(await getAddressXrpBalance(client, address)) if (newBalance > originalBalance) { - clearInterval(interval); - resolve(true); + clearInterval(interval) + resolve(true) } } catch (err) { - clearInterval(interval); + clearInterval(interval) reject( new errors.XRPLFaucetError( - `Unable to check if the address ${address} balance has increased. Error: ${err}` - ) - ); + `Unable to check if the address ${address} balance has increased. Error: ${err}`, + ), + ) } - }, INTERVAL_SECONDS * 1000); - }); + }, INTERVAL_SECONDS * 1000) + }) } /** @@ -214,18 +214,18 @@ async function hasAddressBalanceIncreased( * @returns A {@link FaucetNetwork}. */ export function getFaucetUrl(client: Client) { - const connectionUrl = client.connection.getUrl(); + const connectionUrl = client.connection.getUrl() // 'altnet' for Ripple Testnet server and 'testnet' for XRPL Labs Testnet server - if (connectionUrl.includes("altnet") || connectionUrl.includes("testnet")) { - return FaucetNetwork.Testnet; + if (connectionUrl.includes('altnet') || connectionUrl.includes('testnet')) { + return FaucetNetwork.Testnet } - if (connectionUrl.includes("devnet")) { - return FaucetNetwork.Devnet; + if (connectionUrl.includes('devnet')) { + return FaucetNetwork.Devnet } - return undefined; + return undefined } -export default generateFaucetWallet; +export default generateFaucetWallet diff --git a/src/wallet/index.ts b/src/wallet/index.ts index 766c17c4..6a22d287 100644 --- a/src/wallet/index.ts +++ b/src/wallet/index.ts @@ -1,19 +1,19 @@ -import { fromSeed } from "bip32"; -import { mnemonicToSeedSync } from "bip39"; -import { classicAddressToXAddress } from "ripple-address-codec"; -import { decode, encodeForSigning } from "ripple-binary-codec"; +import { fromSeed } from 'bip32' +import { mnemonicToSeedSync } from 'bip39' +import { classicAddressToXAddress } from 'ripple-address-codec' +import { decode, encodeForSigning } from 'ripple-binary-codec' import { deriveAddress, deriveKeypair, generateSeed, verify, -} from "ripple-keypairs"; +} from 'ripple-keypairs' -import ECDSA from "../common/ecdsa"; -import { ValidationError } from "../common/errors"; -import { SignedTransaction } from "../common/types/objects"; -import { signOffline } from "../transaction/sign"; -import { SignOptions } from "../transaction/types"; +import ECDSA from '../common/ecdsa' +import { ValidationError } from '../common/errors' +import { SignedTransaction } from '../common/types/objects' +import { signOffline } from '../transaction/sign' +import { SignOptions } from '../transaction/types' /** * A utility for deriving a wallet composed of a keypair (publicKey/privateKey). @@ -21,18 +21,18 @@ import { SignOptions } from "../transaction/types"; * It provides functionality to sign/verify transactions offline. */ class Wallet { - readonly publicKey: string; - readonly privateKey: string; - readonly classicAddress: string; - readonly seed?: string; - private static readonly defaultAlgorithm: ECDSA = ECDSA.ed25519; - private static readonly defaultDerivationPath: string = "m/44'/144'/0'/0/0"; + readonly publicKey: string + readonly privateKey: string + readonly classicAddress: string + readonly seed?: string + private static readonly defaultAlgorithm: ECDSA = ECDSA.ed25519 + private static readonly defaultDerivationPath: string = "m/44'/144'/0'/0/0" constructor(publicKey: string, privateKey: string, seed?: string) { - this.publicKey = publicKey; - this.privateKey = privateKey; - this.classicAddress = deriveAddress(publicKey); - this.seed = seed; + this.publicKey = publicKey + this.privateKey = privateKey + this.classicAddress = deriveAddress(publicKey) + this.seed = seed } /** @@ -42,8 +42,8 @@ class Wallet { * @returns A new Wallet derived from a generated seed. */ static generate(algorithm: ECDSA = Wallet.defaultAlgorithm): Wallet { - const seed = generateSeed({ algorithm }); - return Wallet.fromSeed(seed); + const seed = generateSeed({ algorithm }) + return Wallet.fromSeed(seed) } /** @@ -55,9 +55,9 @@ class Wallet { */ static fromSeed( seed: string, - algorithm: ECDSA = Wallet.defaultAlgorithm + algorithm: ECDSA = Wallet.defaultAlgorithm, ): Wallet { - return Wallet.deriveWallet(seed, algorithm); + return Wallet.deriveWallet(seed, algorithm) } /** @@ -69,20 +69,20 @@ class Wallet { */ static fromMnemonic( mnemonic: string, - derivationPath: string = Wallet.defaultDerivationPath + derivationPath: string = Wallet.defaultDerivationPath, ): Wallet { - const seed = mnemonicToSeedSync(mnemonic); - const masterNode = fromSeed(seed); - const node = masterNode.derivePath(derivationPath); + const seed = mnemonicToSeedSync(mnemonic) + const masterNode = fromSeed(seed) + const node = masterNode.derivePath(derivationPath) if (node.privateKey === undefined) { throw new ValidationError( - "Unable to derive privateKey from mnemonic input" - ); + 'Unable to derive privateKey from mnemonic input', + ) } - const publicKey = Wallet.hexFromBuffer(node.publicKey); - const privateKey = Wallet.hexFromBuffer(node.privateKey); - return new Wallet(publicKey, `00${privateKey}`); + const publicKey = Wallet.hexFromBuffer(node.publicKey) + const privateKey = Wallet.hexFromBuffer(node.privateKey) + return new Wallet(publicKey, `00${privateKey}`) } /** @@ -94,26 +94,26 @@ class Wallet { */ static fromEntropy( entropy: Uint8Array | number[], - algorithm: ECDSA = Wallet.defaultAlgorithm + algorithm: ECDSA = Wallet.defaultAlgorithm, ): Wallet { const options = { entropy: Uint8Array.from(entropy), algorithm, - }; - const seed = generateSeed(options); - return Wallet.deriveWallet(seed, algorithm); + } + const seed = generateSeed(options) + return Wallet.deriveWallet(seed, algorithm) } private static hexFromBuffer(buffer: Buffer): string { - return buffer.toString("hex").toUpperCase(); + return buffer.toString('hex').toUpperCase() } private static deriveWallet( seed: string, - algorithm: ECDSA = Wallet.defaultAlgorithm + algorithm: ECDSA = Wallet.defaultAlgorithm, ): Wallet { - const { publicKey, privateKey } = deriveKeypair(seed, { algorithm }); - return new Wallet(publicKey, privateKey, seed); + const { publicKey, privateKey } = deriveKeypair(seed, { algorithm }) + return new Wallet(publicKey, privateKey, seed) } /** @@ -125,9 +125,9 @@ class Wallet { */ signTransaction( transaction: any, // TODO: transaction should be typed with Transaction type. - options: SignOptions = { signAs: "" } + options: SignOptions = { signAs: '' }, ): SignedTransaction { - return signOffline(this, JSON.stringify(transaction), options); + return signOffline(this, JSON.stringify(transaction), options) } /** @@ -137,10 +137,10 @@ class Wallet { * @returns Returns true if a signedTransaction is valid. */ verifyTransaction(signedTransaction: string): boolean { - const tx = decode(signedTransaction); - const messageHex: string = encodeForSigning(tx); - const signature = tx.TxnSignature; - return verify(messageHex, signature, this.publicKey); + const tx = decode(signedTransaction) + const messageHex: string = encodeForSigning(tx) + const signature = tx.TxnSignature + return verify(messageHex, signature, this.publicKey) } /** @@ -151,8 +151,8 @@ class Wallet { * @returns An X-address. */ getXAddress(tag: number, test = false): string { - return classicAddressToXAddress(this.classicAddress, tag, test); + return classicAddressToXAddress(this.classicAddress, tag, test) } } -export default Wallet; +export default Wallet diff --git a/test/backoff.ts b/test/backoff.ts index 9d0d03c1..0e9e855c 100644 --- a/test/backoff.ts +++ b/test/backoff.ts @@ -1,38 +1,38 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import ExponentialBackoff from "../src/client/backoff"; +import ExponentialBackoff from '../src/client/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.equal(new ExponentialBackoff().duration(), 100); - assert.equal(new ExponentialBackoff({ min: 100 }).duration(), 100); - assert.equal(new ExponentialBackoff({ min: 123 }).duration(), 123); - }); + assert.equal(new ExponentialBackoff().duration(), 100) + assert.equal(new ExponentialBackoff({ min: 100 }).duration(), 100) + assert.equal(new ExponentialBackoff({ min: 123 }).duration(), 123) + }) - 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); - assert.strictEqual(backoff.duration(), 400); - assert.strictEqual(backoff.duration(), 800); - }); + 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) + assert.strictEqual(backoff.duration(), 400) + assert.strictEqual(backoff.duration(), 800) + }) - 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); - assert.strictEqual(backoff.duration(), 1000); - assert.strictEqual(backoff.duration(), 1000); - }); + 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) + assert.strictEqual(backoff.duration(), 1000) + assert.strictEqual(backoff.duration(), 1000) + }) - 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); - assert.strictEqual(backoff.duration(), 400); - backoff.reset(); - assert.strictEqual(backoff.duration(), 100); - assert.strictEqual(backoff.duration(), 200); - }); -}); + 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) + assert.strictEqual(backoff.duration(), 400) + backoff.reset() + assert.strictEqual(backoff.duration(), 100) + assert.strictEqual(backoff.duration(), 200) + }) +}) diff --git a/test/broadcastClient.ts b/test/broadcastClient.ts index 2c3417e0..de28ccbc 100644 --- a/test/broadcastClient.ts +++ b/test/broadcastClient.ts @@ -1,52 +1,52 @@ -import { assert } from "chai"; -import _ from "lodash"; +import { assert } from 'chai' +import _ from 'lodash' -import responses from "./fixtures/responses"; -import rippled from "./fixtures/rippled"; -import setupClient from "./setupClient"; -import { ignoreWebSocketDisconnect } from "./testUtils"; +import responses from './fixtures/responses' +import rippled from './fixtures/rippled' +import setupClient from './setupClient' +import { ignoreWebSocketDisconnect } from './testUtils' -const TIMEOUT = 20000; +const TIMEOUT = 20000 function checkResult(expected, response) { if (expected.txJSON) { - assert(response.txJSON); - assert.deepEqual(JSON.parse(response.txJSON), JSON.parse(expected.txJSON)); + assert(response.txJSON) + assert.deepEqual(JSON.parse(response.txJSON), JSON.parse(expected.txJSON)) } - assert.deepEqual(_.omit(response, "txJSON"), _.omit(expected, "txJSON")); - return response; + assert.deepEqual(_.omit(response, 'txJSON'), _.omit(expected, 'txJSON')) + return response } -describe("BroadcastClient", function () { - this.timeout(TIMEOUT); - beforeEach(setupClient.setupBroadcast); - afterEach(setupClient.teardown); +describe('BroadcastClient', function () { + this.timeout(TIMEOUT) + beforeEach(setupClient.setupBroadcast) + afterEach(setupClient.teardown) - it("base", function () { + it('base', function () { this.mocks.forEach((mock) => { - mock.addResponse("server_info", rippled.server_info.normal); - }); - assert(this.client.isConnected()); - return this.client.request({ command: "server_info" }).then((response) => { - return checkResult(responses.getServerInfo, response.result.info); - }); - }); + mock.addResponse('server_info', rippled.server_info.normal) + }) + assert(this.client.isConnected()) + return this.client.request({ command: 'server_info' }).then((response) => { + return checkResult(responses.getServerInfo, response.result.info) + }) + }) - it("error propagation", function (done) { - const data = { error: "type", error_message: "info" }; + it('error propagation', function (done) { + const data = { error: 'type', error_message: 'info' } this.mocks.forEach((mock) => { - mock.addResponse("echo", data); - }); - this.client.once("error", (type, info) => { - assert.strictEqual(type, "type"); - assert.strictEqual(info, "info"); - done(); - }); + mock.addResponse('echo', data) + }) + this.client.once('error', (type, info) => { + assert.strictEqual(type, 'type') + assert.strictEqual(info, 'info') + done() + }) this.client.clients[1].connection .request({ - command: "echo", + command: 'echo', data, }) - .catch(ignoreWebSocketDisconnect); - }); -}); + .catch(ignoreWebSocketDisconnect) + }) +}) diff --git a/test/browser/browserIntegration.ts b/test/browser/browserIntegration.ts index 91dcaffe..c24aae29 100644 --- a/test/browser/browserIntegration.ts +++ b/test/browser/browserIntegration.ts @@ -1,35 +1,35 @@ -import { expect, assert } from "chai"; -import puppeteer from "puppeteer"; +import { expect, assert } from 'chai' +import puppeteer from 'puppeteer' -describe("Browser Tests", function () { - it("Integration Tests", async function () { - const browser = await puppeteer.launch({ headless: true }); +describe('Browser Tests', function () { + it('Integration Tests', async function () { + const browser = await puppeteer.launch({ headless: true }) try { - const page = await browser.newPage().catch(); - await page.goto(`file:///${__dirname}/../localIntegrationRunner.html`); + const page = await browser.newPage().catch() + await page.goto(`file:///${__dirname}/../localIntegrationRunner.html`) await page.waitForFunction( - 'document.querySelector("body").innerText.includes("submit multisigned transaction")' - ); + 'document.querySelector("body").innerText.includes("submit multisigned transaction")', + ) const fails = await page.evaluate(() => { - const element = document.querySelector(".failures"); + const element = document.querySelector('.failures') - return element == null ? null : element.textContent; - }); + return element == null ? null : element.textContent + }) const passes = await page.evaluate(() => { - const element = document.querySelector(".passes"); + const element = document.querySelector('.passes') - return element == null ? null : element.textContent; - }); + return element == null ? null : element.textContent + }) - expect(fails).to.equal("failures: 0"); - expect(passes).to.not.equal("passes: 0"); + expect(fails).to.equal('failures: 0') + expect(passes).to.not.equal('passes: 0') } catch (err) { - console.log(err); - assert(false); + console.log(err) + assert(false) } finally { - await browser.close(); + await browser.close() } - }).timeout(40000); -}); + }).timeout(40000) +}) diff --git a/test/client.ts b/test/client.ts index 13a00d72..620f71ed 100644 --- a/test/client.ts +++ b/test/client.ts @@ -1,98 +1,98 @@ -import { assert } from "chai"; -import _ from "lodash"; +import { assert } from 'chai' +import _ from 'lodash' -import { Client } from "xrpl-local"; +import { Client } from 'xrpl-local' import { RecursiveData, renameCounterpartyToIssuerInOrder, compareTransactions, getRecursive, -} from "xrpl-local/ledger/utils"; +} from 'xrpl-local/ledger/utils' -import { toRippledAmount } from "../src"; +import { toRippledAmount } from '../src' -import setupClient from "./setupClient"; -import { assertRejects } from "./testUtils"; +import setupClient from './setupClient' +import { assertRejects } from './testUtils' // how long before each test case times out -const TIMEOUT = 20000; +const TIMEOUT = 20000 -describe("Client", function () { - this.timeout(TIMEOUT); - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('Client', function () { + this.timeout(TIMEOUT) + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("Client - implicit server port", function () { - new Client("wss://s1.ripple.com"); - }); + it('Client - implicit server port', function () { + new Client('wss://s1.ripple.com') + }) - it("Client invalid options", function () { + it('Client invalid options', function () { // @ts-expect-error - This is intentionally invalid - assert.throws(() => new Client({ invalid: true })); - }); + assert.throws(() => new Client({ invalid: true })) + }) - it("Client valid options", function () { - const client = new Client("wss://s:1"); - const privateConnectionUrl = (client.connection as any).url; - assert.deepEqual(privateConnectionUrl, "wss://s:1"); - }); + it('Client valid options', function () { + const client = new Client('wss://s:1') + const privateConnectionUrl = (client.connection as any).url + assert.deepEqual(privateConnectionUrl, 'wss://s:1') + }) - it("Client invalid server uri", function () { - assert.throws(() => new Client("wss//s:1")); - }); + it('Client invalid server uri', function () { + assert.throws(() => new Client('wss//s:1')) + }) - it("Client connect() times out after 2 seconds", function () { + it('Client 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. - }); + }) - describe("[private] validator", function () { - it("common utils - toRippledAmount", async function () { - const amount = { issuer: "is", currency: "c", value: "v" }; + describe('[private] validator', function () { + it('common utils - toRippledAmount', async function () { + const amount = { issuer: 'is', currency: 'c', value: 'v' } assert.deepEqual(toRippledAmount(amount), { - issuer: "is", - currency: "c", - value: "v", - }); - }); + issuer: 'is', + currency: 'c', + value: 'v', + }) + }) - it("ledger utils - renameCounterpartyToIssuerInOrder", async function () { + it('ledger utils - renameCounterpartyToIssuerInOrder', async function () { const order = { - taker_gets: { counterparty: "1", currency: "XRP" }, - taker_pays: { counterparty: "1", currency: "XRP" }, - }; + taker_gets: { counterparty: '1', currency: 'XRP' }, + taker_pays: { counterparty: '1', currency: 'XRP' }, + } const expected = { - taker_gets: { issuer: "1", currency: "XRP" }, - taker_pays: { issuer: "1", currency: "XRP" }, - }; - assert.deepEqual(renameCounterpartyToIssuerInOrder(order), expected); - }); + taker_gets: { issuer: '1', currency: 'XRP' }, + taker_pays: { issuer: '1', currency: 'XRP' }, + } + assert.deepEqual(renameCounterpartyToIssuerInOrder(order), expected) + }) - it("ledger utils - compareTransactions", async function () { + it('ledger utils - compareTransactions', async function () { // @ts-expect-error - assert.strictEqual(compareTransactions({}, {}), 0); - let first: any = { outcome: { ledgerVersion: 1, indexInLedger: 100 } }; - let second: any = { outcome: { ledgerVersion: 1, indexInLedger: 200 } }; - assert.strictEqual(compareTransactions(first, second), -1); - first = { outcome: { ledgerVersion: 1, indexInLedger: 100 } }; - second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } }; - assert.strictEqual(compareTransactions(first, second), 0); - first = { outcome: { ledgerVersion: 1, indexInLedger: 200 } }; - second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } }; - assert.strictEqual(compareTransactions(first, second), 1); - }); + assert.strictEqual(compareTransactions({}, {}), 0) + let first: any = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + let second: any = { outcome: { ledgerVersion: 1, indexInLedger: 200 } } + assert.strictEqual(compareTransactions(first, second), -1) + first = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + assert.strictEqual(compareTransactions(first, second), 0) + first = { outcome: { ledgerVersion: 1, indexInLedger: 200 } } + second = { outcome: { ledgerVersion: 1, indexInLedger: 100 } } + assert.strictEqual(compareTransactions(first, second), 1) + }) - it("ledger utils - getRecursive", async function () { + it('ledger utils - getRecursive', async function () { async function getter(marker) { return new Promise((resolve, reject) => { if (marker != null) { - reject(new Error()); - return; + reject(new Error()) + return } - resolve({ marker: "A", results: [1] }); - }); + resolve({ marker: 'A', results: [1] }) + }) } - await assertRejects(getRecursive(getter, 10), Error); - }); - }); -}); + await assertRejects(getRecursive(getter, 10), Error) + }) + }) +}) diff --git a/test/client/combine.ts b/test/client/combine.ts index 0ba3bcb1..ea18acec 100644 --- a/test/client/combine.ts +++ b/test/client/combine.ts @@ -1,30 +1,30 @@ -import { assert } from "chai"; -import binary from "ripple-binary-codec"; +import { assert } from 'chai' +import binary from 'ripple-binary-codec' -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import setupClient from "../setupClient"; -import { assertResultMatch } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import setupClient from '../setupClient' +import { assertResultMatch } from '../testUtils' -const { combine: REQUEST_FIXTURES } = requests; -const { combine: RESPONSE_FIXTURES } = responses; +const { combine: REQUEST_FIXTURES } = requests +const { combine: RESPONSE_FIXTURES } = responses -describe("client.combine", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.combine', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("combine", async function () { - const combined = this.client.combine(REQUEST_FIXTURES.setDomain); - assertResultMatch(combined, RESPONSE_FIXTURES.single, "sign"); - }); + it('combine', async function () { + const combined = this.client.combine(REQUEST_FIXTURES.setDomain) + assertResultMatch(combined, RESPONSE_FIXTURES.single, 'sign') + }) - it("combine - different transactions", async function () { - const request = [REQUEST_FIXTURES.setDomain[0]]; - const tx = binary.decode(REQUEST_FIXTURES.setDomain[0]); - tx.Flags = 0; - request.push(binary.encode(tx)); + it('combine - different transactions', async function () { + const request = [REQUEST_FIXTURES.setDomain[0]] + const tx = binary.decode(REQUEST_FIXTURES.setDomain[0]) + tx.Flags = 0 + request.push(binary.encode(tx)) assert.throws(() => { - this.client.combine(request); - }, /txJSON is not the same for all signedTransactions/); - }); -}); + this.client.combine(request) + }, /txJSON is not the same for all signedTransactions/) + }) +}) diff --git a/test/client/constructor.ts b/test/client/constructor.ts index 6ccf1af0..1fa7e30a 100644 --- a/test/client/constructor.ts +++ b/test/client/constructor.ts @@ -1,24 +1,24 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { Client } from "xrpl-local"; +import { Client } from 'xrpl-local' -describe("client constructor", function () { - it("Client - implicit server port", function () { - new Client("wss://s1.ripple.com"); - }); +describe('client constructor', function () { + it('Client - implicit server port', function () { + new Client('wss://s1.ripple.com') + }) - it("Client invalid options", function () { + it('Client invalid options', function () { // @ts-expect-error - This is intentionally invalid - assert.throws(() => new Client({ invalid: true })); - }); + assert.throws(() => new Client({ invalid: true })) + }) - it("Client valid options", function () { - const client = new Client("wss://s:1"); - const privateConnectionUrl = (client.connection as any).url; - assert.deepEqual(privateConnectionUrl, "wss://s:1"); - }); + it('Client valid options', function () { + const client = new Client('wss://s:1') + const privateConnectionUrl = (client.connection as any).url + assert.deepEqual(privateConnectionUrl, 'wss://s:1') + }) - it("Client invalid server uri", function () { - assert.throws(() => new Client("wss//s:1")); - }); -}); + it('Client invalid server uri', function () { + assert.throws(() => new Client('wss//s:1')) + }) +}) diff --git a/test/client/deriveXAddress.ts b/test/client/deriveXAddress.ts index e361930b..b04fc19c 100644 --- a/test/client/deriveXAddress.ts +++ b/test/client/deriveXAddress.ts @@ -1,26 +1,26 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { Client } from "../../src"; +import { Client } from '../../src' -describe("client.deriveXAddress", function () { - it("returns address for public key", function () { +describe('client.deriveXAddress', function () { + it('returns address for public key', function () { assert.equal( Client.deriveXAddress({ publicKey: - "035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06", + '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06', tag: false, test: false, }), - "XVZVpQj8YSVpNyiwXYSqvQoQqgBttTxAZwMcuJd4xteQHyt" - ); + 'XVZVpQj8YSVpNyiwXYSqvQoQqgBttTxAZwMcuJd4xteQHyt', + ) assert.equal( Client.deriveXAddress({ publicKey: - "035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06", + '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06', tag: false, test: true, }), - "TVVrSWtmQQssgVcmoMBcFQZKKf56QscyWLKnUyiuZW8ALU4" - ); - }); -}); + 'TVVrSWtmQQssgVcmoMBcFQZKKf56QscyWLKnUyiuZW8ALU4', + ) + }) +}) diff --git a/test/client/errors.ts b/test/client/errors.ts index f928f94e..889114b4 100644 --- a/test/client/errors.ts +++ b/test/client/errors.ts @@ -1,18 +1,18 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import setupClient from "../setupClient"; +import setupClient from '../setupClient' -describe("client errors", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client errors', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("RippleError with data", async function () { - const error = new this.client.errors.RippleError("_message_", "_data_"); - assert.strictEqual(error.toString(), "[RippleError(_message_, '_data_')]"); - }); + it('RippleError with data', async function () { + const error = new this.client.errors.RippleError('_message_', '_data_') + assert.strictEqual(error.toString(), "[RippleError(_message_, '_data_')]") + }) - it("NotFoundError default message", async function () { - const error = new this.client.errors.NotFoundError(); - assert.strictEqual(error.toString(), "[NotFoundError(Not found)]"); - }); -}); + it('NotFoundError default message', async function () { + const error = new this.client.errors.NotFoundError() + assert.strictEqual(error.toString(), '[NotFoundError(Not found)]') + }) +}) diff --git a/test/client/formatBidsAndAsks.ts b/test/client/formatBidsAndAsks.ts index 20da7e69..7fd791b1 100644 --- a/test/client/formatBidsAndAsks.ts +++ b/test/client/formatBidsAndAsks.ts @@ -38,7 +38,7 @@ // return true // } -describe("client.formatBidsAndAsks", function () { +describe('client.formatBidsAndAsks', function () { // 'normal': async (client, address) => { // const orderbookInfo = { // base: { @@ -359,4 +359,4 @@ describe("client.formatBidsAndAsks", function () { // ) // }) // } -}); +}) diff --git a/test/client/getBalances.ts b/test/client/getBalances.ts index 7909e330..2890619a 100644 --- a/test/client/getBalances.ts +++ b/test/client/getBalances.ts @@ -1,94 +1,94 @@ -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import rippledAccountLines from "../fixtures/rippled/accountLines"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import rippledAccountLines from '../fixtures/rippled/accountLines' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. * - Check out "test/client/index.ts" for more information about the test runner. */ -describe("getBalances", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('getBalances', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("getBalances", async function () { + it('getBalances', async function () { this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) this.mockRippled.addResponse( - "account_lines", - rippledAccountLines.normal - ); - this.mockRippled.addResponse("ledger", rippled.ledger.normal); - const result = await this.client.getBalances(test.address); - assertResultMatch(result, responses.getBalances, "getBalances"); - }); + 'account_lines', + rippledAccountLines.normal, + ) + this.mockRippled.addResponse('ledger', rippled.ledger.normal) + const result = await this.client.getBalances(test.address) + assertResultMatch(result, responses.getBalances, 'getBalances') + }) - it("getBalances - limit", async function () { - const options = { limit: 3, ledgerVersion: 123456 }; + it('getBalances - limit', async function () { + const options = { limit: 3, ledgerVersion: 123456 } this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) this.mockRippled.addResponse( - "account_lines", - rippledAccountLines.normal - ); - this.mockRippled.addResponse("ledger", rippled.ledger.normal); - const expectedResponse = responses.getBalances.slice(0, 3); - const result = await this.client.getBalances(test.address, options); - assertResultMatch(result, expectedResponse, "getBalances"); - }); + 'account_lines', + rippledAccountLines.normal, + ) + this.mockRippled.addResponse('ledger', rippled.ledger.normal) + const expectedResponse = responses.getBalances.slice(0, 3) + const result = await this.client.getBalances(test.address, options) + assertResultMatch(result, expectedResponse, 'getBalances') + }) - it("getBalances - limit & currency", async function () { - const options = { currency: "USD", limit: 3 }; + it('getBalances - limit & currency', async function () { + const options = { currency: 'USD', limit: 3 } this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) this.mockRippled.addResponse( - "account_lines", - rippledAccountLines.normal - ); - this.mockRippled.addResponse("ledger", rippled.ledger.normal); + 'account_lines', + rippledAccountLines.normal, + ) + this.mockRippled.addResponse('ledger', rippled.ledger.normal) const expectedResponse = responses.getBalances - .filter((item) => item.currency === "USD") - .slice(0, 3); - const result = await this.client.getBalances(test.address, options); - assertResultMatch(result, expectedResponse, "getBalances"); - }); + .filter((item) => item.currency === 'USD') + .slice(0, 3) + const result = await this.client.getBalances(test.address, options) + assertResultMatch(result, expectedResponse, 'getBalances') + }) - it("getBalances - limit & currency & issuer", async function () { + it('getBalances - limit & currency & issuer', async function () { const options = { - currency: "USD", - counterparty: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B", + currency: 'USD', + counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', limit: 3, - }; + } this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) this.mockRippled.addResponse( - "account_lines", - rippledAccountLines.normal - ); - this.mockRippled.addResponse("ledger", rippled.ledger.normal); + 'account_lines', + rippledAccountLines.normal, + ) + this.mockRippled.addResponse('ledger', rippled.ledger.normal) const expectedResponse = responses.getBalances .filter( (item) => - item.currency === "USD" && - item.counterparty === "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B" + item.currency === 'USD' && + item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', ) - .slice(0, 3); - const result = await this.client.getBalances(test.address, options); - assertResultMatch(result, expectedResponse, "getBalances"); - }); - }); - }); -}); + .slice(0, 3) + const result = await this.client.getBalances(test.address, options) + assertResultMatch(result, expectedResponse, 'getBalances') + }) + }) + }) +}) diff --git a/test/client/getFee.ts b/test/client/getFee.ts index 11f009de..836cc7f2 100644 --- a/test/client/getFee.ts +++ b/test/client/getFee.ts @@ -1,70 +1,70 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { addressTests } from "../testUtils"; +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { addressTests } from '../testUtils' -describe("client.getFee", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.getFee', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("getFee", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - const fee = await this.client.getFee(); - assert.strictEqual(fee, "0.000012"); - }); + it('getFee', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + const fee = await this.client.getFee() + assert.strictEqual(fee, '0.000012') + }) - it("getFee default", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.client.feeCushion = undefined as unknown as number; - const fee = await this.client.getFee(); - assert.strictEqual(fee, "0.000012"); - }); + it('getFee default', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.client.feeCushion = undefined as unknown as number + const fee = await this.client.getFee() + assert.strictEqual(fee, '0.000012') + }) - it("getFee - high load_factor", async function () { + it('getFee - high load_factor', async function () { this.mockRippled.addResponse( - "server_info", - rippled.server_info.highLoadFactor - ); - const fee = await this.client.getFee(); - assert.strictEqual(fee, "2"); - }); + 'server_info', + rippled.server_info.highLoadFactor, + ) + const fee = await this.client.getFee() + assert.strictEqual(fee, '2') + }) - it("getFee - high load_factor with custom maxFeeXRP", async function () { + it('getFee - high load_factor with custom maxFeeXRP', async function () { this.mockRippled.addResponse( - "server_info", - rippled.server_info.highLoadFactor - ); + 'server_info', + rippled.server_info.highLoadFactor, + ) // Ensure that overriding with high maxFeeXRP of '51540' causes no errors. // (fee will actually be 51539.607552) - this.client.maxFeeXRP = "51540"; - const fee = await this.client.getFee(); - assert.strictEqual(fee, "51539.607552"); - }); + this.client.maxFeeXRP = '51540' + const fee = await this.client.getFee() + assert.strictEqual(fee, '51539.607552') + }) - it("getFee custom cushion", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.client.feeCushion = 1.4; - const fee = await this.client.getFee(); - assert.strictEqual(fee, "0.000014"); - }); + it('getFee custom cushion', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.client.feeCushion = 1.4 + const fee = await this.client.getFee() + assert.strictEqual(fee, '0.000014') + }) // This is not recommended since it may result in attempting to pay // less than the base fee. However, this test verifies the existing behavior. - it("getFee cushion less than 1.0", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.client.feeCushion = 0.9; - const fee = await this.client.getFee(); - assert.strictEqual(fee, "0.000009"); - }); + it('getFee cushion less than 1.0', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.client.feeCushion = 0.9 + const fee = await this.client.getFee() + assert.strictEqual(fee, '0.000009') + }) - it("getFee reporting", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - const fee = await this.client.getFee(); - assert.strictEqual(fee, "0.000012"); - }); - }); - }); -}); + it('getFee reporting', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + const fee = await this.client.getFee() + assert.strictEqual(fee, '0.000012') + }) + }) + }) +}) diff --git a/test/client/getOrderbook.ts b/test/client/getOrderbook.ts index cda1bc49..3b68e42f 100644 --- a/test/client/getOrderbook.ts +++ b/test/client/getOrderbook.ts @@ -1,11 +1,11 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { BookOffersRequest } from "../../src"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { addressTests, assertResultMatch, assertRejects } from "../testUtils"; +import { BookOffersRequest } from '../../src' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { addressTests, assertResultMatch, assertRejects } from '../testUtils' // import BigNumber from 'bignumber.js' // function checkSortingOfOrders(orders) { @@ -44,16 +44,16 @@ import { addressTests, assertResultMatch, assertRejects } from "../testUtils"; function isUSD(currency: string) { return ( - currency === "USD" || - currency === "0000000000000000000000005553440000000000" - ); + currency === 'USD' || + currency === '0000000000000000000000005553440000000000' + ) } function isBTC(currency: string) { return ( - currency === "BTC" || - currency === "0000000000000000000000004254430000000000" - ); + currency === 'BTC' || + currency === '0000000000000000000000004254430000000000' + ) } function normalRippledResponse(request: BookOffersRequest): object { @@ -61,69 +61,69 @@ function normalRippledResponse(request: BookOffersRequest): object { isBTC(request.taker_gets.currency) && isUSD(request.taker_pays.currency) ) { - return rippled.book_offers.fabric.requestBookOffersBidsResponse(request); + return rippled.book_offers.fabric.requestBookOffersBidsResponse(request) } if ( isUSD(request.taker_gets.currency) && isBTC(request.taker_pays.currency) ) { - return rippled.book_offers.fabric.requestBookOffersAsksResponse(request); + return rippled.book_offers.fabric.requestBookOffersAsksResponse(request) } - throw new Error("unexpected end"); + throw new Error('unexpected end') } function xrpRippledResponse(request: BookOffersRequest): object { - if (request.taker_pays.issuer === "rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw") { - return rippled.book_offers.xrp_usd; + if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') { + return rippled.book_offers.xrp_usd } - if (request.taker_gets.issuer === "rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw") { - return rippled.book_offers.usd_xrp; + if (request.taker_gets.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') { + return rippled.book_offers.usd_xrp } - throw new Error("unexpected end"); + throw new Error('unexpected end') } -describe("client.getOrderbook", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.getOrderbook', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("normal", async function () { - this.mockRippled.addResponse("book_offers", normalRippledResponse); + it('normal', async function () { + this.mockRippled.addResponse('book_offers', normalRippledResponse) const response = await this.client.getOrderbook( test.address, requests.getOrderbook.normal, - { limit: 20 } - ); + { limit: 20 }, + ) assertResultMatch( response, responses.getOrderbook.normal, - "getOrderbook" - ); - }); + 'getOrderbook', + ) + }) - it("invalid options", async function () { - this.mockRippled.addResponse("book_offers", normalRippledResponse); + it('invalid options', async function () { + this.mockRippled.addResponse('book_offers', normalRippledResponse) assertRejects( this.client.getOrderbook(test.address, requests.getOrderbook.normal, { - invalid: "options", + invalid: 'options', }), - this.client.errors.ValidationError - ); - }); + this.client.errors.ValidationError, + ) + }) - it("with XRP", async function () { - this.mockRippled.addResponse("book_offers", xrpRippledResponse); + it('with XRP', async function () { + this.mockRippled.addResponse('book_offers', xrpRippledResponse) const response = await this.client.getOrderbook( test.address, - requests.getOrderbook.withXRP - ); + requests.getOrderbook.withXRP, + ) assertResultMatch( response, responses.getOrderbook.withXRP, - "getOrderbook" - ); - }); + 'getOrderbook', + ) + }) // 'sample XRP/JPY book has orders sorted correctly', async function () { // const orderbookInfo = { @@ -157,61 +157,61 @@ describe("client.getOrderbook", function () { // }, // WARNING: This test fails to catch the sorting bug, issue #766 - it("sorted so that best deals come first [bad test]", async function () { - this.mockRippled.addResponse("book_offers", normalRippledResponse); + it('sorted so that best deals come first [bad test]', async function () { + this.mockRippled.addResponse('book_offers', normalRippledResponse) const response = await this.client.getOrderbook( test.address, - requests.getOrderbook.normal - ); + requests.getOrderbook.normal, + ) const bidRates = response.bids.map( - (bid) => bid.properties.makerExchangeRate - ); + (bid) => bid.properties.makerExchangeRate, + ) const askRates = response.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.sort((x) => Number(x)), - bidRates - ); + bidRates, + ) assert.deepEqual( askRates.sort((x) => Number(x)), - askRates - ); - }); + askRates, + ) + }) - it("currency & counterparty are correct", async function () { - this.mockRippled.addResponse("book_offers", normalRippledResponse); + it('currency & counterparty are correct', async function () { + this.mockRippled.addResponse('book_offers', normalRippledResponse) const response = await this.client.getOrderbook( test.address, - requests.getOrderbook.normal - ); - [...response.bids, ...response.asks].forEach((order) => { - const quantity = order.specification.quantity; - const totalPrice = order.specification.totalPrice; - const { base, counter } = requests.getOrderbook.normal; - assert.strictEqual(quantity.currency, base.currency); - assert.strictEqual(quantity.counterparty, base.counterparty); - assert.strictEqual(totalPrice.currency, counter.currency); - assert.strictEqual(totalPrice.counterparty, counter.counterparty); - }); - }); + requests.getOrderbook.normal, + ) + ;[...response.bids, ...response.asks].forEach((order) => { + const quantity = order.specification.quantity + const totalPrice = order.specification.totalPrice + const { base, counter } = requests.getOrderbook.normal + assert.strictEqual(quantity.currency, base.currency) + assert.strictEqual(quantity.counterparty, base.counterparty) + assert.strictEqual(totalPrice.currency, counter.currency) + assert.strictEqual(totalPrice.counterparty, counter.counterparty) + }) + }) - it("direction is correct for bids and asks", async function () { - this.mockRippled.addResponse("book_offers", normalRippledResponse); + it('direction is correct for bids and asks', async function () { + this.mockRippled.addResponse('book_offers', normalRippledResponse) const response = await this.client.getOrderbook( test.address, - requests.getOrderbook.normal - ); + requests.getOrderbook.normal, + ) assert( - response.bids.every((bid) => bid.specification.direction === "buy") - ); + response.bids.every((bid) => bid.specification.direction === 'buy'), + ) assert( - response.asks.every((ask) => ask.specification.direction === "sell") - ); - }); - }); - }); -}); + response.asks.every((ask) => ask.specification.direction === 'sell'), + ) + }) + }) + }) +}) diff --git a/test/client/getPaths.ts b/test/client/getPaths.ts index 73c6f3af..17d5899a 100644 --- a/test/client/getPaths.ts +++ b/test/client/getPaths.ts @@ -1,22 +1,22 @@ -import addresses from "../fixtures/addresses.json"; -import requests from "../fixtures/requests"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertRejects } from "../testUtils"; +import addresses from '../fixtures/addresses.json' +import requests from '../fixtures/requests' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertRejects } from '../testUtils' // import responses from '../fixtures/responses' -const { getPaths: REQUEST_FIXTURES } = requests; +const { getPaths: REQUEST_FIXTURES } = requests // const {getPaths: RESPONSE_FIXTURES} = responses const rippledResponse = rippled.path_find.generate.generateIOUPaymentPaths( 0, REQUEST_FIXTURES.normal.source.address, REQUEST_FIXTURES.normal.destination.address, - REQUEST_FIXTURES.normal.destination.amount -); + REQUEST_FIXTURES.normal.destination.amount, +) -describe("client.getPaths", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.getPaths', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) // 'simple test', function () { // const response = await this.client.getPaths(REQUEST_FIXTURES.normal) // assertResultMatch(response, RESPONSE_FIXTURES.XrpToUsd, 'getPaths') @@ -43,13 +43,13 @@ describe("client.getPaths", function () { // const response = await this.client.getPaths(REQUEST_FIXTURES.XrpToXrp) // assertResultMatch(response, RESPONSE_FIXTURES.XrpToXrp, 'getPaths') // }) - it("source with issuer", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + it('source with issuer', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths(REQUEST_FIXTURES.issuer), - this.client.errors.NotFoundError - ); - }); + this.client.errors.NotFoundError, + ) + }) // 'XRP 2 XRP - not enough', function () { // return assertRejects( // this.client.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough), @@ -62,46 +62,46 @@ describe("client.getPaths", function () { // this.client.getPaths(REQUEST_FIXTURES.invalid); // }, /Cannot specify both source.amount/); // }); - it("does not accept currency", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + it('does not accept currency', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths(REQUEST_FIXTURES.NotAcceptCurrency), - this.client.errors.NotFoundError - ); - }); - it("no paths", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + this.client.errors.NotFoundError, + ) + }) + it('no paths', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths(REQUEST_FIXTURES.NoPaths), - this.client.errors.NotFoundError - ); - }); - it("no paths source amount", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + this.client.errors.NotFoundError, + ) + }) + it('no paths source amount', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths(REQUEST_FIXTURES.NoPathsSource), - this.client.errors.NotFoundError - ); - }); - it("no paths with source currencies", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + this.client.errors.NotFoundError, + ) + }) + it('no paths with source currencies', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies), - this.client.errors.NotFoundError - ); - }); - it("error: srcActNotFound", async function () { - this.mockRippled.addResponse("ripple_path_find", rippledResponse); + this.client.errors.NotFoundError, + ) + }) + it('error: srcActNotFound', async function () { + this.mockRippled.addResponse('ripple_path_find', rippledResponse) return assertRejects( this.client.getPaths({ ...REQUEST_FIXTURES.normal, source: { address: addresses.NOTFOUND }, }), - this.client.errors.RippleError - ); - }); + this.client.errors.RippleError, + ) + }) // 'send all', function () { // const response = await this.client.getPaths(REQUEST_FIXTURES.sendAll) // assertResultMatch(response, RESPONSE_FIXTURES.sendAll, 'getPaths') // }) -}); +}) diff --git a/test/client/getTrustlines.ts b/test/client/getTrustlines.ts index 5dccc69f..c3e87524 100644 --- a/test/client/getTrustlines.ts +++ b/test/client/getTrustlines.ts @@ -1,60 +1,60 @@ -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled/accountLines"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled/accountLines' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const { getTrustlines: RESPONSE_FIXTURES } = responses; +const { getTrustlines: RESPONSE_FIXTURES } = responses -describe("client.getTrustlines", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.getTrustlines', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("getTrustlines - filtered", async function () { - this.mockRippled.addResponse("account_lines", rippled.normal); - const options = { currency: "USD" }; - const result = await this.client.getTrustlines(test.address, options); - assertResultMatch(result, RESPONSE_FIXTURES.filtered, "getTrustlines"); - }); + it('getTrustlines - filtered', async function () { + this.mockRippled.addResponse('account_lines', rippled.normal) + const options = { currency: 'USD' } + const result = await this.client.getTrustlines(test.address, options) + assertResultMatch(result, RESPONSE_FIXTURES.filtered, 'getTrustlines') + }) - it("getTrustlines - more than 400 items", async function () { - this.mockRippled.addResponse("account_lines", rippled.manyItems); - const options = { limit: 401 }; - const result = await this.client.getTrustlines(test.address, options); + it('getTrustlines - more than 400 items', async function () { + this.mockRippled.addResponse('account_lines', rippled.manyItems) + const options = { limit: 401 } + const result = await this.client.getTrustlines(test.address, options) assertResultMatch( result, RESPONSE_FIXTURES.moreThan400Items, - "getTrustlines" - ); - }); + 'getTrustlines', + ) + }) - it("getTrustlines - no options", async function () { - this.mockRippled.addResponse("account_lines", rippled.normal); - await this.client.getTrustlines(test.address); - }); + it('getTrustlines - no options', async function () { + this.mockRippled.addResponse('account_lines', rippled.normal) + await this.client.getTrustlines(test.address) + }) - it("getTrustlines - ripplingDisabled works properly", async function () { - this.mockRippled.addResponse("account_lines", rippled.ripplingDisabled); - const result = await this.client.getTrustlines(test.address); + it('getTrustlines - ripplingDisabled works properly', async function () { + this.mockRippled.addResponse('account_lines', rippled.ripplingDisabled) + const result = await this.client.getTrustlines(test.address) assertResultMatch( result, RESPONSE_FIXTURES.ripplingDisabled, - "getTrustlines" - ); - }); + 'getTrustlines', + ) + }) - it("getTrustlines - ledger version option", async function () { - this.mockRippled.addResponse("account_lines", rippled.manyItems); + it('getTrustlines - ledger version option', async function () { + this.mockRippled.addResponse('account_lines', rippled.manyItems) const result = await this.client.getTrustlines(test.address, { ledgerVersion: 5, - }); + }) assertResultMatch( result, RESPONSE_FIXTURES.moreThan400Items, - "getTrustlines" - ); - }); - }); - }); -}); + 'getTrustlines', + ) + }) + }) + }) +}) diff --git a/test/client/hasNextPage.ts b/test/client/hasNextPage.ts index 1eda18a0..7b1b61fb 100644 --- a/test/client/hasNextPage.ts +++ b/test/client/hasNextPage.ts @@ -1,32 +1,32 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { Client } from "../../src"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; +import { Client } from '../../src' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' -describe("client.hasNextPage", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.hasNextPage', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("returns true when there is another page", async function () { - this.mockRippled.addResponse("ledger_data", rippled.ledger_data.first_page); - const response = await this.client.request({ command: "ledger_data" }); - assert(Client.hasNextPage(response)); - }); + it('returns true when there is another page', async function () { + this.mockRippled.addResponse('ledger_data', rippled.ledger_data.first_page) + const response = await this.client.request({ command: 'ledger_data' }) + assert(Client.hasNextPage(response)) + }) - it("returns false when there are no more pages", async function () { + it('returns false when there are no more pages', async function () { const rippledResponse = function (request: Request): object { - if ("marker" in request) { - return rippled.ledger_data.last_page; + if ('marker' in request) { + return rippled.ledger_data.last_page } - return rippled.ledger_data.first_page; - }; - this.mockRippled.addResponse("ledger_data", rippledResponse); - const response = await this.client.request({ command: "ledger_data" }); + return rippled.ledger_data.first_page + } + this.mockRippled.addResponse('ledger_data', rippledResponse) + const response = await this.client.request({ command: 'ledger_data' }) const responseNextPage = await this.client.requestNextPage( - { command: "ledger_data" }, - response - ); - assert(!Client.hasNextPage(responseNextPage)); - }); -}); + { command: 'ledger_data' }, + response, + ) + assert(!Client.hasNextPage(responseNextPage)) + }) +}) diff --git a/test/client/isConnected.ts b/test/client/isConnected.ts index e9925e33..04166e67 100644 --- a/test/client/isConnected.ts +++ b/test/client/isConnected.ts @@ -1,14 +1,14 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import setupClient from "../setupClient"; +import setupClient from '../setupClient' -describe("client.isConnected", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.isConnected', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("disconnect & isConnected", async function () { - assert.strictEqual(this.client.isConnected(), true); - await this.client.disconnect(); - assert.strictEqual(this.client.isConnected(), false); - }); -}); + it('disconnect & isConnected', async function () { + assert.strictEqual(this.client.isConnected(), true) + await this.client.disconnect() + assert.strictEqual(this.client.isConnected(), false) + }) +}) diff --git a/test/client/prepareCheckCancel.ts b/test/client/prepareCheckCancel.ts index b55e674c..80dd4eff 100644 --- a/test/client/prepareCheckCancel.ts +++ b/test/client/prepareCheckCancel.ts @@ -1,60 +1,60 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareCheckCancel", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareCheckCancel', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareCheckCancel", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareCheckCancel', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const result = await this.client.prepareCheckCancel( - test.address, - requests.prepareCheckCancel.normal - ); - assertResultMatch( - result, - responses.prepareCheckCancel.normal, - "prepare" - ); - }); - - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const localInstructions = { - ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - ticketSequence: 23, - }; + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareCheckCancel( test.address, requests.prepareCheckCancel.normal, - localInstructions - ); + ) + assertResultMatch( + result, + responses.prepareCheckCancel.normal, + 'prepare', + ) + }) + + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse( + 'account_info', + rippled.account_info.normal, + ) + const localInstructions = { + ...instructionsWithMaxLedgerVersionOffset, + maxFee: '0.000012', + ticketSequence: 23, + } + const result = await this.client.prepareCheckCancel( + test.address, + requests.prepareCheckCancel.normal, + localInstructions, + ) assertResultMatch( result, responses.prepareCheckCancel.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/prepareCheckCash.ts b/test/client/prepareCheckCash.ts index bfa1bec2..4720aefc 100644 --- a/test/client/prepareCheckCash.ts +++ b/test/client/prepareCheckCash.ts @@ -1,71 +1,71 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareCheckCash", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareCheckCash', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareCheckCash amount", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareCheckCash amount', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const result = await this.client.prepareCheckCash( - test.address, - requests.prepareCheckCash.amount - ); - assertResultMatch(result, responses.prepareCheckCash.amount, "prepare"); - }); - - it("prepareCheckCash deliverMin", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const result = await this.client.prepareCheckCash( - test.address, - requests.prepareCheckCash.deliverMin - ); - assertResultMatch( - result, - responses.prepareCheckCash.deliverMin, - "prepare" - ); - }); - - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const localInstructions = { - ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - ticketSequence: 23, - }; + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareCheckCash( test.address, requests.prepareCheckCash.amount, - localInstructions - ); - assertResultMatch(result, responses.prepareCheckCash.ticket, "prepare"); - }); - }); - }); -}); + ) + assertResultMatch(result, responses.prepareCheckCash.amount, 'prepare') + }) + + it('prepareCheckCash deliverMin', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse( + 'account_info', + rippled.account_info.normal, + ) + const result = await this.client.prepareCheckCash( + test.address, + requests.prepareCheckCash.deliverMin, + ) + assertResultMatch( + result, + responses.prepareCheckCash.deliverMin, + 'prepare', + ) + }) + + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse( + 'account_info', + rippled.account_info.normal, + ) + const localInstructions = { + ...instructionsWithMaxLedgerVersionOffset, + maxFee: '0.000012', + ticketSequence: 23, + } + const result = await this.client.prepareCheckCash( + test.address, + requests.prepareCheckCash.amount, + localInstructions, + ) + assertResultMatch(result, responses.prepareCheckCash.ticket, 'prepare') + }) + }) + }) +}) diff --git a/test/client/prepareCheckCreate.ts b/test/client/prepareCheckCreate.ts index e74b60aa..33dfcd5f 100644 --- a/test/client/prepareCheckCreate.ts +++ b/test/client/prepareCheckCreate.ts @@ -1,80 +1,80 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareCheckCreate", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareCheckCreate', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareCheckCreate", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareCheckCreate', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const result = await this.client.prepareCheckCreate( test.address, requests.prepareCheckCreate.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.prepareCheckCreate.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("prepareCheckCreate full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareCheckCreate full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareCheckCreate( test.address, - requests.prepareCheckCreate.full - ); - assertResultMatch(result, responses.prepareCheckCreate.full, "prepare"); - }); + requests.prepareCheckCreate.full, + ) + assertResultMatch(result, responses.prepareCheckCreate.full, 'prepare') + }) - it("prepareCheckCreate with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareCheckCreate with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.prepareCheckCreate( test.address, requests.prepareCheckCreate.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.prepareCheckCreate.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/prepareEscrowCancellation.ts b/test/client/prepareEscrowCancellation.ts index da51b998..4cf8fe36 100644 --- a/test/client/prepareEscrowCancellation.ts +++ b/test/client/prepareEscrowCancellation.ts @@ -1,80 +1,80 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareEscrowCancellation", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareEscrowCancellation', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareEscrowCancellation", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowCancellation', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareEscrowCancellation( test.address, requests.prepareEscrowCancellation.normal, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( result, responses.prepareEscrowCancellation.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("prepareEscrowCancellation with memos", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowCancellation with memos', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareEscrowCancellation( test.address, - requests.prepareEscrowCancellation.memos - ); + requests.prepareEscrowCancellation.memos, + ) assertResultMatch( result, responses.prepareEscrowCancellation.memos, - "prepare" - ); - }); + 'prepare', + ) + }) - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.prepareEscrowCancellation( test.address, requests.prepareEscrowCancellation.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.prepareEscrowCancellation.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/prepareEscrowCreation.ts b/test/client/prepareEscrowCreation.ts index 2f82a331..881ae4e7 100644 --- a/test/client/prepareEscrowCreation.ts +++ b/test/client/prepareEscrowCreation.ts @@ -1,55 +1,51 @@ -import addresses from "../fixtures/addresses.json"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch } from "../testUtils"; +import addresses from '../fixtures/addresses.json' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } export const config = { // TODO: The mock server right now returns a hard-coded string, no matter // what "Account" value you pass. We'll need it to support more accurate // responses before we can turn these tests on. skipXAddress: true, -}; +} -describe("client.prepareEscrowCreation", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareEscrowCreation', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("prepareEscrowCreation", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('prepareEscrowCreation', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const result = await this.client.prepareEscrowCreation( addresses.ACCOUNT, requests.prepareEscrowCreation.normal, - localInstructions - ); - assertResultMatch( - result, - responses.prepareEscrowCreation.normal, - "prepare" - ); - }); + localInstructions, + ) + assertResultMatch(result, responses.prepareEscrowCreation.normal, 'prepare') + }) - it("prepareEscrowCreation full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('prepareEscrowCreation full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const result = await this.client.prepareEscrowCreation( addresses.ACCOUNT, - requests.prepareEscrowCreation.full - ); - assertResultMatch(result, responses.prepareEscrowCreation.full, "prepare"); - }); + requests.prepareEscrowCreation.full, + ) + assertResultMatch(result, responses.prepareEscrowCreation.full, 'prepare') + }) // it("prepareEscrowCreation - invalid", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -65,25 +61,21 @@ describe("client.prepareEscrowCreation", function () { // ); // }); - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000396", + maxFee: '0.000396', ticketSequence: 23, - }; + } const result = await this.client.prepareEscrowCreation( addresses.ACCOUNT, requests.prepareEscrowCreation.normal, - localInstructions - ); - assertResultMatch( - result, - responses.prepareEscrowCreation.ticket, - "prepare" - ); - }); -}); + localInstructions, + ) + assertResultMatch(result, responses.prepareEscrowCreation.ticket, 'prepare') + }) +}) diff --git a/test/client/prepareEscrowExecution.ts b/test/client/prepareEscrowExecution.ts index ea5570f9..0b81870b 100644 --- a/test/client/prepareEscrowExecution.ts +++ b/test/client/prepareEscrowExecution.ts @@ -1,118 +1,118 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { addressTests, assertRejects, assertResultMatch } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { addressTests, assertRejects, assertResultMatch } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareEscrowExecution", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareEscrowExecution', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareEscrowExecution", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowExecution', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareEscrowExecution( test.address, requests.prepareEscrowExecution.normal, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( result, responses.prepareEscrowExecution.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("prepareEscrowExecution - simple", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowExecution - simple', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareEscrowExecution( test.address, - requests.prepareEscrowExecution.simple - ); + requests.prepareEscrowExecution.simple, + ) assertResultMatch( result, responses.prepareEscrowExecution.simple, - "prepare" - ); - }); + 'prepare', + ) + }) - it("prepareEscrowExecution - no condition", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowExecution - no condition', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) await assertRejects( this.client.prepareEscrowExecution( test.address, requests.prepareEscrowExecution.noCondition, - instructionsWithMaxLedgerVersionOffset + instructionsWithMaxLedgerVersionOffset, ), this.client.errors.ValidationError, - '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.' - ); - }); + '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.', + ) + }) - it("prepareEscrowExecution - no fulfillment", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareEscrowExecution - no fulfillment', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) await assertRejects( this.client.prepareEscrowExecution( test.address, requests.prepareEscrowExecution.noFulfillment, - instructionsWithMaxLedgerVersionOffset + instructionsWithMaxLedgerVersionOffset, ), this.client.errors.ValidationError, - '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.' - ); - }); + '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.', + ) + }) - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000396", + maxFee: '0.000396', ticketSequence: 23, - }; + } const result = await this.client.prepareEscrowExecution( test.address, requests.prepareEscrowExecution.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.prepareEscrowExecution.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/prepareOrder.ts b/test/client/prepareOrder.ts index e4dddfc5..ee767ead 100644 --- a/test/client/prepareOrder.ts +++ b/test/client/prepareOrder.ts @@ -1,64 +1,64 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareOrder", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareOrder', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("buy order", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('buy order', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrder.buy; - const result = await this.client.prepareOrder(test.address, request); - assertResultMatch(result, responses.prepareOrder.buy, "prepare"); - }); + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrder.buy + const result = await this.client.prepareOrder(test.address, request) + assertResultMatch(result, responses.prepareOrder.buy, 'prepare') + }) - it("buy order with expiration", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('buy order with expiration', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrder.expiration; - const response = responses.prepareOrder.expiration; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrder.expiration + const response = responses.prepareOrder.expiration const result = await this.client.prepareOrder( test.address, request, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(result, response, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(result, response, 'prepare') + }) - it("sell order", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('sell order', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrder.sell; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrder.sell const result = await this.client.prepareOrder( test.address, request, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(result, responses.prepareOrder.sell, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(result, responses.prepareOrder.sell, 'prepare') + }) // it("invalid", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -81,27 +81,27 @@ describe("client.prepareOrder", function () { // ); // }); - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrder.sell; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrder.sell const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.prepareOrder( test.address, request, - localInstructions - ); - assertResultMatch(result, responses.prepareOrder.ticket, "prepare"); - }); - }); - }); -}); + localInstructions, + ) + assertResultMatch(result, responses.prepareOrder.ticket, 'prepare') + }) + }) + }) +}) diff --git a/test/client/prepareOrderCancellation.ts b/test/client/prepareOrderCancellation.ts index 0b074d6d..2d9b275e 100644 --- a/test/client/prepareOrderCancellation.ts +++ b/test/client/prepareOrderCancellation.ts @@ -1,77 +1,77 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareOrderCancellation", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareOrderCancellation', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("prepareOrderCancellation", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('prepareOrderCancellation', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrderCancellation.simple; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrderCancellation.simple const result = await this.client.prepareOrderCancellation( test.address, request, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( result, responses.prepareOrderCancellation.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("no instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('no instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrderCancellation.simple; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrderCancellation.simple const result = await this.client.prepareOrderCancellation( test.address, - request - ); + request, + ) assertResultMatch( result, responses.prepareOrderCancellation.noInstructions, - "prepare" - ); - }); + 'prepare', + ) + }) - it("with memos", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with memos', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrderCancellation.withMemos; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrderCancellation.withMemos const result = await this.client.prepareOrderCancellation( test.address, - request - ); + request, + ) assertResultMatch( result, responses.prepareOrderCancellation.withMemos, - "prepare" - ); - }); + 'prepare', + ) + }) // it("invalid", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -93,31 +93,31 @@ describe("client.prepareOrderCancellation", function () { // ); // }); - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const request = requests.prepareOrderCancellation.simple; + 'account_info', + rippled.account_info.normal, + ) + const request = requests.prepareOrderCancellation.simple const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.prepareOrderCancellation( test.address, request, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.prepareOrderCancellation.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/preparePayment.ts b/test/client/preparePayment.ts index 0bd85e89..5496a44d 100644 --- a/test/client/preparePayment.ts +++ b/test/client/preparePayment.ts @@ -1,249 +1,249 @@ -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests, assertRejects } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests, assertRejects } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; -const { preparePayment: REQUEST_FIXTURES } = requests; -const { preparePayment: RESPONSE_FIXTURES } = responses; -const RECIPIENT_ADDRESS = "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo"; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +const { preparePayment: REQUEST_FIXTURES } = requests +const { preparePayment: RESPONSE_FIXTURES } = responses +const RECIPIENT_ADDRESS = 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' -describe("client.preparePayment", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.preparePayment', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("normal", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('normal', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.normal, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.normal, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.normal, 'prepare') + }) - it("min amount xrp", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('min amount xrp', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.minAmountXRP, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.minAmountXRP, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.minAmountXRP, 'prepare') + }) - it("min amount xrp2xrp", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('min amount xrp2xrp', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.minAmount, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, RESPONSE_FIXTURES.minAmountXRPXRP, - "prepare" - ); - }); + 'prepare', + ) + }) - it("XRP to XRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('XRP to XRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { - address: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - maxAmount: { value: "1", currency: "XRP" }, + address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + maxAmount: { value: '1', currency: 'XRP' }, }, destination: { - address: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - amount: { value: "1", currency: "XRP" }, + address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + amount: { value: '1', currency: 'XRP' }, }, - }; + } const expected = { txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}', instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, payment, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expected, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expected, 'prepare') + }) - it("XRP drops to XRP drops", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('XRP drops to XRP drops', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { - address: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - maxAmount: { value: "1000000", currency: "drops" }, + address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + maxAmount: { value: '1000000', currency: 'drops' }, }, destination: { - address: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - amount: { value: "1000000", currency: "drops" }, + address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + amount: { value: '1000000', currency: 'drops' }, }, - }; + } const expected = { txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}', instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, payment, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expected, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expected, 'prepare') + }) - it("XRP drops to XRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('XRP drops to XRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { - address: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - maxAmount: { value: "1000000", currency: "drops" }, + address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + maxAmount: { value: '1000000', currency: 'drops' }, }, destination: { - address: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - amount: { value: "1", currency: "XRP" }, + address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + amount: { value: '1', currency: 'XRP' }, }, - }; + } const expected = { txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}', instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, payment, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expected, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expected, 'prepare') + }) - it("XRP to XRP drops", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('XRP to XRP drops', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { - address: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - maxAmount: { value: "1", currency: "XRP" }, + address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + maxAmount: { value: '1', currency: 'XRP' }, }, destination: { - address: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - amount: { value: "1000000", currency: "drops" }, + address: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + amount: { value: '1000000', currency: 'drops' }, }, - }; + } const expected = { txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}', instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, payment, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expected, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expected, 'prepare') + }) // Errors - it("rejects promise and does not throw when payment object is invalid", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('rejects promise and does not throw when payment object is invalid', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { address: test.address, // instead of `maxAmount` - amount: { value: "1000", currency: "drops" }, + amount: { value: '1000', currency: 'drops' }, }, destination: { address: RECIPIENT_ADDRESS, - amount: { value: "1000", currency: "drops" }, + amount: { value: '1000', currency: 'drops' }, }, - }; + } return assertRejects( this.client.preparePayment(test.address, payment), ValidationError, - "payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)" - ); - }); + 'payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)', + ) + }) // it("rejects promise and does not throw when field is missing", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -269,107 +269,107 @@ describe("client.preparePayment", function () { // ); // }); - it("rejects promise and does not throw when fee exceeds maxFeeXRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('rejects promise and does not throw when fee exceeds maxFeeXRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = { source: { address: test.address, - maxAmount: { value: "1000", currency: "drops" }, + maxAmount: { value: '1000', currency: 'drops' }, }, destination: { address: RECIPIENT_ADDRESS, - amount: { value: "1000", currency: "drops" }, + amount: { value: '1000', currency: 'drops' }, }, - }; + } return assertRejects( - this.client.preparePayment(test.address, payment, { fee: "3" }), + this.client.preparePayment(test.address, payment, { fee: '3' }), ValidationError, - "Fee of 3 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the Client constructor." - ); - }); + 'Fee of 3 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the Client constructor.', + ) + }) - it("XRP to XRP no partial", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('XRP to XRP no partial', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) return assertRejects( this.client.preparePayment( test.address, - REQUEST_FIXTURES.wrongPartial + REQUEST_FIXTURES.wrongPartial, ), ValidationError, - "XRP to XRP payments cannot be partial payments" - ); - }); + 'XRP to XRP payments cannot be partial payments', + ) + }) - it("address must match payment.source.address", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('address must match payment.source.address', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) return assertRejects( this.client.preparePayment( test.address, - REQUEST_FIXTURES.wrongAddress + REQUEST_FIXTURES.wrongAddress, ), ValidationError, - "address must match payment.source.address" - ); - }); + 'address must match payment.source.address', + ) + }) - it("wrong amount", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('wrong amount', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) return assertRejects( this.client.preparePayment( test.address, - REQUEST_FIXTURES.wrongAmount + REQUEST_FIXTURES.wrongAmount, ), ValidationError, - "payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)" - ); - }); + 'payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)', + ) + }) - it("throws when fee exceeds 2 XRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('throws when fee exceeds 2 XRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - fee: "2.1", - }; + fee: '2.1', + } return assertRejects( this.client.preparePayment( test.address, REQUEST_FIXTURES.normal, - localInstructions + localInstructions, ), ValidationError, - "Fee of 2.1 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the Client constructor." - ); - }); + 'Fee of 2.1 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the Client constructor.', + ) + }) // 'preparePayment with all options specified': async (client, test.address) => { // const ledgerResponse = await this.client.request({command: 'ledger', ledger_index: 'validated'}) @@ -386,215 +386,207 @@ describe("client.preparePayment", function () { // assertResultMatch(response, RESPONSE_FIXTURES.allOptions, 'prepare') // }, - it("preparePayment without counterparty set", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('preparePayment without counterparty set', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, sequence: 23, - }; + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.noCounterparty, - localInstructions - ); - assertResultMatch( - response, - RESPONSE_FIXTURES.noCounterparty, - "prepare" - ); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.noCounterparty, 'prepare') + }) - it("preparePayment with source.amount/destination.minAmount can be signed", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('preparePayment with source.amount/destination.minAmount can be signed', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) // See also: 'sign succeeds with source.amount/destination.minAmount' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, sequence: 23, - }; + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.noCounterparty, - localInstructions - ); - assertResultMatch( - response, - RESPONSE_FIXTURES.noCounterparty, - "prepare" - ); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.noCounterparty, 'prepare') + }) - it("destination.minAmount", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('destination.minAmount', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const response = await this.client.preparePayment( test.address, responses.getPaths.sendAll[0], - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, RESPONSE_FIXTURES.minAmount, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, RESPONSE_FIXTURES.minAmount, 'prepare') + }) - it("caps fee at 2 XRP by default", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('caps fee at 2 XRP by default', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - this.client.feeCushion = 1000000; + 'account_info', + rippled.account_info.normal, + ) + this.client.feeCushion = 1000000 const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"2000000","Sequence":23}', instructions: { - fee: "2", + fee: '2', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.normal, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) - it("allows fee exceeding 2 XRP when maxFeeXRP is higher", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('allows fee exceeding 2 XRP when maxFeeXRP is higher', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - this.client.maxFeeXRP = "2.2"; + 'account_info', + rippled.account_info.normal, + ) + this.client.maxFeeXRP = '2.2' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - fee: "2.1", - }; + fee: '2.1', + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"2100000","Sequence":23}', instructions: { - fee: "2.1", + fee: '2.1', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, REQUEST_FIXTURES.normal, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) - it("fee - default maxFee of 2 XRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('fee - default maxFee of 2 XRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - this.client.feeCushion = 1000000; + 'account_info', + rippled.account_info.normal, + ) + this.client.feeCushion = 1000000 const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"2000000","Sequence":23}', instructions: { - fee: "2", + fee: '2', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, requests.preparePayment.normal, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) - it("fee - capped to maxFeeXRP when maxFee exceeds maxFeeXRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('fee - capped to maxFeeXRP when maxFee exceeds maxFeeXRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - this.client.feeCushion = 1000000; - this.client.maxFeeXRP = "3"; + 'account_info', + rippled.account_info.normal, + ) + this.client.feeCushion = 1000000 + this.client.maxFeeXRP = '3' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "4", - }; + maxFee: '4', + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"3000000","Sequence":23}', instructions: { - fee: "3", + fee: '3', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, requests.preparePayment.normal, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) - it("fee - capped to maxFee", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('fee - capped to maxFee', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - this.client.feeCushion = 1000000; - this.client.maxFeeXRP = "5"; + 'account_info', + rippled.account_info.normal, + ) + this.client.feeCushion = 1000000 + this.client.maxFeeXRP = '5' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "4", - }; + maxFee: '4', + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"4000000","Sequence":23}', instructions: { - fee: "4", + fee: '4', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.preparePayment( test.address, requests.preparePayment.normal, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) // 'fee - calculated fee does not use more than 6 decimal places': async ( // client, @@ -666,6 +658,6 @@ describe("client.preparePayment", function () { // 'instance.instructions is of prohibited type [object Object]' // ) // } - }); - }); -}); + }) + }) +}) diff --git a/test/client/preparePaymentChannelClaim.ts b/test/client/preparePaymentChannelClaim.ts index 8f78ee99..144655ba 100644 --- a/test/client/preparePaymentChannelClaim.ts +++ b/test/client/preparePaymentChannelClaim.ts @@ -1,155 +1,155 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; -const { preparePaymentChannelClaim: REQUEST_FIXTURES } = requests; -const { preparePaymentChannelClaim: RESPONSE_FIXTURES } = responses; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } +const { preparePaymentChannelClaim: REQUEST_FIXTURES } = requests +const { preparePaymentChannelClaim: RESPONSE_FIXTURES } = responses -describe("client.preparePaymentChannelClaim", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.preparePaymentChannelClaim', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("default", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('default', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.preparePaymentChannelClaim( test.address, REQUEST_FIXTURES.normal, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.normal, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.normal, 'prepare') + }) - it("with renew", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with renew', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.preparePaymentChannelClaim( test.address, REQUEST_FIXTURES.renew, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.renew, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.renew, 'prepare') + }) - it("with close", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with close', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.preparePaymentChannelClaim( test.address, REQUEST_FIXTURES.close, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.close, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.close, 'prepare') + }) - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const response = await this.client.preparePaymentChannelClaim( test.address, REQUEST_FIXTURES.normal, - localInstructions - ); - assertResultMatch(response, RESPONSE_FIXTURES.ticket, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, RESPONSE_FIXTURES.ticket, 'prepare') + }) - it("rejects Promise on preparePaymentChannelClaim with renew and close", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('rejects Promise on preparePaymentChannelClaim with renew and close', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) try { const prepared = await this.client.preparePaymentChannelClaim( test.address, - REQUEST_FIXTURES.full - ); + REQUEST_FIXTURES.full, + ) throw new Error( `Expected method to reject. Prepared transaction: ${JSON.stringify( - prepared - )}` - ); + prepared, + )}`, + ) } catch (err) { - assert.strictEqual(err.name, "ValidationError"); + assert.strictEqual(err.name, 'ValidationError') assert.strictEqual( err.message, - '"renew" and "close" flags on PaymentChannelClaim are mutually exclusive' - ); + '"renew" and "close" flags on PaymentChannelClaim are mutually exclusive', + ) } - }); + }) - it("rejects Promise on preparePaymentChannelClaim with no signature", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('rejects Promise on preparePaymentChannelClaim with no signature', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) try { const prepared = await this.client.preparePaymentChannelClaim( test.address, - REQUEST_FIXTURES.noSignature - ); + REQUEST_FIXTURES.noSignature, + ) throw new Error( `Expected method to reject. Prepared transaction: ${JSON.stringify( - prepared - )}` - ); + prepared, + )}`, + ) } catch (err) { - assert.strictEqual(err.name, "ValidationError"); + assert.strictEqual(err.name, 'ValidationError') assert.strictEqual( err.message, - '"signature" and "publicKey" fields on PaymentChannelClaim must only be specified together.' - ); + '"signature" and "publicKey" fields on PaymentChannelClaim must only be specified together.', + ) } - }); - }); - }); -}); + }) + }) + }) +}) diff --git a/test/client/preparePaymentChannelCreate.ts b/test/client/preparePaymentChannelCreate.ts index 72aef5d1..350642ba 100644 --- a/test/client/preparePaymentChannelCreate.ts +++ b/test/client/preparePaymentChannelCreate.ts @@ -1,79 +1,79 @@ -import addresses from "../fixtures/addresses.json"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch } from "../testUtils"; +import addresses from '../fixtures/addresses.json' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } export const config = { // TODO: The mock server right now returns a hard-coded string, no matter // what "Account" value you pass. We'll need it to support more accurate // responses before we can turn these tests on. skipXAddress: true, -}; +} -describe("client.preparePaymentChannelCreate", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.preparePaymentChannelCreate', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("preparePaymentChannelCreate", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('preparePaymentChannelCreate', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const result = await this.client.preparePaymentChannelCreate( addresses.ACCOUNT, requests.preparePaymentChannelCreate.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.preparePaymentChannelCreate.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("preparePaymentChannelCreate full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('preparePaymentChannelCreate full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const result = await this.client.preparePaymentChannelCreate( addresses.ACCOUNT, - requests.preparePaymentChannelCreate.full - ); + requests.preparePaymentChannelCreate.full, + ) assertResultMatch( result, responses.preparePaymentChannelCreate.full, - "prepare" - ); - }); + 'prepare', + ) + }) - it("preparePaymentChannelCreate with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('preparePaymentChannelCreate with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.preparePaymentChannelCreate( addresses.ACCOUNT, requests.preparePaymentChannelCreate.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.preparePaymentChannelCreate.ticket, - "prepare" - ); - }); -}); + 'prepare', + ) + }) +}) diff --git a/test/client/preparePaymentChannelFund.ts b/test/client/preparePaymentChannelFund.ts index 05fab95a..5661a1d6 100644 --- a/test/client/preparePaymentChannelFund.ts +++ b/test/client/preparePaymentChannelFund.ts @@ -1,84 +1,84 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.preparePaymentChannelFund", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.preparePaymentChannelFund', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("preparePaymentChannelFund", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('preparePaymentChannelFund', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const result = await this.client.preparePaymentChannelFund( test.address, requests.preparePaymentChannelFund.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.preparePaymentChannelFund.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("preparePaymentChannelFund full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('preparePaymentChannelFund full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.preparePaymentChannelFund( test.address, - requests.preparePaymentChannelFund.full - ); + requests.preparePaymentChannelFund.full, + ) assertResultMatch( result, responses.preparePaymentChannelFund.full, - "prepare" - ); - }); + 'prepare', + ) + }) - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.preparePaymentChannelFund( test.address, requests.preparePaymentChannelFund.normal, - localInstructions - ); + localInstructions, + ) assertResultMatch( result, responses.preparePaymentChannelFund.ticket, - "prepare" - ); - }); - }); - }); -}); + 'prepare', + ) + }) + }) + }) +}) diff --git a/test/client/prepareSettings.ts b/test/client/prepareSettings.ts index 4bbefb7a..ed6c82d5 100644 --- a/test/client/prepareSettings.ts +++ b/test/client/prepareSettings.ts @@ -1,251 +1,251 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { FormattedSettings } from "../../src/common/types/objects"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import { FormattedSettings } from '../../src/common/types/objects' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareSettings", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareSettings', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("simple test", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('simple test', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const response = await this.client.prepareSettings( test.address, requests.prepareSettings.domain, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(response, responses.prepareSettings.flags, "prepare"); - }); - it("no maxLedgerVersion", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(response, responses.prepareSettings.flags, 'prepare') + }) + it('no maxLedgerVersion', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const response = await this.client.prepareSettings( test.address, requests.prepareSettings.domain, { maxLedgerVersion: null as unknown as undefined, - } - ); + }, + ) assertResultMatch( response, responses.prepareSettings.noMaxLedgerVersion, - "prepare" - ); - }); - it("no instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('no instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const response = await this.client.prepareSettings( test.address, - requests.prepareSettings.domain - ); + requests.prepareSettings.domain, + ) assertResultMatch( response, responses.prepareSettings.noInstructions, - "prepare" - ); - }); - it("regularKey", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('regularKey', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const regularKey = { regularKey: "rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD" }; + 'account_info', + rippled.account_info.normal, + ) + const regularKey = { regularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD' } const response = await this.client.prepareSettings( test.address, regularKey, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.regularKey, - "prepare" - ); - }); - it("remove regularKey", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('remove regularKey', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const regularKey = { regularKey: null }; + 'account_info', + rippled.account_info.normal, + ) + const regularKey = { regularKey: null } const response = await this.client.prepareSettings( test.address, regularKey as unknown as FormattedSettings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.removeRegularKey, - "prepare" - ); - }); - it("flag set", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('flag set', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { requireDestinationTag: true }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { requireDestinationTag: true } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.flagSet, - "prepare" - ); - }); - it("flag clear", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('flag clear', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { requireDestinationTag: false }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { requireDestinationTag: false } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.flagClear, - "prepare" - ); - }); - it("set depositAuth flag", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('set depositAuth flag', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { depositAuth: true }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { depositAuth: true } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.flagSetDepositAuth, - "prepare" - ); - }); - it("clear depositAuth flag", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('clear depositAuth flag', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { depositAuth: false }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { depositAuth: false } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.flagClearDepositAuth, - "prepare" - ); - }); - it("integer field clear", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('integer field clear', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { transferRate: null }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { transferRate: null } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); - assert(response); - assert.strictEqual(JSON.parse(response.txJSON).TransferRate, 0); - }); - it("set transferRate", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + instructionsWithMaxLedgerVersionOffset, + ) + assert(response) + assert.strictEqual(JSON.parse(response.txJSON).TransferRate, 0) + }) + it('set transferRate', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = { transferRate: 1 }; + 'account_info', + rippled.account_info.normal, + ) + const settings = { transferRate: 1 } const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.setTransferRate, - "prepare" - ); - }); - it("set signers", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('set signers', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = requests.prepareSettings.signers.normal; + 'account_info', + rippled.account_info.normal, + ) + const settings = requests.prepareSettings.signers.normal const response = await this.client.prepareSettings( test.address, settings, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.prepareSettings.signers, - "prepare" - ); - }); + 'prepare', + ) + }) // it("signers no threshold", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); // this.mockRippled.addResponse("fee", rippled.fee); @@ -274,77 +274,77 @@ describe("client.prepareSettings", function () { // assert.strictEqual(err.name, "ValidationError"); // } // }); - it("signers no weights", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('signers no weights', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = requests.prepareSettings.signers.noWeights; + 'account_info', + rippled.account_info.normal, + ) + const settings = requests.prepareSettings.signers.noWeights const localInstructions = { signersCount: 1, ...instructionsWithMaxLedgerVersionOffset, - }; + } const response = await this.client.prepareSettings( test.address, settings, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.prepareSettings.noWeights, - "prepare" - ); - }); - it("fee for multisign", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('fee for multisign', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { signersCount: 4, ...instructionsWithMaxLedgerVersionOffset, - }; + } const response = await this.client.prepareSettings( test.address, requests.prepareSettings.domain, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.prepareSettings.flagsMultisign, - "prepare" - ); - }); - it("no signer list", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + 'prepare', + ) + }) + it('no signer list', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const settings = requests.prepareSettings.noSignerEntries; + 'account_info', + rippled.account_info.normal, + ) + const settings = requests.prepareSettings.noSignerEntries const localInstructions = { signersCount: 1, ...instructionsWithMaxLedgerVersionOffset, - }; + } const response = await this.client.prepareSettings( test.address, settings, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.prepareSettings.noSignerList, - "prepare" - ); - }); + 'prepare', + ) + }) // it("invalid", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); // this.mockRippled.addResponse("fee", rippled.fee); @@ -379,57 +379,53 @@ describe("client.prepareSettings", function () { // assert.strictEqual(err.name, "ValidationError"); // } // }); - it("offline", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('offline', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + 'account_info', + rippled.account_info.normal, + ) + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' - const settings = requests.prepareSettings.domain; + const settings = requests.prepareSettings.domain const instructions = { sequence: 23, maxLedgerVersion: 8820051, - fee: "0.000012", - }; + fee: '0.000012', + } const result = await this.client.prepareSettings( test.address, settings, - instructions - ); - assertResultMatch(result, responses.prepareSettings.flags, "prepare"); + instructions, + ) + assertResultMatch(result, responses.prepareSettings.flags, 'prepare') assert.deepEqual( this.client.sign(result.txJSON, secret), - responses.prepareSettings.signed - ); - }); - it("prepare settings with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + responses.prepareSettings.signed, + ) + }) + it('prepare settings with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const instructions = { ticketSequence: 23, maxLedgerVersion: 8820051, - fee: "0.000012", - }; + fee: '0.000012', + } const response = await this.client.prepareSettings( test.address, requests.prepareSettings.domain, - instructions - ); - assertResultMatch( - response, - responses.prepareSettings.ticket, - "prepare" - ); - }); - }); - }); -}); + instructions, + ) + assertResultMatch(response, responses.prepareSettings.ticket, 'prepare') + }) + }) + }) +}) diff --git a/test/client/prepareTicket.ts b/test/client/prepareTicket.ts index 29e6ab87..3022a529 100644 --- a/test/client/prepareTicket.ts +++ b/test/client/prepareTicket.ts @@ -1,6 +1,6 @@ -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' // import responses from '../fixtures/responses' // import requests from '../fixtures/requests' // import {ValidationError} from 'xrpl-local/common/errors' @@ -14,62 +14,62 @@ import { assertResultMatch, addressTests } from "../testUtils"; // const {preparePayment: RESPONSE_FIXTURES} = responses // const ADDRESS = 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' -describe("client.prepareTicket", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareTicket', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("creates a ticket successfully with a sequence number", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('creates a ticket successfully with a sequence number', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) 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", + fee: '0.000012', }, - }; - const response = await this.client.prepareTicketCreate(test.address, 2); - assertResultMatch(response, expected, "prepare"); - }); + } + const response = await this.client.prepareTicketCreate(test.address, 2) + assertResultMatch(response, expected, 'prepare') + }) - it("creates a ticket successfully with another ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('creates a ticket successfully with another ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) 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", + fee: '0.000012', }, - }; + } const instructions = { maxLedgerVersion: 8819954, ticketSequence: 23, - fee: "0.000012", - }; + fee: '0.000012', + } const response = await this.client.prepareTicketCreate( test.address, 1, - instructions - ); - assertResultMatch(response, expected, "prepare"); - }); - }); - }); -}); + instructions, + ) + assertResultMatch(response, expected, 'prepare') + }) + }) + }) +}) diff --git a/test/client/prepareTransaction.ts b/test/client/prepareTransaction.ts index 72e02863..5a499e08 100644 --- a/test/client/prepareTransaction.ts +++ b/test/client/prepareTransaction.ts @@ -1,124 +1,124 @@ -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' // import requests from '../fixtures/requests' -import { xrpToDrops, ISOTimeToRippleTime } from "../../src/utils"; -import addresses from "../fixtures/addresses.json"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertRejects, assertResultMatch } from "../testUtils"; +import { xrpToDrops, ISOTimeToRippleTime } from '../../src/utils' +import addresses from '../fixtures/addresses.json' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertRejects, assertResultMatch } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } export const config = { // TODO: The mock server right now returns a hard-coded string, no matter // what "Account" value you pass. We'll need it to support more accurate // responses before we can turn these tests on. skipXAddress: true, -}; +} -describe("client.prepareTransaction", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareTransaction', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("auto-fillable fields - does not overwrite Fee in txJSON", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - const localInstructions = instructionsWithMaxLedgerVersionOffset; + it('auto-fillable fields - does not overwrite Fee in txJSON', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + const localInstructions = instructionsWithMaxLedgerVersionOffset const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - Fee: "10", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + Fee: '10', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"10","Sequence":23}`, instructions: { - fee: "0.00001", // Notice there are not always 6 digits after the decimal point as trailing zeros are omitted + fee: '0.00001', // Notice there are not always 6 digits after the decimal point as trailing zeros are omitted sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("does not overwrite Fee in Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('does not overwrite Fee in Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - fee: "0.000014", // CAUTION: This `fee` is specified in XRP, not drops. - }; + fee: '0.000014', // CAUTION: This `fee` is specified in XRP, not drops. + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"14","Sequence":23}`, instructions: { - fee: "0.000014", + fee: '0.000014', sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("rejects Promise if both are set, even when txJSON.Fee matches instructions.fee", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('rejects Promise if both are set, even when txJSON.Fee matches instructions.fee', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - fee: "0.000016", - }; + fee: '0.000016', + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - Fee: "16", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + Fee: '16', + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - "`Fee` in txJSON and `fee` in `instructions` cannot both be set" - ); + '`Fee` in txJSON and `fee` in `instructions` cannot both be set', + ) }), - it("rejects Promise if both are set, when txJSON.Fee does not match instructions.fee", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('rejects Promise if both are set, when txJSON.Fee does not match instructions.fee', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - fee: "0.000018", - }; + fee: '0.000018', + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - Fee: "20", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + Fee: '20', + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - "`Fee` in txJSON and `fee` in `instructions` cannot both be set" - ); - }); + '`Fee` in txJSON and `fee` in `instructions` cannot both be set', + ) + }) // it("rejects Promise when the Fee is capitalized in Instructions", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -141,126 +141,126 @@ describe("client.prepareTransaction", function () { // ); // }); - it("rejects Promise when the fee is specified in txJSON", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - const localInstructions = instructionsWithMaxLedgerVersionOffset; + it('rejects Promise when the fee is specified in txJSON', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + const localInstructions = instructionsWithMaxLedgerVersionOffset const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - fee: "10", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + fee: '10', + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - 'txJSON additionalProperty "fee" exists in instance when not allowed' - ); - }); + 'txJSON additionalProperty "fee" exists in instance when not allowed', + ) + }) - it("does not overwrite Sequence in txJSON", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - const localInstructions = instructionsWithMaxLedgerVersionOffset; + it('does not overwrite Sequence in txJSON', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + const localInstructions = instructionsWithMaxLedgerVersionOffset const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - fee: "10", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + fee: '10', + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - 'txJSON additionalProperty "fee" exists in instance when not allowed' - ); - }); + 'txJSON additionalProperty "fee" exists in instance when not allowed', + ) + }) - it("does not overwrite Sequence in Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('does not overwrite Sequence in Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', sequence: 100, - }; + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":100}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 100, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("does not overwrite Sequence when same sequence is provided in both txJSON and Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('does not overwrite Sequence when same sequence is provided in both txJSON and Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', sequence: 100, - }; + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":100}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 100, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("rejects Promise when Sequence in txJSON does not match sequence in Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('rejects Promise when Sequence in txJSON does not match sequence in Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', sequence: 100, - }; + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Sequence: 101, - }; + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - "`Sequence` in txJSON must match `sequence` in `instructions`" - ); - }); + '`Sequence` in txJSON must match `sequence` in `instructions`', + ) + }) // it("rejects Promise when the Sequence is capitalized in Instructions", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -308,62 +308,62 @@ describe("client.prepareTransaction", function () { // ); // }); - it("does not overwrite maxLedgerVersion in Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('does not overwrite maxLedgerVersion in Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { maxLedgerVersion: 8890000, - }; + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8890000,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8890000, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("does not overwrite maxLedgerVersionOffset in Instructions", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('does not overwrite maxLedgerVersionOffset in Instructions', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxLedgerVersionOffset: 124, - }; + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820075,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820075, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) // it("rejects Promise if txJSON.LastLedgerSequence and instructions.maxLedgerVersion both are set", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -501,43 +501,43 @@ describe("client.prepareTransaction", function () { // ); // }); - it("rejects Promise when the maxLedgerVersionOffset is specified in txJSON", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - const localInstructions = instructionsWithMaxLedgerVersionOffset; + it('rejects Promise when the maxLedgerVersionOffset is specified in txJSON', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + const localInstructions = instructionsWithMaxLedgerVersionOffset const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', maxLedgerVersionOffset: 8900000, - }; + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - 'txJSON additionalProperty "maxLedgerVersionOffset" exists in instance when not allowed' - ); - }); + 'txJSON additionalProperty "maxLedgerVersionOffset" exists in instance when not allowed', + ) + }) - it("rejects Promise when the sequence is specified in txJSON", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - const localInstructions = instructionsWithMaxLedgerVersionOffset; + it('rejects Promise when the sequence is specified in txJSON', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + const localInstructions = instructionsWithMaxLedgerVersionOffset const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', sequence: 8900000, - }; + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - 'txJSON additionalProperty "sequence" exists in instance when not allowed' - ); - }); + 'txJSON additionalProperty "sequence" exists in instance when not allowed', + ) + }) // Paths: is not auto-filled by ripple-lib. @@ -674,34 +674,34 @@ describe("client.prepareTransaction", function () { // Error: DepositPreXXXX is not a valid name or ordinal for TransactionType // // at Function.from (ripple-binary-codec/distrib/npm/enums/index.js:43:15) - it("prepares tx when TransactionType is invalid", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('prepares tx when TransactionType is invalid', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "DepositPreXXXX", - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + TransactionType: 'DepositPreXXXX', + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreXXXX","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) // it("rejects Promise when TransactionType is not a string", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -745,223 +745,223 @@ describe("client.prepareTransaction", function () { // '304402201F0EF6A2DE7F96966F7082294D14F3EC1EF59C21E29443E5858A0120079357A302203CDB7FEBDEAAD93FF39CB589B55778CB80DC3979F96F27E828D5E659BEB26B7A', // hash: // 'C181D470684311658852713DA81F8201062535C8DE2FF853F7DD9981BB85312F' } })] - it("prepares tx when a required field is missing", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('prepares tx when a required field is missing', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', // Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' // Normally required, intentionally removed - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("DepositPreauth - Authorize", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('DepositPreauth - Authorize', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Authorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - return assertResultMatch(response, expected, "prepare"); - }); + localInstructions, + ) + return assertResultMatch(response, expected, 'prepare') + }) - it("DepositPreauth - Unauthorize", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('DepositPreauth - Unauthorize', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { - TransactionType: "DepositPreauth", + TransactionType: 'DepositPreauth', Account: addresses.ACCOUNT, - Unauthorize: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - }; + Unauthorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${addresses.ACCOUNT}","Unauthorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) - it("AccountDelete", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('AccountDelete', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "5.0", // 5 XRP fee for AccountDelete - }; + maxFee: '5.0', // 5 XRP fee for AccountDelete + } const txJSON = { - TransactionType: "AccountDelete", + TransactionType: 'AccountDelete', Account: addresses.ACCOUNT, - Destination: "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe", - }; + Destination: 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe', + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) const expected = { txJSON: `{"TransactionType":"AccountDelete","Account":"${addresses.ACCOUNT}","Destination":"rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { - fee: "0.000012", + fee: '0.000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; - return assertResultMatch(response, expected, "prepare"); - }); + } + return assertResultMatch(response, expected, 'prepare') + }) // prepareTransaction - Payment - it("Payment - normal", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('Payment - normal', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, SendMax: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, Flags: 0, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, responses.preparePayment.normal, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, responses.preparePayment.normal, 'prepare') + }) - it("min amount xrp", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('min amount xrp', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', // Max amount to send. Use 100 billion XRP to // ensure that we send the full SendMax amount. - Amount: "100000000000000000", + Amount: '100000000000000000', SendMax: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, - DeliverMin: "10000", + DeliverMin: '10000', Flags: this.client.txFlags.Payment.PartialPayment, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePayment.minAmountXRP, - "prepare" - ); - }); + 'prepare', + ) + }) - it("min amount xrp2xrp", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('min amount xrp2xrp', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", - Amount: "10000", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', + Amount: '10000', Flags: 0, - }; + } const response = await this.client.prepareTransaction( txJSON, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( response, responses.preparePayment.minAmountXRPXRP, - "prepare" - ); - }); + 'prepare', + ) + }) // 'with all options specified': async (client, addresses.ACCOUNT) => { // const ledgerResponse = await this.client.request({ @@ -1000,185 +1000,185 @@ describe("client.prepareTransaction", function () { // assertResultMatch(response, responses.preparePayment.allOptions, 'prepare') // }, - it("fee is capped at default maxFee of 2 XRP (using txJSON.LastLedgerSequence)", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - this.client.feeCushion = 1000000; + it('fee is capped at default maxFee of 2 XRP (using txJSON.LastLedgerSequence)', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + this.client.feeCushion = 1000000 const txJSON = { Flags: 2147483648, - TransactionType: "Payment", - Account: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + TransactionType: 'Payment', + Account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, SendMax: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, LastLedgerSequence: 8820051, - }; - const localInstructions = {}; + } + const localInstructions = {} const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"2000000","Sequence":23}', instructions: { - fee: "2", + fee: '2', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) - it("fee is capped at default maxFee of 2 XRP (using instructions.maxLedgerVersion)", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - this.client.feeCushion = 1000000; + it('fee is capped at default maxFee of 2 XRP (using instructions.maxLedgerVersion)', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + this.client.feeCushion = 1000000 const txJSON = { Flags: 2147483648, - TransactionType: "Payment", - Account: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + TransactionType: 'Payment', + Account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, SendMax: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, - }; + } const localInstructions = { maxLedgerVersion: 8820051, - }; + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"2000000","Sequence":23}', instructions: { - fee: "2", + fee: '2', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) // prepareTransaction - Payment - it("fee is capped to custom maxFeeXRP when maxFee exceeds maxFeeXRP", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - this.client.feeCushion = 1000000; - this.client.maxFeeXRP = "3"; + it('fee is capped to custom maxFeeXRP when maxFee exceeds maxFeeXRP', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + this.client.feeCushion = 1000000 + this.client.maxFeeXRP = '3' const localInstructions = { - maxFee: "4", // We are testing that this does not matter; fee is still capped to maxFeeXRP - }; + maxFee: '4', // We are testing that this does not matter; fee is still capped to maxFeeXRP + } const txJSON = { Flags: 2147483648, - TransactionType: "Payment", - Account: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + TransactionType: 'Payment', + Account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, SendMax: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, LastLedgerSequence: 8820051, - }; + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"3000000","Sequence":23}', instructions: { - fee: "3", + fee: '3', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) // prepareTransaction - Payment - it("fee is capped to maxFee", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); - this.client.feeCushion = 1000000; - this.client.maxFeeXRP = "5"; + it('fee is capped to maxFee', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) + this.client.feeCushion = 1000000 + this.client.maxFeeXRP = '5' const localInstructions = { - maxFee: "4", // maxFeeXRP does not matter if maxFee is lower than maxFeeXRP - }; + maxFee: '4', // maxFeeXRP does not matter if maxFee is lower than maxFeeXRP + } const txJSON = { Flags: 2147483648, - TransactionType: "Payment", - Account: "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59", - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + TransactionType: 'Payment', + Account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, SendMax: { - value: "0.01", - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", + value: '0.01', + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', }, LastLedgerSequence: 8820051, - }; + } const expectedResponse = { txJSON: '{"Flags":2147483648,"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"SendMax":{"value":"0.01","currency":"USD","issuer":"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"},"LastLedgerSequence":8820051,"Fee":"4000000","Sequence":23}', instructions: { - fee: "4", + fee: '4', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, expectedResponse, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, expectedResponse, 'prepare') + }) // 'fee - calculated fee does not use more than 6 decimal places': async ( // client, @@ -1207,249 +1207,249 @@ describe("client.prepareTransaction", function () { // assertResultMatch(response, expectedResponse, 'prepare') // }, - it("xaddresses.ACCOUNT-issuer", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('xaddresses.ACCOUNT-issuer', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - currency: "USD", - issuer: "XVbehP2sFMQAd5orFAy8Lt6vLHGiDhA7VMAnsv9H6WpuB1s", - value: "0.01", + currency: 'USD', + issuer: 'XVbehP2sFMQAd5orFAy8Lt6vLHGiDhA7VMAnsv9H6WpuB1s', + value: '0.01', }, SendMax: { - currency: "USD", - issuer: "XVbehP2sFMQAd5orFAy8Lt6vLHGiDhA7VMAnsv9H6WpuB1s", - value: "0.01", + currency: 'USD', + issuer: 'XVbehP2sFMQAd5orFAy8Lt6vLHGiDhA7VMAnsv9H6WpuB1s', + value: '0.01', }, Flags: 0, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, responses.preparePayment.normal, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, responses.preparePayment.normal, 'prepare') + }) - it("PaymentChannelCreate", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelCreate', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const response = await this.client.prepareTransaction( { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelCreate", - Amount: "1000000", // 1 XRP in drops. Use a string-encoded integer. - Destination: "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW", + TransactionType: 'PaymentChannelCreate', + Amount: '1000000', // 1 XRP in drops. Use a string-encoded integer. + Destination: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', SettleDelay: 86400, PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A", + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', // If cancelAfter is used, you must use RippleTime. // You can use `ISOTimeToRippleTime()` to convert to RippleTime. // Other fields are available (but not used in this test), // including `sourceTag` and `destinationTag`. }, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePaymentChannelCreate.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelCreate full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelCreate full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelCreate", - Amount: xrpToDrops("1"), // or '1000000' - Destination: "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW", + TransactionType: 'PaymentChannelCreate', + Amount: xrpToDrops('1'), // or '1000000' + Destination: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', SettleDelay: 86400, // Ensure this is in upper case if it is not already PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A".toUpperCase(), - CancelAfter: ISOTimeToRippleTime("2017-02-17T15:04:57Z"), + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A'.toUpperCase(), + CancelAfter: ISOTimeToRippleTime('2017-02-17T15:04:57Z'), SourceTag: 11747, DestinationTag: 23480, - }; + } - const response = await this.client.prepareTransaction(txJSON); + const response = await this.client.prepareTransaction(txJSON) assertResultMatch( response, responses.preparePaymentChannelCreate.full, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelFund", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelFund', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelFund", + TransactionType: 'PaymentChannelFund', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Amount: xrpToDrops("1"), // or '1000000' - }; + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Amount: xrpToDrops('1'), // or '1000000' + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePaymentChannelFund.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelFund full", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelFund full', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelFund", + TransactionType: 'PaymentChannelFund', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Amount: xrpToDrops("1"), // or '1000000' - Expiration: ISOTimeToRippleTime("2017-02-17T15:04:57Z"), - }; + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Amount: xrpToDrops('1'), // or '1000000' + Expiration: ISOTimeToRippleTime('2017-02-17T15:04:57Z'), + } - const response = await this.client.prepareTransaction(txJSON); + const response = await this.client.prepareTransaction(txJSON) assertResultMatch( response, responses.preparePaymentChannelFund.full, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelClaim", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelClaim', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelClaim", + TransactionType: 'PaymentChannelClaim', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', Flags: 0, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePaymentChannelClaim.normal, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelClaim with renew", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelClaim with renew', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelClaim", + TransactionType: 'PaymentChannelClaim', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Balance: xrpToDrops("1"), // or '1000000' - Amount: xrpToDrops("1"), // or '1000000' + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Balance: xrpToDrops('1'), // or '1000000' + Amount: xrpToDrops('1'), // or '1000000' Signature: - "30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B", + '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B', PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A", + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', Flags: 0, - }; - txJSON.Flags |= this.client.txFlags.PaymentChannelClaim.Renew; + } + txJSON.Flags |= this.client.txFlags.PaymentChannelClaim.Renew const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePaymentChannelClaim.renew, - "prepare" - ); - }); + 'prepare', + ) + }) - it("PaymentChannelClaim with close", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('PaymentChannelClaim with close', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", - }; + maxFee: '0.000012', + } const txJSON = { Account: addresses.ACCOUNT, - TransactionType: "PaymentChannelClaim", + TransactionType: 'PaymentChannelClaim', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Balance: xrpToDrops("1"), // or 1000000 - Amount: xrpToDrops("1"), // or 1000000 + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Balance: xrpToDrops('1'), // or 1000000 + Amount: xrpToDrops('1'), // or 1000000 Signature: - "30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B", + '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B', PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A", + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', Flags: 0, - }; - txJSON.Flags |= this.client.txFlags.PaymentChannelClaim.Close; + } + txJSON.Flags |= this.client.txFlags.PaymentChannelClaim.Close const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); + localInstructions, + ) assertResultMatch( response, responses.preparePaymentChannelClaim.close, - "prepare" - ); - }); + 'prepare', + ) + }) // it("rejects Promise if both sequence and ticketSequence are set", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -1473,73 +1473,73 @@ describe("client.prepareTransaction", function () { // ); // }); - it("sets sequence to 0 if a ticketSequence is passed", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('sets sequence to 0 if a ticketSequence is passed', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, SendMax: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, Flags: 0, - }; + } const response = await this.client.prepareTransaction( txJSON, - localInstructions - ); - assertResultMatch(response, responses.preparePayment.ticket, "prepare"); - }); + localInstructions, + ) + assertResultMatch(response, responses.preparePayment.ticket, 'prepare') + }) - it("rejects Promise if a sequence with value 0 is passed", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); - this.mockRippled.addResponse("account_info", rippled.account_info.normal); + it('rejects Promise if a sequence with value 0 is passed', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) + this.mockRippled.addResponse('account_info', rippled.account_info.normal) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', sequence: 0, - }; + } const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: addresses.ACCOUNT, - Destination: "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo", + Destination: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Amount: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, SendMax: { - currency: "USD", - issuer: "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM", - value: "0.01", + currency: 'USD', + issuer: 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM', + value: '0.01', }, Flags: 0, - }; + } await assertRejects( this.client.prepareTransaction(txJSON, localInstructions), ValidationError, - "`sequence` cannot be 0" - ); - }); -}); + '`sequence` cannot be 0', + ) + }) +}) diff --git a/test/client/prepareTrustline.ts b/test/client/prepareTrustline.ts index 99e0d158..0422eee2 100644 --- a/test/client/prepareTrustline.ts +++ b/test/client/prepareTrustline.ts @@ -1,67 +1,63 @@ -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertResultMatch, addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertResultMatch, addressTests } from '../testUtils' -const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 }; +const instructionsWithMaxLedgerVersionOffset = { maxLedgerVersionOffset: 100 } -describe("client.prepareTrustline", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.prepareTrustline', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("simple", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('simple', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareTrustline( test.address, requests.prepareTrustline.simple, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch(result, responses.prepareTrustline.simple, "prepare"); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(result, responses.prepareTrustline.simple, 'prepare') + }) - it("frozen", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('frozen', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareTrustline( test.address, - requests.prepareTrustline.frozen - ); - assertResultMatch(result, responses.prepareTrustline.frozen, "prepare"); - }); + requests.prepareTrustline.frozen, + ) + assertResultMatch(result, responses.prepareTrustline.frozen, 'prepare') + }) - it("complex", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('complex', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareTrustline( test.address, requests.prepareTrustline.complex, - instructionsWithMaxLedgerVersionOffset - ); - assertResultMatch( - result, - responses.prepareTrustline.complex, - "prepare" - ); - }); + instructionsWithMaxLedgerVersionOffset, + ) + assertResultMatch(result, responses.prepareTrustline.complex, 'prepare') + }) // it("invalid", async function () { // this.mockRippled.addResponse("server_info", rippled.server_info.normal); @@ -85,46 +81,46 @@ describe("client.prepareTrustline", function () { // ); // }); - it("xtest.address-issuer", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('xtest.address-issuer', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const result = await this.client.prepareTrustline( test.address, requests.prepareTrustline.issuedXAddress, - instructionsWithMaxLedgerVersionOffset - ); + instructionsWithMaxLedgerVersionOffset, + ) assertResultMatch( result, responses.prepareTrustline.issuedXAddress, - "prepare" - ); - }); + 'prepare', + ) + }) - it("with ticket", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('with ticket', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, - maxFee: "0.000012", + maxFee: '0.000012', ticketSequence: 23, - }; + } const result = await this.client.prepareTrustline( test.address, requests.prepareTrustline.simple, - localInstructions - ); - assertResultMatch(result, responses.prepareTrustline.ticket, "prepare"); - }); - }); - }); -}); + localInstructions, + ) + assertResultMatch(result, responses.prepareTrustline.ticket, 'prepare') + }) + }) + }) +}) diff --git a/test/client/request.ts b/test/client/request.ts index ad77310a..46cced7e 100644 --- a/test/client/request.ts +++ b/test/client/request.ts @@ -1,47 +1,47 @@ -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { addressTests, assertResultMatch } from "../testUtils"; +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { addressTests, assertResultMatch } from '../testUtils' -describe("client.request", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('client.request', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) addressTests.forEach(function (test) { describe(test.type, function () { - it("request account_objects", async function () { + it('request account_objects', async function () { this.mockRippled.addResponse( - "account_objects", - rippled.account_objects.normal - ); + 'account_objects', + rippled.account_objects.normal, + ) const result = await this.client.request({ - command: "account_objects", + command: 'account_objects', account: test.address, - }); + }) assertResultMatch( result.result, responses.getAccountObjects, - "AccountObjectsResponse" - ); - }); + 'AccountObjectsResponse', + ) + }) - it("request account_objects - invalid options", async function () { + it('request account_objects - invalid options', async function () { this.mockRippled.addResponse( - "account_objects", - rippled.account_objects.normal - ); + 'account_objects', + rippled.account_objects.normal, + ) const result = await this.client.request({ - command: "account_objects", + command: 'account_objects', account: test.address, - }); + }) assertResultMatch( result.result, responses.getAccountObjects, - "AccountObjectsResponse" - ); - }); - }); - }); -}); + 'AccountObjectsResponse', + ) + }) + }) + }) +}) diff --git a/test/client/requestNextPage.ts b/test/client/requestNextPage.ts index 8128b9f6..39f9a5a1 100644 --- a/test/client/requestNextPage.ts +++ b/test/client/requestNextPage.ts @@ -1,45 +1,45 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { Client } from "../../src"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { assertRejects } from "../testUtils"; +import { Client } from '../../src' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { assertRejects } from '../testUtils' const rippledResponse = function (request: Request): object { - if ("marker" in request) { - return rippled.ledger_data.last_page; + if ('marker' in request) { + return rippled.ledger_data.last_page } - return rippled.ledger_data.first_page; -}; + return rippled.ledger_data.first_page +} -describe("client.requestNextPage", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); - it("requests the next page", async function () { - this.mockRippled.addResponse("ledger_data", rippledResponse); - const response = await this.client.request({ command: "ledger_data" }); +describe('client.requestNextPage', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) + it('requests the next page', async function () { + this.mockRippled.addResponse('ledger_data', rippledResponse) + const response = await this.client.request({ command: 'ledger_data' }) const responseNextPage = await this.client.requestNextPage( - { command: "ledger_data" }, - response - ); + { command: 'ledger_data' }, + response, + ) assert.equal( responseNextPage.result.state[0].index, - "000B714B790C3C79FEE00D17C4DEB436B375466F29679447BA64F265FD63D731" - ); - }); + '000B714B790C3C79FEE00D17C4DEB436B375466F29679447BA64F265FD63D731', + ) + }) - it("rejects when there are no more pages", async function () { - this.mockRippled.addResponse("ledger_data", rippledResponse); - const response = await this.client.request({ command: "ledger_data" }); + it('rejects when there are no more pages', async function () { + this.mockRippled.addResponse('ledger_data', rippledResponse) + const response = await this.client.request({ command: 'ledger_data' }) const responseNextPage = await this.client.requestNextPage( - { command: "ledger_data" }, - response - ); - assert(!Client.hasNextPage(responseNextPage)); + { command: 'ledger_data' }, + response, + ) + assert(!Client.hasNextPage(responseNextPage)) await assertRejects( - this.client.requestNextPage({ command: "ledger_data" }, responseNextPage), + this.client.requestNextPage({ command: 'ledger_data' }, responseNextPage), Error, - "response does not have a next page" - ); - }); -}); + 'response does not have a next page', + ) + }) +}) diff --git a/test/client/sign.ts b/test/client/sign.ts index 07e6e84c..6ccc77de 100644 --- a/test/client/sign.ts +++ b/test/client/sign.ts @@ -1,34 +1,34 @@ -import { assert } from "chai"; -import binary from "ripple-binary-codec"; +import { assert } from 'chai' +import binary from 'ripple-binary-codec' -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import rippled from "../fixtures/rippled"; -import setupClient from "../setupClient"; -import { addressTests } from "../testUtils"; +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import rippled from '../fixtures/rippled' +import setupClient from '../setupClient' +import { addressTests } from '../testUtils' -const { sign: REQUEST_FIXTURES } = requests; -const { sign: RESPONSE_FIXTURES } = responses; +const { sign: REQUEST_FIXTURES } = requests +const { sign: RESPONSE_FIXTURES } = responses -describe("client.sign", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); - it("sign", async function () { - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; - const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, secret); - assert.deepEqual(result, RESPONSE_FIXTURES.normal); - }); +describe('client.sign', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) + it('sign', async function () { + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' + const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, secret) + assert.deepEqual(result, RESPONSE_FIXTURES.normal) + }) - it("sign with lowercase hex data in memo (hex should be case insensitive)", async function () { - const secret = "shd2nxpFD6iBRKWsRss2P4tKMWyy9"; + it('sign with lowercase hex data in memo (hex should be case insensitive)', async function () { + const secret = 'shd2nxpFD6iBRKWsRss2P4tKMWyy9' const lowercaseMemoTxJson = { - TransactionType: "Payment", + TransactionType: 'Payment', Flags: 2147483648, - Account: "rwiZ3q3D3QuG4Ga2HyGdq3kPKJRGctVG8a", - Amount: "10000000", + Account: 'rwiZ3q3D3QuG4Ga2HyGdq3kPKJRGctVG8a', + Amount: '10000000', LastLedgerSequence: 14000999, - Destination: "rUeEBYXHo8vF86Rqir3zWGRQ84W9efdAQd", - Fee: "12", + Destination: 'rUeEBYXHo8vF86Rqir3zWGRQ84W9efdAQd', + Fee: '12', Sequence: 12, SourceTag: 8888, DestinationTag: 9999, @@ -36,380 +36,380 @@ describe("client.sign", function () { { Memo: { MemoType: - "687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963", - MemoData: "72656e74", + '687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963', + MemoData: '72656e74', }, }, ], - }; + } - const txParams = JSON.stringify(lowercaseMemoTxJson); - const result = this.client.sign(txParams, secret); + const txParams = JSON.stringify(lowercaseMemoTxJson) + const result = this.client.sign(txParams, secret) assert.deepEqual(result, { signedTransaction: - "120000228000000023000022B8240000000C2E0000270F201B00D5A36761400000000098968068400000000000000C73210305E09ED602D40AB1AF65646A4007C2DAC17CB6CDACDE301E74FB2D728EA057CF744730450221009C00E8439E017CA622A5A1EE7643E26B4DE9C808DE2ABE45D33479D49A4CEC66022062175BE8733442FA2A4D9A35F85A57D58252AE7B19A66401FE238B36FA28E5A081146C1856D0E36019EA75C56D7E8CBA6E35F9B3F71583147FB49CD110A1C46838788CD12764E3B0F837E0DDF9EA7C1F687474703A2F2F6578616D706C652E636F6D2F6D656D6F2F67656E657269637D0472656E74E1F1", - id: "41B9CB78D8E18A796CDD4B0BC6FB0EA19F64C4F25FDE23049197852CAB71D10D", - }); - }); + '120000228000000023000022B8240000000C2E0000270F201B00D5A36761400000000098968068400000000000000C73210305E09ED602D40AB1AF65646A4007C2DAC17CB6CDACDE301E74FB2D728EA057CF744730450221009C00E8439E017CA622A5A1EE7643E26B4DE9C808DE2ABE45D33479D49A4CEC66022062175BE8733442FA2A4D9A35F85A57D58252AE7B19A66401FE238B36FA28E5A081146C1856D0E36019EA75C56D7E8CBA6E35F9B3F71583147FB49CD110A1C46838788CD12764E3B0F837E0DDF9EA7C1F687474703A2F2F6578616D706C652E636F6D2F6D656D6F2F67656E657269637D0472656E74E1F1', + id: '41B9CB78D8E18A796CDD4B0BC6FB0EA19F64C4F25FDE23049197852CAB71D10D', + }) + }) - it("EscrowExecution", async function () { - const secret = "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"; - const result = this.client.sign(REQUEST_FIXTURES.escrow.txJSON, secret); - assert.deepEqual(result, RESPONSE_FIXTURES.escrow); - }); + it('EscrowExecution', async function () { + const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' + const result = this.client.sign(REQUEST_FIXTURES.escrow.txJSON, secret) + assert.deepEqual(result, RESPONSE_FIXTURES.escrow) + }) - it("signAs", async function () { - const txJSON = REQUEST_FIXTURES.signAs; - const secret = "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"; + it('signAs', async function () { + const txJSON = REQUEST_FIXTURES.signAs + const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' const signature = this.client.sign(JSON.stringify(txJSON), secret, { - signAs: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - }); - assert.deepEqual(signature, RESPONSE_FIXTURES.signAs); - }); + signAs: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', + }) + assert.deepEqual(signature, RESPONSE_FIXTURES.signAs) + }) - it("withKeypair", async function () { + it('withKeypair', async function () { const keypair = { privateKey: - "00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A", + '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A', publicKey: - "02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8", - }; - const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, keypair); - assert.deepEqual(result, RESPONSE_FIXTURES.normal); - }); + '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8', + } + const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, keypair) + assert.deepEqual(result, RESPONSE_FIXTURES.normal) + }) - it("withKeypair already signed", async function () { + it('withKeypair already signed', async function () { const keypair = { privateKey: - "00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A", + '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A', publicKey: - "02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8", - }; - const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, keypair); + '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8', + } + const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, keypair) assert.throws(() => { - const tx = JSON.stringify(binary.decode(result.signedTransaction)); - this.client.sign(tx, keypair); - }, /txJSON must not contain "TxnSignature" or "Signers" properties/); - }); + const tx = JSON.stringify(binary.decode(result.signedTransaction)) + this.client.sign(tx, keypair) + }, /txJSON must not contain "TxnSignature" or "Signers" properties/) + }) - it("withKeypair EscrowExecution", async function () { + it('withKeypair EscrowExecution', async function () { const keypair = { privateKey: - "001ACAAEDECE405B2A958212629E16F2EB46B153EEE94CDD350FDEFF52795525B7", + '001ACAAEDECE405B2A958212629E16F2EB46B153EEE94CDD350FDEFF52795525B7', publicKey: - "0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020", - }; - const result = this.client.sign(REQUEST_FIXTURES.escrow.txJSON, keypair); - assert.deepEqual(result, RESPONSE_FIXTURES.escrow); - }); + '0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020', + } + const result = this.client.sign(REQUEST_FIXTURES.escrow.txJSON, keypair) + assert.deepEqual(result, RESPONSE_FIXTURES.escrow) + }) - it("withKeypair signAs", async function () { - const txJSON = REQUEST_FIXTURES.signAs; + it('withKeypair signAs', async function () { + const txJSON = REQUEST_FIXTURES.signAs const keypair = { privateKey: - "001ACAAEDECE405B2A958212629E16F2EB46B153EEE94CDD350FDEFF52795525B7", + '001ACAAEDECE405B2A958212629E16F2EB46B153EEE94CDD350FDEFF52795525B7', publicKey: - "0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020", - }; + '0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020', + } const signature = this.client.sign(JSON.stringify(txJSON), keypair, { - signAs: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", - }); - assert.deepEqual(signature, RESPONSE_FIXTURES.signAs); - }); + signAs: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', + }) + assert.deepEqual(signature, RESPONSE_FIXTURES.signAs) + }) - it("already signed", async function () { - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; - const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, secret); + it('already signed', async function () { + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' + const result = this.client.sign(REQUEST_FIXTURES.normal.txJSON, secret) assert.throws(() => { - const tx = JSON.stringify(binary.decode(result.signedTransaction)); - this.client.sign(tx, secret); - }, /txJSON must not contain "TxnSignature" or "Signers" properties/); - }); + const tx = JSON.stringify(binary.decode(result.signedTransaction)) + this.client.sign(tx, secret) + }, /txJSON must not contain "TxnSignature" or "Signers" properties/) + }) - it("succeeds - no flags", async function () { + it('succeeds - no flags', async function () { const txJSON = - '{"TransactionType":"Payment","Account":"r45Rev1EXGxy2hAUmJPCne97KUE7qyrD3j","Destination":"rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r","Amount":"20000000","Sequence":1,"Fee":"12"}'; - const secret = "shotKgaEotpcYsshSE39vmSnBDRim"; - const result = this.client.sign(txJSON, secret); + '{"TransactionType":"Payment","Account":"r45Rev1EXGxy2hAUmJPCne97KUE7qyrD3j","Destination":"rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r","Amount":"20000000","Sequence":1,"Fee":"12"}' + const secret = 'shotKgaEotpcYsshSE39vmSnBDRim' + const result = this.client.sign(txJSON, secret) const expectedResult = { signedTransaction: - "1200002400000001614000000001312D0068400000000000000C7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100C104B7B97C31FACA4597E7D6FCF13BD85BD11375963A62A0AC45B0061236E39802207784F157F6A98DFC85B051CDDF61CC3084C4F5750B82674801C8E9950280D1998114EE3046A5DDF8422C40DDB93F1D522BB4FE6419158314FDB08D07AAA0EB711793A3027304D688E10C3648", - id: "0596925967F541BF332FF6756645B2576A9858414B5B363DC3D34915BE8A70D6", - }; - const decoded = binary.decode(result.signedTransaction); + '1200002400000001614000000001312D0068400000000000000C7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100C104B7B97C31FACA4597E7D6FCF13BD85BD11375963A62A0AC45B0061236E39802207784F157F6A98DFC85B051CDDF61CC3084C4F5750B82674801C8E9950280D1998114EE3046A5DDF8422C40DDB93F1D522BB4FE6419158314FDB08D07AAA0EB711793A3027304D688E10C3648', + id: '0596925967F541BF332FF6756645B2576A9858414B5B363DC3D34915BE8A70D6', + } + const decoded = binary.decode(result.signedTransaction) assert( decoded.Flags == null, - `Flags = ${decoded.Flags}, should be undefined` - ); - assert.deepEqual(result, expectedResult); - }); + `Flags = ${decoded.Flags}, should be undefined`, + ) + assert.deepEqual(result, expectedResult) + }) - it("sign succeeds with source.amount/destination.minAmount", async function () { + it('sign succeeds with source.amount/destination.minAmount', async function () { // See also: 'preparePayment with source.amount/destination.minAmount' const txJSON = - '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq","Amount":{"currency":"USD","issuer":"rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH","value":"999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000"},"Flags":2147614720,"SendMax":{"currency":"GBP","issuer":"rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro","value":"0.1"},"DeliverMin":{"currency":"USD","issuer":"rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH","value":"0.1248548562296331"},"Sequence":23,"LastLedgerSequence":8820051,"Fee":"12"}'; - const secret = "shotKgaEotpcYsshSE39vmSnBDRim"; - const result = this.client.sign(txJSON, secret); + '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rEX4LtGJubaUcMWCJULcy4NVxGT9ZEMVRq","Amount":{"currency":"USD","issuer":"rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH","value":"999999999999999900000000000000000000000000000000000000000000000000000000000000000000000000000000"},"Flags":2147614720,"SendMax":{"currency":"GBP","issuer":"rpat5TmYjDsnFSStmgTumFgXCM9eqsWPro","value":"0.1"},"DeliverMin":{"currency":"USD","issuer":"rMaa8VLBTjwTJWA2kSme4Sqgphhr6Lr6FH","value":"0.1248548562296331"},"Sequence":23,"LastLedgerSequence":8820051,"Fee":"12"}' + const secret = 'shotKgaEotpcYsshSE39vmSnBDRim' + const result = this.client.sign(txJSON, secret) const expectedResult = { signedTransaction: - "12000022800200002400000017201B0086955361EC6386F26FC0FFFF0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A68400000000000000C69D4438D7EA4C6800000000000000000000000000047425000000000000C155FFE99C8C91F67083CEFFDB69EBFE76348CA6AD4446F8C5D8A5E0B0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100D9634523D8E232D4A7807A71856023D82AC928FA29848571B820867898413B5F022041AC00EC1F81A26A6504EBF844A38CC3204694EF2CC1A97A87632721631F93DA81145E7B112523F68D2F5E879DB4EAC51C6698A6930483149F500E50C2F016CA01945E5A1E5846B61EF2D376", - id: "1C558AA9B926C24FB6BBD6950B2DB1350A83F9F12E4385208867907019761A2D", - }; - const decoded = binary.decode(result.signedTransaction); + '12000022800200002400000017201B0086955361EC6386F26FC0FFFF0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A68400000000000000C69D4438D7EA4C6800000000000000000000000000047425000000000000C155FFE99C8C91F67083CEFFDB69EBFE76348CA6AD4446F8C5D8A5E0B0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100D9634523D8E232D4A7807A71856023D82AC928FA29848571B820867898413B5F022041AC00EC1F81A26A6504EBF844A38CC3204694EF2CC1A97A87632721631F93DA81145E7B112523F68D2F5E879DB4EAC51C6698A6930483149F500E50C2F016CA01945E5A1E5846B61EF2D376', + id: '1C558AA9B926C24FB6BBD6950B2DB1350A83F9F12E4385208867907019761A2D', + } + const decoded = binary.decode(result.signedTransaction) assert( decoded.Flags === 2147614720, - `Flags = ${decoded.Flags}, should be 2147614720` - ); - assert.deepEqual(result, expectedResult); - }); + `Flags = ${decoded.Flags}, should be 2147614720`, + ) + assert.deepEqual(result, expectedResult) + }) - it("throws when encoded tx does not match decoded tx - AccountSet", async function () { - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + it('throws when encoded tx does not match decoded tx - AccountSet', async function () { + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { // TODO: This fails when address is X-address txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"1.2","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, instructions: { - fee: "0.0000012", + fee: '0.0000012', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } assert.throws(() => { - this.client.sign(request.txJSON, secret); - }, /1\.2 is an illegal amount/); - }); + this.client.sign(request.txJSON, secret) + }, /1\.2 is an illegal amount/) + }) - it("throws when encoded tx does not match decoded tx - higher fee", async function () { - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + it('throws when encoded tx does not match decoded tx - higher fee', async function () { + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { // TODO: This fails when address is X-address txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"1123456.7","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, instructions: { - fee: "1.1234567", + fee: '1.1234567', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } assert.throws(() => { - this.client.sign(request.txJSON, secret); - }, /1123456\.7 is an illegal amount/); - }); + this.client.sign(request.txJSON, secret) + }, /1123456\.7 is an illegal amount/) + }) - it("permits fee exceeding 2000000 drops when maxFeeXRP is higher than 2 XRP", async function () { - this.client.maxFeeXRP = "2.1"; - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + it('permits fee exceeding 2000000 drops when maxFeeXRP is higher than 2 XRP', async function () { + this.client.maxFeeXRP = '2.1' + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { // TODO: This fails when address is X-address txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","LastLedgerSequence":8820051,"Fee":"2010000","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, instructions: { - fee: "2.01", + fee: '2.01', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } - const result = this.client.sign(request.txJSON, secret); + const result = this.client.sign(request.txJSON, secret) const expectedResponse = { signedTransaction: - "12000322800000002400000017201B008695536840000000001EAB90732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402200203F219F5371D2C6506888B1B02B27E74998F7A42D412C32FE319AC1A5B8DEF02205959A1B02253ACCCE542759E9886466C56D16B04676FA492AD34AA0E877E91F381145E7B112523F68D2F5E879DB4EAC51C6698A69304", - id: "061D5593E0A117F389826419CAC049A73C7CFCA65A20B788781D41240143D864", - }; + '12000322800000002400000017201B008695536840000000001EAB90732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402200203F219F5371D2C6506888B1B02B27E74998F7A42D412C32FE319AC1A5B8DEF02205959A1B02253ACCCE542759E9886466C56D16B04676FA492AD34AA0E877E91F381145E7B112523F68D2F5E879DB4EAC51C6698A69304', + id: '061D5593E0A117F389826419CAC049A73C7CFCA65A20B788781D41240143D864', + } - assert.deepEqual(result, expectedResponse); - }); + assert.deepEqual(result, expectedResponse) + }) - it("sign with ticket", async function () { - const secret = "sn7n5R1cR5Y3fRFkuWXA94Ts1frVJ"; - const result = this.client.sign(REQUEST_FIXTURES.ticket.txJSON, secret); - assert.deepEqual(result, RESPONSE_FIXTURES.ticket); - }); + it('sign with ticket', async function () { + const secret = 'sn7n5R1cR5Y3fRFkuWXA94Ts1frVJ' + const result = this.client.sign(REQUEST_FIXTURES.ticket.txJSON, secret) + assert.deepEqual(result, RESPONSE_FIXTURES.ticket) + }) addressTests.forEach(function (test) { describe(test.type, function () { - it("throws when Fee exceeds maxFeeXRP (in drops)", async function () { - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + it('throws when Fee exceeds maxFeeXRP (in drops)', async function () { + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"${test.address}","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"2010000","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, instructions: { - fee: "2.01", + fee: '2.01', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } assert.throws(() => { - this.client.sign(request.txJSON, secret); - }, /Fee" should not exceed "2000000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./); - }); + this.client.sign(request.txJSON, secret) + }, /Fee" should not exceed "2000000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./) + }) - it("throws when Fee exceeds maxFeeXRP (in drops) - custom maxFeeXRP", async function () { - this.client.maxFeeXRP = "1.9"; - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + it('throws when Fee exceeds maxFeeXRP (in drops) - custom maxFeeXRP', async function () { + this.client.maxFeeXRP = '1.9' + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"${test.address}","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"2010000","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, instructions: { - fee: "2.01", + fee: '2.01', sequence: 23, maxLedgerVersion: 8820051, }, - }; + } assert.throws(() => { - this.client.sign(request.txJSON, secret); - }, /Fee" should not exceed "1900000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./); - }); + this.client.sign(request.txJSON, secret) + }, /Fee" should not exceed "1900000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./) + }) - it("sign with paths", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('sign with paths', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + 'account_info', + rippled.account_info.normal, + ) + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const payment = { source: { address: test.address, amount: { - currency: "drops", - value: "100", + currency: 'drops', + value: '100', }, }, destination: { - address: "rKT4JX4cCof6LcDYRz8o3rGRu7qxzZ2Zwj", + address: 'rKT4JX4cCof6LcDYRz8o3rGRu7qxzZ2Zwj', minAmount: { - currency: "USD", - value: "0.00004579644712312366", - counterparty: "rVnYNK9yuxBz4uP8zC8LEFokM2nqH3poc", + currency: 'USD', + value: '0.00004579644712312366', + counterparty: 'rVnYNK9yuxBz4uP8zC8LEFokM2nqH3poc', }, }, // eslint-disable-next-line no-useless-escape paths: '[[{"currency":"USD","issuer":"rVnYNK9yuxBz4uP8zC8LEFokM2nqH3poc"}]]', - }; + } const ret = await this.client.preparePayment(test.address, payment, { sequence: 1, maxLedgerVersion: 15696358, - }); - const result = this.client.sign(ret.txJSON, secret); + }) + const result = this.client.sign(ret.txJSON, secret) assert.deepEqual(result, { signedTransaction: - "12000022800200002400000001201B00EF81E661EC6386F26FC0FFFF0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461968400000000000000C6940000000000000646AD3504529A0465E2E0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D1664619732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402200A693FB5CA6B21250EBDFD8CFF526EE0DF7C9E4E31EB0660692E75E6A93BF5F802203CC39463DDA21386898CA31E18AD1A6828647D65741DD637BAD71BC83E29DB9481145E7B112523F68D2F5E879DB4EAC51C6698A693048314CA6EDC7A28252DAEA6F2045B24F4D7C333E146170112300000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461900", - id: "78874FE5F5299FEE3EA85D3CF6C1FB1F1D46BB08F716662A3E3D1F0ADE4EF796", - }); - }); + '12000022800200002400000001201B00EF81E661EC6386F26FC0FFFF0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461968400000000000000C6940000000000000646AD3504529A0465E2E0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D1664619732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402200A693FB5CA6B21250EBDFD8CFF526EE0DF7C9E4E31EB0660692E75E6A93BF5F802203CC39463DDA21386898CA31E18AD1A6828647D65741DD637BAD71BC83E29DB9481145E7B112523F68D2F5E879DB4EAC51C6698A693048314CA6EDC7A28252DAEA6F2045B24F4D7C333E146170112300000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461900', + id: '78874FE5F5299FEE3EA85D3CF6C1FB1F1D46BB08F716662A3E3D1F0ADE4EF796', + }) + }) - it("succeeds - prepared payment", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('succeeds - prepared payment', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = await this.client.preparePayment(test.address, { source: { address: test.address, maxAmount: { - value: "1", - currency: "drops", + value: '1', + currency: 'drops', }, }, destination: { - address: "rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r", + address: 'rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r', amount: { - value: "1", - currency: "drops", + value: '1', + currency: 'drops', }, }, - }); - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; - const result = this.client.sign(payment.txJSON, secret); + }) + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' + const result = this.client.sign(payment.txJSON, secret) const expectedResult = { signedTransaction: - "12000022800000002400000017201B008694F261400000000000000168400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100A9C91D4CFAE45686146EE0B56D4C53A2E7C2D672FB834D43E0BE2D2E9106519A022075DDA2F92DE552B0C45D83D4E6D35889B3FBF51BFBBD9B25EBF70DE3C96D0D6681145E7B112523F68D2F5E879DB4EAC51C6698A693048314FDB08D07AAA0EB711793A3027304D688E10C3648", - id: "88D6B913C66279EA31ADC25C5806C48B2D4E5680261666790A736E1961217700", - }; - assert.deepEqual(result, expectedResult); - }); + '12000022800000002400000017201B008694F261400000000000000168400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100A9C91D4CFAE45686146EE0B56D4C53A2E7C2D672FB834D43E0BE2D2E9106519A022075DDA2F92DE552B0C45D83D4E6D35889B3FBF51BFBBD9B25EBF70DE3C96D0D6681145E7B112523F68D2F5E879DB4EAC51C6698A693048314FDB08D07AAA0EB711793A3027304D688E10C3648', + id: '88D6B913C66279EA31ADC25C5806C48B2D4E5680261666790A736E1961217700', + } + assert.deepEqual(result, expectedResult) + }) - it("throws when encoded tx does not match decoded tx - prepared payment", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('throws when encoded tx does not match decoded tx - prepared payment', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const payment = await this.client.preparePayment(test.address, { source: { address: test.address, maxAmount: { - value: "1.1234567", - currency: "drops", + value: '1.1234567', + currency: 'drops', }, }, destination: { - address: "rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r", + address: 'rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r', amount: { - value: "1.1234567", - currency: "drops", + value: '1.1234567', + currency: 'drops', }, }, - }); - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + }) + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' assert.throws(() => { - this.client.sign(payment.txJSON, secret); - }, /^1.1234567 is an illegal amount/); - }); + this.client.sign(payment.txJSON, secret) + }, /^1.1234567 is an illegal amount/) + }) - it("throws when encoded tx does not match decoded tx - prepared order", async function () { - this.mockRippled.addResponse("server_info", rippled.server_info.normal); - this.mockRippled.addResponse("fee", rippled.fee); - this.mockRippled.addResponse("ledger_current", rippled.ledger_current); + it('throws when encoded tx does not match decoded tx - prepared order', async function () { + this.mockRippled.addResponse('server_info', rippled.server_info.normal) + this.mockRippled.addResponse('fee', rippled.fee) + this.mockRippled.addResponse('ledger_current', rippled.ledger_current) this.mockRippled.addResponse( - "account_info", - rippled.account_info.normal - ); + 'account_info', + rippled.account_info.normal, + ) const order = { - direction: "sell", + direction: 'sell', quantity: { - currency: "USD", - counterparty: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B", - value: "3.140000", + currency: 'USD', + counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', + value: '3.140000', }, totalPrice: { - currency: "XRP", - value: "31415", + currency: 'XRP', + value: '31415', }, - }; + } const prepared = await this.client.prepareOrder(test.address, order, { sequence: 123, - }); - const secret = "shsWGZcmZz6YsWWmcnpfr6fLTdtFV"; + }) + const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' try { - this.client.sign(prepared.txJSON, secret); + this.client.sign(prepared.txJSON, secret) return await Promise.reject( - new Error("this.client.sign should have thrown") - ); + new Error('this.client.sign should have thrown'), + ) } catch (error) { - assert.equal(error.name, "ValidationError"); + assert.equal(error.name, 'ValidationError') assert.equal( error.message, - "Serialized transaction does not match original txJSON. See `error.data`" - ); + 'Serialized transaction does not match original txJSON. See `error.data`', + ) assert.deepEqual(error.data.diff, { TakerGets: { - value: "3.14", + value: '3.14', }, - }); + }) } - }); - }); - }); -}); + }) + }) + }) +}) diff --git a/test/connection.ts b/test/connection.ts index 70b4d81e..b2512dc1 100644 --- a/test/connection.ts +++ b/test/connection.ts @@ -1,10 +1,10 @@ -import net from "net"; +import net from 'net' -import { assert } from "chai"; -import _ from "lodash"; +import { assert } from 'chai' +import _ from 'lodash' -import { Client } from "xrpl-local"; -import { Connection } from "xrpl-local/client"; +import { Client } from 'xrpl-local' +import { Connection } from 'xrpl-local/client' import { ConnectionError, @@ -13,521 +13,518 @@ import { ResponseFormatError, RippleError, TimeoutError, -} from "../src/common/errors"; +} from '../src/common/errors' -import rippled from "./fixtures/rippled"; -import setupClient from "./setupClient"; -import { ignoreWebSocketDisconnect } from "./testUtils"; +import rippled from './fixtures/rippled' +import setupClient from './setupClient' +import { ignoreWebSocketDisconnect } from './testUtils' -const TIMEOUT = 200000; // how long before each test case times out -const isBrowser = (process as any).browser; +const TIMEOUT = 200000 // how long before each test case times out +const isBrowser = (process as any).browser -function createServer() { +async function createServer() { return new Promise((resolve, reject) => { - const server = net.createServer(); - server.on("listening", function () { - resolve(server); - }); - server.on("error", function (error) { - reject(error); - }); - server.listen(0, "0.0.0.0"); - }); + const server = net.createServer() + server.on('listening', function () { + resolve(server) + }) + server.on('error', function (error) { + reject(error) + }) + server.listen(0, '0.0.0.0') + }) } -describe("Connection", function () { - this.timeout(TIMEOUT); - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('Connection', function () { + this.timeout(TIMEOUT) + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("default options", function () { - const connection: any = new Connection("url"); - assert.strictEqual(connection.url, "url"); - assert(connection.config.proxy == null); - assert(connection.config.authorization == null); - }); + it('default options', function () { + const connection: any = new Connection('url') + assert.strictEqual(connection.url, 'url') + assert(connection.config.proxy == null) + assert(connection.config.authorization == null) + }) - describe("trace", function () { - const mockedRequestData = { mocked: "request" }; - const mockedResponse = JSON.stringify({ mocked: "response", id: 0 }); + describe('trace', function () { + const mockedRequestData = { mocked: 'request' } + const mockedResponse = JSON.stringify({ mocked: 'response', id: 0 }) const expectedMessages = [ // We add the ID here, since it's not a part of the user-provided request. - ["send", JSON.stringify({ ...mockedRequestData, id: 0 })], - ["receive", mockedResponse], - ]; - const originalConsoleLog = console.log; + ['send', JSON.stringify({ ...mockedRequestData, id: 0 })], + ['receive', mockedResponse], + ] + const originalConsoleLog = console.log afterEach(function () { - console.log = originalConsoleLog; - }); + console.log = originalConsoleLog + }) - it("as false", function () { - const messages: any[] = []; - console.log = (id, message) => messages.push([id, message]); - const connection: any = new Connection("url", { trace: false }); - connection.ws = { send() {} }; - connection.request(mockedRequestData); - connection.onMessage(mockedResponse); - assert.deepEqual(messages, []); - }); + it('as false', function () { + const messages: any[] = [] + console.log = (id, message) => messages.push([id, message]) + const connection: any = new Connection('url', { trace: false }) + connection.ws = { send() {} } + connection.request(mockedRequestData) + connection.onMessage(mockedResponse) + assert.deepEqual(messages, []) + }) - it("as true", function () { - const messages: any[] = []; - console.log = (id, message) => messages.push([id, message]); - const connection: any = new Connection("url", { trace: true }); - connection.ws = { send() {} }; - connection.request(mockedRequestData); - connection.onMessage(mockedResponse); - assert.deepEqual(messages, expectedMessages); - }); + it('as true', function () { + const messages: any[] = [] + console.log = (id, message) => messages.push([id, message]) + const connection: any = new Connection('url', { trace: true }) + connection.ws = { send() {} } + connection.request(mockedRequestData) + connection.onMessage(mockedResponse) + assert.deepEqual(messages, expectedMessages) + }) - it("as a function", function () { - const messages: any[] = []; - const connection: any = new Connection("url", { + it('as a function', function () { + const messages: any[] = [] + const connection: any = new Connection('url', { trace: (id, message) => messages.push([id, message]), - }); - connection.ws = { send() {} }; - connection.request(mockedRequestData); - connection.onMessage(mockedResponse); - assert.deepEqual(messages, expectedMessages); - }); - }); + }) + connection.ws = { send() {} } + connection.request(mockedRequestData) + connection.onMessage(mockedResponse) + assert.deepEqual(messages, expectedMessages) + }) + }) - it("with proxy", function (done) { + it('with proxy', function (done) { if (isBrowser) { - done(); - return; + done() + return } createServer().then((server: any) => { - const port = server.address().port; - const expect = "CONNECT localhost"; - server.on("connection", (socket) => { - socket.on("data", (data) => { - const got = data.toString("ascii", 0, expect.length); - assert.strictEqual(got, expect); - server.close(); - connection.disconnect(); - done(); - }); - }); + const port = server.address().port + const expect = 'CONNECT localhost' + server.on('connection', (socket) => { + socket.on('data', (data) => { + const got = data.toString('ascii', 0, expect.length) + assert.strictEqual(got, expect) + server.close() + connection.disconnect() + done() + }) + }) const options = { proxy: `ws://localhost:${port}`, - authorization: "authorization", - trustedCertificates: ["path/to/pem"], - }; - const connection = new Connection(this.client.connection.url, options); + authorization: 'authorization', + trustedCertificates: ['path/to/pem'], + } + const connection = new Connection(this.client.connection.url, options) connection.connect().catch((err) => { - assert(err instanceof NotConnectedError); - }); - }, done); - }); + assert(err instanceof NotConnectedError) + }) + }, done) + }) - it("Multiply disconnect calls", function () { - this.client.disconnect(); - return this.client.disconnect(); - }); + it('Multiply disconnect calls', function () { + this.client.disconnect() + return this.client.disconnect() + }) - it("reconnect", function () { - return this.client.connection.reconnect(); - }); + it('reconnect', function () { + return this.client.connection.reconnect() + }) - it("NotConnectedError", function () { - const connection = new Connection("url"); + it('NotConnectedError', async function () { + const connection = new Connection('url') return connection .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) .then(() => { - assert.fail("Should throw NotConnectedError"); + assert.fail('Should throw NotConnectedError') }) .catch((error) => { - assert(error instanceof NotConnectedError); - }); - }); + assert(error instanceof NotConnectedError) + }) + }) - it("should throw NotConnectedError if server not responding ", function (done) { + it('should throw NotConnectedError if server not responding ', function (done) { if (isBrowser) { - if (navigator.userAgent.includes("PhantomJS")) { + if (navigator.userAgent.includes('PhantomJS')) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } // Address where no one listens - const connection = new Connection("ws://testripple.circleci.com:129"); - connection.on("error", done); + const connection = new Connection('ws://testripple.circleci.com:129') + connection.on('error', done) connection.connect().catch((error) => { - assert(error instanceof NotConnectedError); - done(); - }); - }); + assert(error instanceof NotConnectedError) + done() + }) + }) - it("DisconnectedError", async function () { + it('DisconnectedError', async function () { return this.client - .request({ command: "test_command", data: { closeServer: true } }) + .request({ command: 'test_command', data: { closeServer: true } }) .then(() => { - assert.fail("Should throw DisconnectedError"); + assert.fail('Should throw DisconnectedError') }) .catch((error) => { - assert(error instanceof DisconnectedError); - }); - }); + assert(error instanceof DisconnectedError) + }) + }) - it("TimeoutError", function () { + it('TimeoutError', function () { this.client.connection.ws.send = function (_, callback) { - callback(null); - }; - const request = { command: "server_info" }; + callback(null) + } + const request = { command: 'server_info' } return this.client.connection .request(request, 10) .then(() => { - assert.fail("Should throw TimeoutError"); + assert.fail('Should throw TimeoutError') }) .catch((error) => { - assert(error instanceof TimeoutError); - }); - }); + assert(error instanceof TimeoutError) + }) + }) - it("DisconnectedError on send", function () { + it('DisconnectedError on send', function () { this.client.connection.ws.send = function (_, callback) { - callback({ message: "not connected" }); - }; + callback({ message: 'not connected' }) + } return this.client - .request({ command: "server_info" }) + .request({ command: 'server_info' }) .then(() => { - assert.fail("Should throw DisconnectedError"); + assert.fail('Should throw DisconnectedError') }) .catch((error) => { - assert(error instanceof DisconnectedError); - assert.strictEqual(error.message, "not connected"); - }); - }); + assert(error instanceof 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 client.setup hook to test this as it bypasses the case, disconnect client connection first - await this.client.disconnect(); + await this.client.disconnect() // stub _onOpen to only run logic relevant to test case this.client.connection.onOpen = () => { // overload websocket send on open when _ws exists this.client.connection.ws.send = function (_0, _1, _2) { // recent ws throws this error instead of calling back - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - }; - const request = { command: "subscribe", streams: ["ledger"] }; - return this.client.connection.request(request); - }; + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)') + } + const request = { command: 'subscribe', streams: ['ledger'] } + return this.client.connection.request(request) + } try { - await this.client.connect(); + await this.client.connect() } catch (error) { - console.log(error); - assert.instanceOf(error, DisconnectedError); + console.log(error) + assert.instanceOf(error, DisconnectedError) assert.strictEqual( error.message, - "WebSocket is not open: readyState 0 (CONNECTING)" - ); + 'WebSocket is not open: readyState 0 (CONNECTING)', + ) } - }); + }) - it("ResponseFormatError", function () { + it('ResponseFormatError', function () { return this.client .request({ - command: "test_command", + command: 'test_command', data: { unrecognizedResponse: true }, }) .then(() => { - assert.fail("Should throw ResponseFormatError"); + assert.fail('Should throw ResponseFormatError') }) .catch((error) => { - assert(error instanceof ResponseFormatError); - }); - }); + assert(error instanceof ResponseFormatError) + }) + }) - it("reconnect on unexpected close", function (done) { - this.client.connection.on("connected", () => { - done(); - }); + it('reconnect on unexpected close', function (done) { + this.client.connection.on('connected', () => { + done() + }) setTimeout(() => { - this.client.connection.ws.close(); - }, 1); - }); + this.client.connection.ws.close() + }, 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) { - if (navigator.userAgent.includes("PhantomJS")) { + if (navigator.userAgent.includes('PhantomJS')) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } - this.timeout(70001); - const self = this; + this.timeout(70001) + const self = this function breakConnection() { self.client.connection .request({ - command: "test_command", + command: 'test_command', data: { disconnectIn: 10 }, }) - .catch(ignoreWebSocketDisconnect); + .catch(ignoreWebSocketDisconnect) } - let connectsCount = 0; - let disconnectsCount = 0; - let reconnectsCount = 0; - let code = 0; - this.client.connection.on("reconnecting", () => { - reconnectsCount += 1; - }); - this.client.connection.on("disconnected", (_code) => { - code = _code; - disconnectsCount += 1; - }); - const num = 3; - this.client.connection.on("connected", () => { - connectsCount += 1; + let connectsCount = 0 + let disconnectsCount = 0 + let reconnectsCount = 0 + let code = 0 + this.client.connection.on('reconnecting', () => { + reconnectsCount += 1 + }) + this.client.connection.on('disconnected', (_code) => { + code = _code + disconnectsCount += 1 + }) + const num = 3 + this.client.connection.on('connected', () => { + connectsCount += 1 if (connectsCount < num) { - breakConnection(); + breakConnection() } if (connectsCount === num) { if (disconnectsCount !== num) { done( new Error( - `disconnectsCount must be equal to ${num}(got ${disconnectsCount} instead)` - ) - ); + `disconnectsCount must be equal to ${num}(got ${disconnectsCount} instead)`, + ), + ) } else if (reconnectsCount !== num) { done( new Error( - `reconnectsCount must be equal to ${num} (got ${reconnectsCount} instead)` - ) - ); + `reconnectsCount must be equal to ${num} (got ${reconnectsCount} instead)`, + ), + ) } else if (code !== 1006) { done( - new Error(`disconnect must send code 1006 (got ${code} instead)`) - ); + new Error(`disconnect must send code 1006 (got ${code} instead)`), + ) } else { - done(); + done() } } - }); + }) - breakConnection(); - }); - }); + breakConnection() + }) + }) - it("reconnect event on heartbeat failure", function (done) { + it('reconnect event on heartbeat failure', function (done) { if (isBrowser) { - if (navigator.userAgent.includes("PhantomJS")) { + if (navigator.userAgent.includes('PhantomJS')) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } // Set the heartbeat to less than the 1 second ping response - this.client.connection.config.timeout = 500; + this.client.connection.config.timeout = 500 // Drop the test runner timeout, since this should be a quick test - this.timeout(5000); + this.timeout(5000) // Hook up a listener for the reconnect event - this.client.connection.on("reconnect", () => done()); + this.client.connection.on('reconnect', () => done()) // Trigger a heartbeat this.client.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) { - if (navigator.userAgent.includes("PhantomJS")) { + if (navigator.userAgent.includes('PhantomJS')) { // inside PhantomJS this one just hangs, so skip as not very relevant - done(); - return; + done() + return } } // Set the heartbeat to less than the 1 second ping response - this.client.connection.config.timeout = 500; + this.client.connection.config.timeout = 500 // Drop the test runner timeout, since this should be a quick test - this.timeout(5000); + this.timeout(5000) // fail on reconnect/connection this.client.connection.reconnect = async () => { - throw new Error("error on reconnect"); - }; + throw new Error('error on reconnect') + } // Hook up a listener for the reconnect error event - this.client.on("error", (error, message) => { - if (error === "reconnect" && message === "error on reconnect") { - return done(); + this.client.on('error', (error, message) => { + if (error === 'reconnect' && message === 'error on reconnect') { + return done() } - return done(new Error("Expected error on reconnect")); - }); + return done(new Error('Expected error on reconnect')) + }) // Trigger a heartbeat - this.client.connection.heartbeat(); - }); + this.client.connection.heartbeat() + }) - it("should emit disconnected event with code 1000 (CLOSE_NORMAL)", function (done) { - this.client.once("disconnected", (code) => { - assert.strictEqual(code, 1000); - done(); - }); - this.client.disconnect(); - }); + it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) { + this.client.once('disconnected', (code) => { + assert.strictEqual(code, 1000) + done() + }) + this.client.disconnect() + }) - it("should emit disconnected event with code 1006 (CLOSE_ABNORMAL)", function (done) { - this.client.connection.once("error", (error) => { - done(new Error(`should not throw error, got ${String(error)}`)); - }); - this.client.connection.once("disconnected", (code) => { - assert.strictEqual(code, 1006); - done(); - }); + it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) { + this.client.connection.once('error', (error) => { + done(new Error(`should not throw error, got ${String(error)}`)) + }) + this.client.connection.once('disconnected', (code) => { + assert.strictEqual(code, 1006) + done() + }) this.client.connection .request({ - command: "test_command", + command: 'test_command', data: { disconnectIn: 10 }, }) - .catch(ignoreWebSocketDisconnect); - }); + .catch(ignoreWebSocketDisconnect) + }) - it("should emit connected event on after reconnect", function (done) { - this.client.once("connected", done); - this.client.connection.ws.close(); - }); + it('should emit connected event on after reconnect', function (done) { + this.client.once('connected', done) + this.client.connection.ws.close() + }) - it("Multiply connect calls", function () { + it('Multiply connect calls', function () { return this.client.connect().then(() => { - return this.client.connect(); - }); - }); + return this.client.connect() + }) + }) - it("Cannot connect because no server", function () { - const connection = new Connection(undefined as unknown as string); + it('Cannot connect because no server', async function () { + const connection = new Connection(undefined as unknown as string) return connection .connect() .then(() => { - assert.fail("Should throw ConnectionError"); + assert.fail('Should throw ConnectionError') }) .catch((error) => { - assert( - error instanceof ConnectionError, - "Should throw ConnectionError" - ); - }); - }); + assert(error instanceof ConnectionError, 'Should throw ConnectionError') + }) + }) - it("connect multiserver error", function () { + it('connect multiserver error', function () { assert.throws(function () { new Client({ - servers: ["wss://server1.com", "wss://server2.com"], - } as any); - }, RippleError); - }); + servers: ['wss://server1.com', 'wss://server2.com'], + } as any) + }, RippleError) + }) - it("connect throws error", function (done) { - this.client.once("error", (type, info) => { - assert.strictEqual(type, "type"); - assert.strictEqual(info, "info"); - done(); - }); - this.client.connection.emit("error", "type", "info"); - }); + it('connect throws error', function (done) { + this.client.once('error', (type, info) => { + assert.strictEqual(type, 'type') + assert.strictEqual(info, 'info') + done() + }) + this.client.connection.emit('error', 'type', 'info') + }) - it("emit stream messages", function (done) { - let transactionCount = 0; - let pathFindCount = 0; - this.client.connection.on("transaction", () => { - transactionCount++; - }); - this.client.connection.on("path_find", () => { - pathFindCount++; - }); - this.client.connection.on("response", (message) => { - assert.strictEqual(message.id, 1); - assert.strictEqual(transactionCount, 1); - assert.strictEqual(pathFindCount, 1); - done(); - }); + it('emit stream messages', function (done) { + let transactionCount = 0 + let pathFindCount = 0 + this.client.connection.on('transaction', () => { + transactionCount++ + }) + this.client.connection.on('path_find', () => { + pathFindCount++ + }) + this.client.connection.on('response', (message) => { + assert.strictEqual(message.id, 1) + assert.strictEqual(transactionCount, 1) + assert.strictEqual(pathFindCount, 1) + done() + }) this.client.connection.onMessage( JSON.stringify({ - type: "transaction", - }) - ); + type: 'transaction', + }), + ) this.client.connection.onMessage( JSON.stringify({ - type: "path_find", - }) - ); + type: 'path_find', + }), + ) this.client.connection.onMessage( JSON.stringify({ - type: "response", + type: 'response', id: 1, - }) - ); - }); + }), + ) + }) - it("invalid message id", function (done) { - this.client.on("error", (errorCode, errorMessage, message) => { - assert.strictEqual(errorCode, "badMessage"); - assert.strictEqual(errorMessage, "valid id not found in response"); - assert.strictEqual(message, '{"type":"response","id":"must be integer"}'); - done(); - }); + it('invalid message id', function (done) { + this.client.on('error', (errorCode, errorMessage, message) => { + assert.strictEqual(errorCode, 'badMessage') + assert.strictEqual(errorMessage, 'valid id not found in response') + assert.strictEqual(message, '{"type":"response","id":"must be integer"}') + done() + }) this.client.connection.onMessage( JSON.stringify({ - type: "response", - id: "must be integer", - }) - ); - }); + type: 'response', + id: 'must be integer', + }), + ) + }) - it("propagates error message", function (done) { - this.client.on("error", (errorCode, errorMessage, data) => { - assert.strictEqual(errorCode, "slowDown"); - assert.strictEqual(errorMessage, "slow down"); - assert.deepEqual(data, { error: "slowDown", error_message: "slow down" }); - done(); - }); + it('propagates error message', function (done) { + this.client.on('error', (errorCode, errorMessage, data) => { + assert.strictEqual(errorCode, 'slowDown') + assert.strictEqual(errorMessage, 'slow down') + assert.deepEqual(data, { error: 'slowDown', error_message: 'slow down' }) + done() + }) this.client.connection.onMessage( JSON.stringify({ - error: "slowDown", - error_message: "slow down", - }) - ); - }); + error: 'slowDown', + error_message: 'slow down', + }), + ) + }) - it("propagates RippledError data", function (done) { - const request = { command: "subscribe", streams: "validations" }; - this.mockRippled.addResponse(request.command, rippled.subscribe.error); + it('propagates RippledError data', function (done) { + const request = { command: 'subscribe', streams: 'validations' } + this.mockRippled.addResponse(request.command, rippled.subscribe.error) this.client.request(request).catch((error) => { - assert.strictEqual(error.name, "RippledError"); - assert.strictEqual(error.data.error, "invalidParams"); - assert.strictEqual(error.message, "Invalid parameters."); - assert.strictEqual(error.data.error_code, 31); - assert.strictEqual(error.data.error_message, "Invalid parameters."); + assert.strictEqual(error.name, 'RippledError') + assert.strictEqual(error.data.error, 'invalidParams') + assert.strictEqual(error.message, 'Invalid parameters.') + assert.strictEqual(error.data.error_code, 31) + assert.strictEqual(error.data.error_message, 'Invalid parameters.') assert.deepEqual(error.data.request, { - command: "subscribe", + command: 'subscribe', id: 0, - streams: "validations", - }); - done(); - }); - }); + streams: 'validations', + }) + done() + }) + }) - 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.client.connection.on("unknown", (event) => { - assert.deepEqual(event, { type: "unknown" }); - done(); - }); + this.client.connection.on('unknown', (event) => { + assert.deepEqual(event, { type: 'unknown' }) + done() + }) - this.client.connection.onMessage(JSON.stringify({ type: "unknown" })); - }); + this.client.connection.onMessage(JSON.stringify({ type: 'unknown' })) + }) // it('should clean up websocket connection if error after websocket is opened', async function () { // await this.client.disconnect() @@ -547,35 +544,35 @@ describe("Connection", function () { // } // }) - it("should try to reconnect on empty subscribe response on reconnect", function (done) { - this.timeout(23000); - this.client.on("error", (error) => { - done(error || new Error("Should not emit error.")); - }); - let disconnectedCount = 0; - this.client.on("connected", () => { + it('should try to reconnect on empty subscribe response on reconnect', function (done) { + this.timeout(23000) + this.client.on('error', (error) => { + done(error || new Error('Should not emit error.')) + }) + let disconnectedCount = 0 + this.client.on('connected', () => { done( disconnectedCount !== 1 - ? new Error("Wrong number of disconnects") - : undefined - ); - }); - this.client.on("disconnected", () => { - disconnectedCount++; - }); + ? new Error('Wrong number of disconnects') + : undefined, + ) + }) + this.client.on('disconnected', () => { + disconnectedCount++ + }) this.client.connection.request({ - command: "test_command", + command: 'test_command', data: { disconnectIn: 5 }, - }); - }); + }) + }) - it("should not crash on error", async function (done) { - this.mockRippled.suppressOutput = true; + it('should not crash on error', async function (done) { + this.mockRippled.suppressOutput = true this.client.connection .request({ - command: "test_garbage", + command: 'test_garbage', }) - .then(() => new Error("Should not have succeeded")) - .catch(done()); - }); -}); + .then(() => new Error('Should not have succeeded')) + .catch(done()) + }) +}) diff --git a/test/fixtures/requests/index.ts b/test/fixtures/requests/index.ts index b82a7bcc..9b7a55bf 100644 --- a/test/fixtures/requests/index.ts +++ b/test/fixtures/requests/index.ts @@ -1,78 +1,78 @@ import setDomain from './combine.json' -import transactions from './computeLedgerHashTransactions.json' import header from './computeLedgerHash.json' -import withXRPOrderBook from './getOrderbookWithXrp.json' +import transactions from './computeLedgerHashTransactions.json' import normalOrderBook from './getOrderbook.json' +import withXRPOrderBook from './getOrderbookWithXrp.json' import invalid from './getpaths/invalid.json' import issuer from './getpaths/issuer.json' +import NoPaths from './getpaths/noPaths.json' import NoPathsSource from './getpaths/noPathsSourceAmount.json' import NoPathsWithCurrencies from './getpaths/noPathsWithCurrencies.json' -import NoPaths from './getpaths/noPaths.json' import normalPaths from './getpaths/normal.json' import NotAcceptCurrency from './getpaths/notAcceptCurrency.json' import sendAll from './getpaths/sendAll.json' import UsdToUsd from './getpaths/usd2usd.json' -import XrpToXrpNotEnough from './getpaths/xrp2xrpNotEnough.json' import XrpToXrp from './getpaths/xrp2xrp.json' +import XrpToXrpNotEnough from './getpaths/xrp2xrpNotEnough.json' import normalCheckCancel from './prepareCheckCancel.json' import amountCheckCash from './prepareCheckCashAmount.json' import deliverMinCheckCash from './prepareCheckCashDelivermin.json' -import fullCheckCreate from './prepareCheckCreateFull.json' import normalCheckCreate from './prepareCheckCreate.json' -import memosEscrowCancel from './prepareEscrowCancellationMemos.json' +import fullCheckCreate from './prepareCheckCreateFull.json' import normalEscrowCancel from './prepareEscrowCancellation.json' -import fullEscrowCreate from './prepareEscrowCreationFull.json' +import memosEscrowCancel from './prepareEscrowCancellationMemos.json' import normalEscrowCreate from './prepareEscrowCreation.json' +import fullEscrowCreate from './prepareEscrowCreationFull.json' +import normalEscrowExec from './prepareEscrowExecution.json' import noConditionEscrowExec from './prepareEscrowExecutionNoCondition.json' import noFulfillmentEscrowExec from './prepareEscrowExecutionNoFulfillment.json' import simpleEscrowExec from './prepareEscrowExecutionSimple.json' -import normalEscrowExec from './prepareEscrowExecution.json' -import withMemosCancel from './prepareOrderCancellationMemos.json' +import buyOrder from './prepareOrder.json' import simpleCancel from './prepareOrderCancellation.json' +import withMemosCancel from './prepareOrderCancellationMemos.json' import expirationOrder from './prepareOrderExpiration.json' import sellOrder from './prepareOrderSell.json' -import buyOrder from './prepareOrder.json' +import normalPayment from './preparePayment.json' import allOptions from './preparePaymentAllOptions.json' +import normalPayChanClaim from './preparePaymentChannelClaim.json' import closePayChanClaim from './preparePaymentChannelClaimClose.json' import fullPayChanClaim from './preparePaymentChannelClaimFull.json' import noSignaturePayChanClaim from './preparePaymentChannelClaimNoSignature.json' import renewPayChanClaim from './preparePaymentChannelClaimRenew.json' -import normalPayChanClaim from './preparePaymentChannelClaim.json' -import fullPayChanCreate from './preparePaymentChannelCreateFull.json' import normalPayChanCreate from './preparePaymentChannelCreate.json' -import fullPayChanFund from './preparePaymentChannelFundFull.json' +import fullPayChanCreate from './preparePaymentChannelCreateFull.json' import normalPayChanFund from './preparePaymentChannelFund.json' -import minAmountXRP from './preparePaymentMinXrp.json' +import fullPayChanFund from './preparePaymentChannelFundFull.json' import minAmount from './preparePaymentMin.json' +import minAmountXRP from './preparePaymentMinXrp.json' import noCounterparty from './preparePaymentNoCounterparty.json' import wrongAddress from './preparePaymentWrongAddress.json' import wrongAmount from './preparePaymentWrongAmount.json' import wrongPartial from './preparePaymentWrongPartial.json' -import normalPayment from './preparePayment.json' +import domain from './prepareSettings.json' import noSignerEntries from './prepareSettingsNoSignerEntries.json' +import normalSigners from './prepareSettingsSigners.json' import noThresholdSigners from './prepareSettingsSignersNoThreshold.json' import noWeightsSigners from './prepareSettingsSignersNoWeights.json' -import normalSigners from './prepareSettingsSigners.json' -import domain from './prepareSettings.json' +import complexTrustline from './prepareTrustline.json' import frozenTrustline from './prepareTrustlineFrozen.json' import issuedXAddressTrustline from './prepareTrustlineIssuerXaddress.json' import simpleTrustline from './prepareTrustlineSimple.json' -import complexTrustline from './prepareTrustline.json' +import normalSign from './sign.json' import signAsSign from './signAs.json' import escrowSign from './signEscrow.json' import signPaymentChannelClaim from './signPaymentChannelClaim.json' import ticketSign from './signTicket.json' -import normalSign from './sign.json' const prepareOrder = { buy: buyOrder, sell: sellOrder, - expiration: expirationOrder + expiration: expirationOrder, } const prepareOrderCancellation = { simple: simpleCancel, - withMemos: withMemosCancel + withMemos: withMemosCancel, } const preparePayment = { @@ -83,7 +83,7 @@ const preparePayment = { wrongAmount, wrongPartial, allOptions, - noCounterparty + noCounterparty, } const prepareSettings = { @@ -92,48 +92,48 @@ const prepareSettings = { signers: { normal: normalSigners, noThreshold: noThresholdSigners, - noWeights: noWeightsSigners - } + noWeights: noWeightsSigners, + }, } const prepareEscrowCreation = { normal: normalEscrowCreate, - full: fullEscrowCreate + full: fullEscrowCreate, } const prepareEscrowExecution = { normal: normalEscrowExec, simple: simpleEscrowExec, noCondition: noConditionEscrowExec, - noFulfillment: noFulfillmentEscrowExec + noFulfillment: noFulfillmentEscrowExec, } const prepareEscrowCancellation = { normal: normalEscrowCancel, - memos: memosEscrowCancel + memos: memosEscrowCancel, } const prepareCheckCreate = { normal: normalCheckCreate, - full: fullCheckCreate + full: fullCheckCreate, } const prepareCheckCash = { amount: amountCheckCash, - deliverMin: deliverMinCheckCash + deliverMin: deliverMinCheckCash, } const prepareCheckCancel = { - normal: normalCheckCancel + normal: normalCheckCancel, } const preparePaymentChannelCreate = { normal: normalPayChanCreate, - full: fullPayChanCreate + full: fullPayChanCreate, } const preparePaymentChannelFund = { normal: normalPayChanFund, - full: fullPayChanFund + full: fullPayChanFund, } const preparePaymentChannelClaim = { @@ -141,21 +141,21 @@ const preparePaymentChannelClaim = { full: fullPayChanClaim, close: closePayChanClaim, renew: renewPayChanClaim, - noSignature: noSignaturePayChanClaim + noSignature: noSignaturePayChanClaim, } const prepareTrustline = { simple: simpleTrustline, complex: complexTrustline, frozen: frozenTrustline, - issuedXAddress: issuedXAddressTrustline + issuedXAddress: issuedXAddressTrustline, } const sign = { normal: normalSign, ticket: ticketSign, escrow: escrowSign, - signAs: signAsSign + signAs: signAsSign, } const getPaths = { @@ -169,21 +169,21 @@ const getPaths = { NoPathsWithCurrencies, sendAll, invalid, - issuer + issuer, } const getOrderbook = { normal: normalOrderBook, - withXRP: withXRPOrderBook + withXRP: withXRPOrderBook, } const computeLedgerHash = { - header: {...header, rawTransactions: JSON.stringify(transactions)}, - transactions + header: { ...header, rawTransactions: JSON.stringify(transactions) }, + transactions, } const combine = { - setDomain + setDomain, } const requests = { @@ -206,7 +206,7 @@ const requests = { prepareTrustline, prepareSettings, sign, - signPaymentChannelClaim + signPaymentChannelClaim, } export default requests diff --git a/test/fixtures/responses/index.ts b/test/fixtures/responses/index.ts index ca557d5d..cd853439 100644 --- a/test/fixtures/responses/index.ts +++ b/test/fixtures/responses/index.ts @@ -4,124 +4,125 @@ import generateFaucetWallet from './generateFaucetWallet.json' import generateXAddress from './generateXAddress.json' import getAccountInfo from './getAccountInfo.json' import getAccountObjects from './getAccountObjects.json' -import getBalanceSheet from './getBalanceSheet.json' import getBalances from './getBalances.json' +import getBalanceSheet from './getBalanceSheet.json' +import header from './getLedger.json' import headerByHash from './getLedgerByHash.json' import fullLedger from './getLedgerFull.json' import pre2014withPartial from './getLedgerPre2014WithPartial.json' import withPartial from './getLedgerWithPartialPayment.json' import withSettingsTx from './getLedgerWithSettingsTx.json' import withStateAsHashes from './getLedgerWithStateAsHashes.json' -import header from './getLedger.json' -import withXRPOrderBook from './getOrderbookWithXrp.json' import normalOrderBook from './getOrderbook.json' +import withXRPOrderBook from './getOrderbookWithXrp.json' import getOrders from './getOrders.json' +import XrpToUsd from './getPaths.json' import sendAll from './getPathsSendAll.json' import UsdToUsd from './getPathsSendUsd.json' import XrpToXrp from './getPathsXrpToXrp.json' -import XrpToUsd from './getPaths.json' -import fullPayChan from './getPaymentChannelFull.json' import normalPayChan from './getPaymentChannel.json' +import fullPayChan from './getPaymentChannelFull.json' import getServerInfo from './getServerInfo.json' import getSettings from './getSettings.json' -import accountDeleteWithMemo from './getTransactionAccountDeleteWithMemo.json' import accountDelete from './getTransactionAccountDelete.json' +import accountDeleteWithMemo from './getTransactionAccountDeleteWithMemo.json' import amendment from './getTransactionAmendment.json' -import checkCancelWithMemo from './getTransactionCheckCancelWithMemo.json' import checkCancel from './getTransactionCheckCancel.json' -import checkCashWithMemo from './getTransactionCheckCashWithMemo.json' +import checkCancelWithMemo from './getTransactionCheckCancelWithMemo.json' import checkCash from './getTransactionCheckCash.json' -import checkCreateWithMemo from './getTransactionCheckCreateWithMemo.json' +import checkCashWithMemo from './getTransactionCheckCashWithMemo.json' import checkCreate from './getTransactionCheckCreate.json' +import checkCreateWithMemo from './getTransactionCheckCreateWithMemo.json' import depositPreauthWithMemo from './getTransactionDepositPreauthWithMemo.json' import escrowCancellation from './getTransactionEscrowCancellation.json' import escrowCreation from './getTransactionEscrowCreation.json' -import escrowExecutionSimple from './getTransactionEscrowExecutionSimple.json' import escrowExecution from './getTransactionEscrowExecution.json' -import feeUpdateWithMemo from './getTransactionFeeUpdateWithMemo.json' +import escrowExecutionSimple from './getTransactionEscrowExecutionSimple.json' import feeUpdate from './getTransactionFeeUpdate.json' +import feeUpdateWithMemo from './getTransactionFeeUpdateWithMemo.json' import noMeta from './getTransactionNoMeta.json' import notValidated from './getTransactionNotValidated.json' -import orderCancellationWithMemo from './getTransactionOrderCancellationWithMemo.json' +import order from './getTransactionOrder.json' import orderCancellation from './getTransactionOrderCancellation.json' +import orderCancellationWithMemo from './getTransactionOrderCancellationWithMemo.json' import orderSell from './getTransactionOrderSell.json' import orderWithExpirationCancellation from './getTransactionOrderWithExpirationCancellation.json' import orderWithMemo from './getTransactionOrderWithMemo.json' -import order from './getTransactionOrder.json' -import paymentChannelClaimWithMemo from './getTransactionPaymentChannelClaimWithMemo.json' -import paymentChannelClaim from './getTransactionPaymentChannelClaim.json' -import paymentChannelCreateWithMemo from './getTransactionPaymentChannelCreateWithMemo.json' -import paymentChannelCreate from './getTransactionPaymentChannelCreate.json' -import paymentChannelFundWithMemo from './getTransactionPaymentChannelFundWithMemo.json' -import paymentChannelFund from './getTransactionPaymentChannelFund.json' -import paymentIncludeRawTransaction from './getTransactionPaymentIncludeRawTransaction.json' import payment from './getTransactionPayment.json' +import paymentChannelClaim from './getTransactionPaymentChannelClaim.json' +import paymentChannelClaimWithMemo from './getTransactionPaymentChannelClaimWithMemo.json' +import paymentChannelCreate from './getTransactionPaymentChannelCreate.json' +import paymentChannelCreateWithMemo from './getTransactionPaymentChannelCreateWithMemo.json' +import paymentChannelFund from './getTransactionPaymentChannelFund.json' +import paymentChannelFundWithMemo from './getTransactionPaymentChannelFundWithMemo.json' +import paymentIncludeRawTransaction from './getTransactionPaymentIncludeRawTransaction.json' +import normalTransactions from './getTransactions.json' +import settings from './getTransactionSettings.json' import setRegularKey from './getTransactionSettingsSetRegularKey.json' import trackingOff from './getTransactionSettingsTrackingOff.json' import trackingOn from './getTransactionSettingsTrackingOn.json' -import settings from './getTransactionSettings.json' -import ticketCreateWithMemo from './getTransactionTicketCreateWithMemo.json' -import trustlineAddMemo from './getTransactionTrustAddMemo.json' -import trustlineNoQuality from './getTransactionTrustNoQuality.json' -import trustlineFrozenOff from './getTransactionTrustSetFrozenOff.json' -import trustline from './getTransactionTrustlineSet.json' -import withMemo from './getTransactionWithMemo.json' -import withMemos from './getTransactionWithMemos.json' import includeRawTransactions from './getTransactionsIncludeRawTransactions.json' import oneTransaction from './getTransactionsOne.json' -import normalTransactions from './getTransactions.json' +import ticketCreateWithMemo from './getTransactionTicketCreateWithMemo.json' +import trustlineAddMemo from './getTransactionTrustAddMemo.json' +import trustline from './getTransactionTrustlineSet.json' +import trustlineNoQuality from './getTransactionTrustNoQuality.json' +import trustlineFrozenOff from './getTransactionTrustSetFrozenOff.json' +import withMemo from './getTransactionWithMemo.json' +import withMemos from './getTransactionWithMemos.json' +import filteredLines from './getTrustlines.json' import allTrustlines from './getTrustlinesAll.json' import ripplingDisabledLines from './getTrustlinesRipplingDisabled.json' -import filteredLines from './getTrustlines.json' import ledgerEvent from './ledgerEvent.json' -import ticketCheckCancel from './prepareCheckCancelTicket.json' import normalCheckCancel from './prepareCheckCancel.json' +import ticketCheckCancel from './prepareCheckCancelTicket.json' import amountCheckCash from './prepareCheckCashAmount.json' import deliverMinCheckCash from './prepareCheckCashDelivermin.json' import ticketCheckCash from './prepareCheckCashTicket.json' +import normalCheckCreate from './prepareCheckCreate.json' import fullCheckCreate from './prepareCheckCreateFull.json' import ticketCheckCreate from './prepareCheckCreateTicket.json' -import normalCheckCreate from './prepareCheckCreate.json' +import normalEscrowCancel from './prepareEscrowCancellation.json' import memosEscrowCancel from './prepareEscrowCancellationMemos.json' import ticketEscrowCancel from './prepareEscrowCancellationTicket.json' -import normalEscrowCancel from './prepareEscrowCancellation.json' +import normalEscrowCreate from './prepareEscrowCreation.json' import fullEscrowCreate from './prepareEscrowCreationFull.json' import ticketEscrowCreate from './prepareEscrowCreationTicket.json' -import normalEscrowCreate from './prepareEscrowCreation.json' +import normalEscrowExec from './prepareEscrowExecution.json' import simpleEscrowExec from './prepareEscrowExecutionSimple.json' import ticketEscrowExec from './prepareEscrowExecutionTicket.json' -import normalEscrowExec from './prepareEscrowExecution.json' +import buyOrder from './prepareOrder.json' +import normalCancel from './prepareOrderCancellation.json' import withMemosCancel from './prepareOrderCancellationMemos.json' import noInstructionsCancel from './prepareOrderCancellationNoInstructions.json' import ticketCancel from './prepareOrderCancellationTicket.json' -import normalCancel from './prepareOrderCancellation.json' import expirationOrder from './prepareOrderExpiration.json' import sellOrder from './prepareOrderSell.json' import ticketOrder from './prepareOrderTicket.json' -import buyOrder from './prepareOrder.json' +import normalPayment from './preparePayment.json' import allOptionsPayment from './preparePaymentAllOptions.json' +import normalPayChanClaim from './preparePaymentChannelClaim.json' import closePayChanClaim from './preparePaymentChannelClaimClose.json' import renewPayChanClaim from './preparePaymentChannelClaimRenew.json' import ticketPayChanClaim from './preparePaymentChannelClaimTicket.json' -import normalPayChanClaim from './preparePaymentChannelClaim.json' +import normalPayChanCreate from './preparePaymentChannelCreate.json' import fullPayChanCreate from './preparePaymentChannelCreateFull.json' import ticketPayChanCreate from './preparePaymentChannelCreateTicket.json' -import normalPayChanCreate from './preparePaymentChannelCreate.json' +import normalPayChanFund from './preparePaymentChannelFund.json' import fullPayChanFund from './preparePaymentChannelFundFull.json' import ticketPayChanFund from './preparePaymentChannelFundTicket.json' -import normalPayChanFund from './preparePaymentChannelFund.json' -import minAmountXRPXRPPayment from './preparePaymentMinAmountXrpXrp.json' -import minAmountXRPPayment from './preparePaymentMinAmountXrp.json' import minAmountPayment from './preparePaymentMinAmount.json' +import minAmountXRPPayment from './preparePaymentMinAmountXrp.json' +import minAmountXRPXRPPayment from './preparePaymentMinAmountXrpXrp.json' import noCounterpartyPayment from './preparePaymentNoCounterparty.json' -import ticketSequencePayment from './preparePaymentTicketSequence.json' import ticketPayment from './preparePaymentTicket.json' -import normalPayment from './preparePayment.json' +import ticketSequencePayment from './preparePaymentTicketSequence.json' +import flagsSettings from './prepareSettings.json' import fieldClear from './prepareSettingsFieldClear.json' -import flagClearDepositAuth from './prepareSettingsFlagClearDepositAuth.json' import flagClear from './prepareSettingsFlagClear.json' -import flagSetDepositAuth from './prepareSettingsFlagSetDepositAuth.json' +import flagClearDepositAuth from './prepareSettingsFlagClearDepositAuth.json' import flagSet from './prepareSettingsFlagSet.json' +import flagSetDepositAuth from './prepareSettingsFlagSetDepositAuth.json' import flagsMultisign from './prepareSettingsMultisign.json' import noInstructions from './prepareSettingsNoInstructions.json' import noMaxLedgerVersion from './prepareSettingsNoMaxledgerversion.json' @@ -133,39 +134,38 @@ import setTransferRate from './prepareSettingsSetTransferRate.json' import signedSettings from './prepareSettingsSigned.json' import signersSettings from './prepareSettingsSigners.json' import ticketSettings from './prepareSettingsTicket.json' -import flagsSettings from './prepareSettings.json' +import complexTrustline from './prepareTrustline.json' import frozenTrustline from './prepareTrustlineFrozen.json' import issuedXAddressTrustline from './prepareTrustlineIssuerXaddress.json' import simpleTrustline from './prepareTrustlineSimple.json' import ticketTrustline from './prepareTrustlineTicket.json' -import complexTrustline from './prepareTrustline.json' +import normalSign from './sign.json' import signAsSign from './signAs.json' import escrowSign from './signEscrow.json' import signPaymentChannelClaim from './signPaymentChannelClaim.json' import ticketSign from './signTicket.json' -import normalSign from './sign.json' import submit from './submit.json' import trustlineItems from './trustlineItem.json' -function buildList(options: {item: any; count: number}): any[] { +function buildList(options: { item: any; count: number }): any[] { return new Array(options.count).fill(options.item) } const getPaymentChannel = { normal: normalPayChan, - full: fullPayChan + full: fullPayChan, } const getOrderbook = { normal: normalOrderBook, - withXRP: withXRPOrderBook + withXRP: withXRPOrderBook, } const getPaths = { XrpToUsd, XrpToXrp, UsdToUsd, - sendAll + sendAll, } const getTransaction = { @@ -211,23 +211,23 @@ const getTransaction = { accountDeleteWithMemo, ticketCreateWithMemo, withMemo, - withMemos + withMemos, } const getTransactions = { normal: normalTransactions, includeRawTransactions, - one: oneTransaction + one: oneTransaction, } const getTrustlines = { filtered: filteredLines, moreThan400Items: buildList({ item: trustlineItems, - count: 401 + count: 401, }), all: allTrustlines, - ripplingDisabled: ripplingDisabledLines + ripplingDisabled: ripplingDisabledLines, } const getLedger = { @@ -237,21 +237,21 @@ const getLedger = { withSettingsTx, withStateAsHashes, withPartial, - pre2014withPartial + pre2014withPartial, } const prepareOrder = { buy: buyOrder, ticket: ticketOrder, sell: sellOrder, - expiration: expirationOrder + expiration: expirationOrder, } const prepareOrderCancellation = { normal: normalCancel, ticket: ticketCancel, withMemos: withMemosCancel, - noInstructions: noInstructionsCancel + noInstructions: noInstructionsCancel, } const preparePayment = { @@ -262,7 +262,7 @@ const preparePayment = { allOptions: allOptionsPayment, noCounterparty: noCounterpartyPayment, minAmount: minAmountPayment, - ticketSequence: ticketSequencePayment + ticketSequence: ticketSequencePayment, } const prepareSettings = { @@ -282,61 +282,61 @@ const prepareSettings = { noMaxLedgerVersion, signers: signersSettings, noSignerList, - noWeights + noWeights, } const prepareCheckCreate = { normal: normalCheckCreate, ticket: ticketCheckCreate, - full: fullCheckCreate + full: fullCheckCreate, } const prepareCheckCash = { amount: amountCheckCash, ticket: ticketCheckCash, - deliverMin: deliverMinCheckCash + deliverMin: deliverMinCheckCash, } const prepareCheckCancel = { normal: normalCheckCancel, - ticket: ticketCheckCancel + ticket: ticketCheckCancel, } const prepareEscrowCreation = { normal: normalEscrowCreate, ticket: ticketEscrowCreate, - full: fullEscrowCreate + full: fullEscrowCreate, } const prepareEscrowExecution = { normal: normalEscrowExec, ticket: ticketEscrowExec, - simple: simpleEscrowExec + simple: simpleEscrowExec, } const prepareEscrowCancellation = { normal: normalEscrowCancel, ticket: ticketEscrowCancel, - memos: memosEscrowCancel + memos: memosEscrowCancel, } const preparePaymentChannelCreate = { normal: normalPayChanCreate, ticket: ticketPayChanCreate, - full: fullPayChanCreate + full: fullPayChanCreate, } const preparePaymentChannelFund = { normal: normalPayChanFund, ticket: ticketPayChanFund, - full: fullPayChanFund + full: fullPayChanFund, } const preparePaymentChannelClaim = { normal: normalPayChanClaim, ticket: ticketPayChanClaim, renew: renewPayChanClaim, - close: closePayChanClaim + close: closePayChanClaim, } const prepareTrustline = { @@ -344,18 +344,18 @@ const prepareTrustline = { ticket: ticketTrustline, frozen: frozenTrustline, issuedXAddress: issuedXAddressTrustline, - complex: complexTrustline + complex: complexTrustline, } const sign = { normal: normalSign, ticket: ticketSign, escrow: escrowSign, - signAs: signAsSign + signAs: signAsSign, } const combine = { - single: singleCombine + single: singleCombine, } const responses = { @@ -394,7 +394,7 @@ const responses = { preparePaymentChannelClaim, prepareTrustline, sign, - combine + combine, } export default responses diff --git a/test/fixtures/rippled/index.ts b/test/fixtures/rippled/index.ts index 79848609..7853c4f2 100644 --- a/test/fixtures/rippled/index.ts +++ b/test/fixtures/rippled/index.ts @@ -1,100 +1,100 @@ -import normalAccountInfo from "./accountInfo.json"; -import notfoundAccountInfo from "./accountInfoNotFound.json"; -import normalAccountObjects from "./accountObjectsNormal.json"; -import account_offers from "./accountOffers"; -import normalAccountTx from "./accountTx"; -import fabric from "./bookOffers"; -import usd_xrp from "./bookOffersUsdXrp.json"; -import empty from "./empty.json"; -import fee from "./fee.json"; -import normalLedger from "./ledger.json"; -import normalByHash from "./ledgerByHash.json"; -import notFound from "./ledgerNotFound.json"; -import withoutCloseTime from "./ledgerWithoutCloseTime.json"; +import normalAccountInfo from './accountInfo.json' +import notfoundAccountInfo from './accountInfoNotFound.json' +import normalAccountObjects from './accountObjectsNormal.json' +import account_offers from './accountOffers' +import normalAccountTx from './accountTx' +import fabric from './bookOffers' +import usd_xrp from './bookOffersUsdXrp.json' +import xrp_usd from './bookOffersXrpUsd.json' +import empty from './empty.json' +import escrow from './escrow.json' +import fee from './fee.json' +import gateway_balances from './gatewayBalances.json' +import oneAccountTx from './getTransactionsOne.json' +import normalLedger from './ledger.json' +import normalByHash from './ledgerByHash.json' +import ledger_current from './ledgerCurrent.json' +import first_page from './ledgerDataFirstPage.json' +import last_page from './ledgerDataLastPage.json' +import errorLedgerEntry from './ledgerEntryError.json' +import notFound from './ledgerNotFound.json' +import pre2014withPartial from './ledgerPre2014WithPartial.json' +import withoutCloseTime from './ledgerWithoutCloseTime.json' +import withPartialPayment from "./ledgerWithPartialPayment.json"; import withSettingsTx from "./ledgerWithSettingsTx.json"; import withStateAsHashes from "./ledgerWithStateAsHashes.json"; -import withPartialPayment from "./ledgerWithPartialPayment.json"; -import pre2014withPartial from "./ledgerPre2014WithPartial.json"; -import normalServerInfo from "./serverInfo.json"; +import normalServerInfo from './serverInfo.json' +import errorServerInfo from './serverInfoError.json' +import highLoadFactor from './serverInfoHighLoadFactor.json' import noValidated from "./serverInfoNoValidated.json"; import successSubscribe from "./subscribe.json"; import errorSubscribe from "./subscribeError.json"; import unsubscribe from "./unsubscribe.json"; -import escrow from "./escrow.json"; -import gateway_balances from "./gatewayBalances.json"; -import Payment from "./tx/payment.json"; -import AccountSet from "./tx/accountSet.json"; -import AccountSetTrackingOn from "./tx/accountSetTrackingOn.json"; -import AccountSetTrackingOff from "./tx/accountSetTrackingOff.json"; -import RegularKey from "./tx/setRegularKey.json"; -import OfferCreate from "./tx/offerCreate.json"; -import OfferCreateWithMemo from "./tx/offerCreateWithMemo.json"; -import OfferCreateSell from "./tx/offerCreateSell.json"; -import OfferCancel from "./tx/offerCancel.json"; -import OfferCancelWithMemo from "./tx/offerCancelWithMemo.json"; -import TrustSet from "./tx/trustSet.json"; -import TrustSetFrozenOff from "./tx/trustSetFrozenOff.json"; -import TrustSetNoQuality from "./tx/trustSetNoQuality.json"; -import TrustSetAddMemo from "./tx/trustSetAddMemo.json"; -import NotFound from "./tx/notFound.json"; -import NoLedgerIndex from "./tx/noLedgerIndex.json"; -import NoLedgerFound from "./tx/noLedgerFound.json"; -import LedgerWithoutTime from "./tx/ledgerWithoutTime.json"; -import NotValidated from "./tx/notValidated.json"; -import OfferWithExpiration from "./tx/orderWithExpiration.json"; -import CheckCreate from "./tx/checkCreate.json"; -import CheckCreateWithMemo from "./tx/checkCreateWithMemo.json"; -import CheckCancel from "./tx/checkCancel.json"; -import CheckCancelWithMemo from "./tx/checkCancelWithMemo.json"; -import CheckCash from "./tx/checkCash.json"; -import CheckCashWithMemo from "./tx/checkCashWithMemo.json"; -import EscrowCreation from "./tx/escrowCreation.json"; -import EscrowCancellation from "./tx/escrowCancellation.json"; -import EscrowExecution from "./tx/escrowExecution.json"; -import EscrowExecutionSimple from "./tx/escrowExecutionSimple.json"; -import PaymentChannelCreate from "./tx/paymentChannelCreate.json"; -import PaymentChannelCreateWithMemo from "./tx/paymentChannelCreateWithMemo.json"; -import PaymentChannelFund from "./tx/paymentChannelFund.json"; -import PaymentChannelFundWithMemo from "./tx/paymentChannelFundWithMemo.json"; -import PaymentChannelClaim from "./tx/paymentChannelClaim.json"; -import PaymentChannelClaimWithMemo from "./tx/paymentChannelClaimWithMemo.json"; -import Unrecognized from "./tx/unrecognized.json"; -import NoMeta from "./tx/noMeta.json"; -import LedgerZero from "./tx/ledgerZero.json"; -import Amendment from "./tx/amendment.json"; -import SetFee from "./tx/setFee.json"; -import SetFeeWithMemo from "./tx/setFeeWithMemo.json"; -import TicketCreateWithMemo from "./tx/ticketCreateWithMemo.json"; -import DepositPreauthWithMemo from "./tx/depositPreauthWithMemo.json"; -import AccountDelete from "./tx/accountDelete.json"; -import AccountDeleteWithMemo from "./tx/accountDeleteWithMemo.json"; -import WithMemo from "./tx/withMemo.json"; -import WithMemos from "./tx/withMemos.json"; -import oneAccountTx from "./getTransactionsOne.json"; -import xrp_usd from "./bookOffersXrpUsd.json"; -import first_page from "./ledgerDataFirstPage.json"; -import last_page from "./ledgerDataLastPage.json"; -import errorLedgerEntry from "./ledgerEntryError.json"; -import syncing from "./serverInfoSyncing.json"; -import errorServerInfo from "./serverInfoError.json"; -import reporting from "./serverInfoReporting.json"; -import highLoadFactor from "./serverInfoHighLoadFactor.json"; -import normalPayChan from "./paymentChannel.json"; -import fullPayChan from "./paymentChannelFull.json"; -import generate from "./pathFind"; -import sendUSD from "./pathFindSendUsd.json"; -import sendAll from "./pathFindSendAll.json"; -import XrpToXrp from "./pathFindXrpToXrp.json"; -import srcActNotFound from "./pathFindSrcActNotFound.json"; -import sourceAmountLow from "./pathFindSrcAmtLow.json"; -import ledger_current from "./ledgerCurrent.json"; -import successSubmit from "./submit.json"; -import failureSubmit from "./submitFailed.json"; +import Payment from './tx/payment.json' +import AccountSet from './tx/accountSet.json' +import AccountSetTrackingOn from './tx/accountSetTrackingOn.json' +import AccountSetTrackingOff from './tx/accountSetTrackingOff.json' +import RegularKey from './tx/setRegularKey.json' +import OfferCreate from './tx/offerCreate.json' +import OfferCreateWithMemo from './tx/offerCreateWithMemo.json' +import OfferCreateSell from './tx/offerCreateSell.json' +import OfferCancel from './tx/offerCancel.json' +import OfferCancelWithMemo from './tx/offerCancelWithMemo.json' +import TrustSet from './tx/trustSet.json' +import TrustSetFrozenOff from './tx/trustSetFrozenOff.json' +import TrustSetNoQuality from './tx/trustSetNoQuality.json' +import TrustSetAddMemo from './tx/trustSetAddMemo.json' +import NotFound from './tx/notFound.json' +import NoLedgerIndex from './tx/noLedgerIndex.json' +import NoLedgerFound from './tx/noLedgerFound.json' +import LedgerWithoutTime from './tx/ledgerWithoutTime.json' +import NotValidated from './tx/notValidated.json' +import OfferWithExpiration from './tx/orderWithExpiration.json' +import CheckCreate from './tx/checkCreate.json' +import CheckCreateWithMemo from './tx/checkCreateWithMemo.json' +import CheckCancel from './tx/checkCancel.json' +import CheckCancelWithMemo from './tx/checkCancelWithMemo.json' +import CheckCash from './tx/checkCash.json' +import CheckCashWithMemo from './tx/checkCashWithMemo.json' +import EscrowCreation from './tx/escrowCreation.json' +import EscrowCancellation from './tx/escrowCancellation.json' +import EscrowExecution from './tx/escrowExecution.json' +import EscrowExecutionSimple from './tx/escrowExecutionSimple.json' +import PaymentChannelCreate from './tx/paymentChannelCreate.json' +import PaymentChannelCreateWithMemo from './tx/paymentChannelCreateWithMemo.json' +import PaymentChannelFund from './tx/paymentChannelFund.json' +import PaymentChannelFundWithMemo from './tx/paymentChannelFundWithMemo.json' +import PaymentChannelClaim from './tx/paymentChannelClaim.json' +import PaymentChannelClaimWithMemo from './tx/paymentChannelClaimWithMemo.json' +import Unrecognized from './tx/unrecognized.json' +import NoMeta from './tx/noMeta.json' +import LedgerZero from './tx/ledgerZero.json' +import Amendment from './tx/amendment.json' +import SetFee from './tx/setFee.json' +import SetFeeWithMemo from './tx/setFeeWithMemo.json' +import TicketCreateWithMemo from './tx/ticketCreateWithMemo.json' +import DepositPreauthWithMemo from './tx/depositPreauthWithMemo.json' +import AccountDelete from './tx/accountDelete.json' +import AccountDeleteWithMemo from './tx/accountDeleteWithMemo.json' +import WithMemo from './tx/withMemo.json' +import WithMemos from './tx/withMemos.json' +import syncing from './serverInfoSyncing.json' +import reporting from './serverInfoReporting.json' +import normalPayChan from './paymentChannel.json' +import fullPayChan from './paymentChannelFull.json' +import generate from './pathFind' +import sendUSD from './pathFindSendUsd.json' +import sendAll from './pathFindSendAll.json' +import XrpToXrp from './pathFindXrpToXrp.json' +import srcActNotFound from './pathFindSrcActNotFound.json' +import sourceAmountLow from './pathFindSrcAmtLow.json' +import successSubmit from './submit.json' +import failureSubmit from './submitFailed.json' const submit = { success: successSubmit, failure: failureSubmit, -}; +} const ledger = { normal: normalLedger, @@ -105,42 +105,42 @@ const ledger = { withStateAsHashes, withPartialPayment, pre2014withPartial, -}; +} const subscribe = { success: successSubscribe, error: errorSubscribe, -}; +} const account_objects = { normal: normalAccountObjects, // notfound: notfoundAccountObjects -}; +} const account_info = { normal: normalAccountInfo, notfound: notfoundAccountInfo, -}; +} const account_tx = { normal: normalAccountTx, one: oneAccountTx, -}; +} const book_offers = { fabric, usd_xrp, xrp_usd, -}; +} const ledger_data = { first_page, last_page, -}; +} const ledger_entry = { error: errorLedgerEntry, -}; +} const server_info = { normal: normalServerInfo, @@ -149,7 +149,7 @@ const server_info = { error: errorServerInfo, reporting, highLoadFactor, -}; +} const path_find = { generate, @@ -158,12 +158,12 @@ const path_find = { XrpToXrp, srcActNotFound, sourceAmountLow, -}; +} const payment_channel = { normal: normalPayChan, full: fullPayChan, -}; +} const tx = { Payment, @@ -214,7 +214,7 @@ const tx = { AccountDeleteWithMemo, WithMemo, WithMemos, -}; +} const rippled = { account_info, @@ -237,6 +237,6 @@ const rippled = { subscribe, tx, unsubscribe, -}; +} -export default rippled; +export default rippled diff --git a/test/integration/integration.ts b/test/integration/integration.ts index 241433f4..451433ac 100644 --- a/test/integration/integration.ts +++ b/test/integration/integration.ts @@ -1,54 +1,54 @@ -import assert from "assert"; +import assert from 'assert' -import _ from "lodash"; -import { isValidXAddress } from "ripple-address-codec"; +import _ from 'lodash' +import { isValidXAddress } from 'ripple-address-codec' -import { Client } from "xrpl-local"; -import { errors } from "xrpl-local/common"; -import { isValidSecret } from "xrpl-local/utils"; +import { Client } from 'xrpl-local' +import { errors } from 'xrpl-local/common' +import { isValidSecret } from 'xrpl-local/utils' -import { generateXAddress } from "../../src/utils/generateAddress"; -import requests from "../fixtures/requests"; +import { generateXAddress } from '../../src/utils/generateAddress' +import requests from '../fixtures/requests' -import { payTo, ledgerAccept } from "./utils"; -import wallet from "./wallet"; +import { payTo, ledgerAccept } from './utils' +import wallet from './wallet' // how long before each test case times out -const TIMEOUT = 20000; -const INTERVAL = 1000; // how long to wait between checks for validated ledger +const TIMEOUT = 20000 +const INTERVAL = 1000 // how long to wait between checks for validated ledger -const HOST = process.env.HOST ?? "0.0.0.0"; -const PORT = process.env.PORT ?? "6006"; -const serverUrl = `ws://${HOST}:${PORT}`; +const HOST = process.env.HOST ?? '0.0.0.0' +const PORT = process.env.PORT ?? '6006' +const serverUrl = `ws://${HOST}:${PORT}` -console.log(serverUrl); +console.log(serverUrl) function acceptLedger(client) { - return client.connection.request({ command: "ledger_accept" }); + return client.connection.request({ command: 'ledger_accept' }) } function verifyTransaction(testcase, hash, type, options, txData, account) { - console.log("VERIFY..."); + console.log('VERIFY...') return testcase.client .request({ - command: "tx", + command: 'tx', transaction: hash, min_ledger: options.minLedgerVersion, max_ledger: options.maxLedgerVersion, }) .then((data) => { - assert(data && data.result); - assert.strictEqual(data.result.TransactionType, type); - assert.strictEqual(data.result.Account, account); - assert.strictEqual(data.result.meta.TransactionResult, "tesSUCCESS"); + assert(data && data.result) + assert.strictEqual(data.result.TransactionType, type) + assert.strictEqual(data.result.Account, account) + assert.strictEqual(data.result.meta.TransactionResult, 'tesSUCCESS') if (testcase.transactions != null) { - testcase.transactions.push(hash); + testcase.transactions.push(hash) } - return { txJSON: JSON.stringify(txData), id: hash, tx: data }; + return { txJSON: JSON.stringify(txData), id: hash, tx: data } }) - .catch((error) => { + .catch(async (error) => { if (error instanceof errors.PendingLedgerVersionError) { - console.log("NOT VALIDATED YET..."); + console.log('NOT VALIDATED YET...') return new Promise((resolve, reject) => { setTimeout( () => @@ -58,15 +58,15 @@ function verifyTransaction(testcase, hash, type, options, txData, account) { type, options, txData, - account + account, ).then(resolve, reject), - INTERVAL - ); - }); + INTERVAL, + ) + }) } - console.log(error.stack); - assert(false, `Transaction not successful: ${error.message}`); - }); + console.log(error.stack) + assert(false, `Transaction not successful: ${error.message}`) + }) } function testTransaction( @@ -75,29 +75,29 @@ function testTransaction( lastClosedLedgerVersion, prepared, address = wallet.getAddress(), - secret = wallet.getSecret() + secret = wallet.getSecret(), ) { - const txJSON = prepared.txJSON; - assert(txJSON, "missing txJSON"); - const txData = JSON.parse(txJSON); - assert.strictEqual(txData.Account, address); - const signedData = testcase.client.sign(txJSON, secret); - console.log("PREPARED..."); + const txJSON = prepared.txJSON + assert(txJSON, 'missing txJSON') + const txData = JSON.parse(txJSON) + assert.strictEqual(txData.Account, address) + const signedData = testcase.client.sign(txJSON, secret) + console.log('PREPARED...') return testcase.client - .request({ command: "submit", tx_blob: signedData.signedTransaction }) + .request({ command: 'submit', tx_blob: signedData.signedTransaction }) .then((response) => - testcase.test.title.indexOf("multisign") !== -1 + testcase.test.title.indexOf('multisign') !== -1 ? acceptLedger(testcase.client).then(() => response) - : response + : response, ) - .then((response) => { - console.log("SUBMITTED..."); - assert.strictEqual(response.result.engine_result, "tesSUCCESS"); + .then(async (response) => { + console.log('SUBMITTED...') + assert.strictEqual(response.result.engine_result, 'tesSUCCESS') const options = { minLedgerVersion: lastClosedLedgerVersion, maxLedgerVersion: txData.LastLedgerSequence, - }; - ledgerAccept(testcase.client); + } + ledgerAccept(testcase.client) return new Promise((resolve, reject) => { setTimeout( () => @@ -107,53 +107,53 @@ function testTransaction( type, options, txData, - address + address, ).then(resolve, reject), - INTERVAL - ); - }); - }); + INTERVAL, + ) + }) + }) } function setup(this: any, server = serverUrl) { - this.client = new Client(server); - console.log("CONNECTING..."); + this.client = new Client(server) + console.log('CONNECTING...') return this.client.connect().then( () => { - console.log("CONNECTED..."); + console.log('CONNECTED...') }, (error) => { - console.log("ERROR:", error); - throw error; - } - ); + console.log('ERROR:', error) + throw error + }, + ) } -const masterAccount = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; -const masterSecret = "snoPBrXtMeMyMHUVTgbuqAfg1SUTb"; +const masterAccount = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' +const masterSecret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' function makeTrustLine(testcase, address, secret) { - const client = testcase.client; + const client = testcase.client const specification = { - currency: "USD", + currency: 'USD', counterparty: masterAccount, - limit: "1341.1", + limit: '1341.1', ripplingDisabled: true, - }; + } const trust = client .prepareTrustline(address, specification, {}) .then((data) => { - const signed = client.sign(data.txJSON, secret); + const signed = client.sign(data.txJSON, secret) if (address === wallet.getAddress()) { - testcase.transactions.push(signed.id); + testcase.transactions.push(signed.id) } return client.request({ - command: "submit", + command: 'submit', tx_blob: signed.signedTransaction, - }); + }) }) - .then(() => ledgerAccept(client)); - return trust; + .then(() => ledgerAccept(client)) + return trust } function makeOrder(client, address, specification, secret) { @@ -161,92 +161,92 @@ function makeOrder(client, address, specification, secret) { .prepareOrder(address, specification) .then((data) => client.sign(data.txJSON, secret)) .then((signed) => - client.request({ command: "submit", tx_blob: signed.signedTransaction }) + client.request({ command: 'submit', tx_blob: signed.signedTransaction }), ) - .then(() => ledgerAccept(client)); + .then(() => ledgerAccept(client)) } function setupAccounts(testcase) { - const client = testcase.client; + const client = testcase.client - const promise = payTo(client, "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM") + const promise = payTo(client, 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM') .then(() => payTo(client, wallet.getAddress())) .then(() => payTo(client, testcase.newWallet.xAddress)) - .then(() => payTo(client, "rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc")) - .then(() => payTo(client, "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q")) + .then(() => payTo(client, 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc')) + .then(() => payTo(client, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { return client .prepareSettings(masterAccount, { defaultRipple: true }) .then((data) => client.sign(data.txJSON, masterSecret)) .then((signed) => client.request({ - command: "submit", + command: 'submit', tx_blob: signed.signedTransaction, - }) + }), ) - .then(() => ledgerAccept(client)); + .then(() => ledgerAccept(client)) }) .then(() => - makeTrustLine(testcase, wallet.getAddress(), wallet.getSecret()) + makeTrustLine(testcase, wallet.getAddress(), wallet.getSecret()), ) .then(() => makeTrustLine( testcase, testcase.newWallet.xAddress, - testcase.newWallet.secret - ) + testcase.newWallet.secret, + ), ) - .then(() => payTo(client, wallet.getAddress(), "123", "USD", masterAccount)) - .then(() => payTo(client, "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q")) + .then(() => payTo(client, wallet.getAddress(), '123', 'USD', masterAccount)) + .then(() => payTo(client, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { const orderSpecification = { - direction: "buy", + direction: 'buy', quantity: { - currency: "USD", - value: "432", + currency: 'USD', + value: '432', counterparty: masterAccount, }, totalPrice: { - currency: "XRP", - value: "432", + currency: 'XRP', + value: '432', }, - }; + } return makeOrder( testcase.client, testcase.newWallet.xAddress, orderSpecification, - testcase.newWallet.secret - ); + testcase.newWallet.secret, + ) }) .then(() => { const orderSpecification = { - direction: "buy", + direction: 'buy', quantity: { - currency: "XRP", - value: "1741", + currency: 'XRP', + value: '1741', }, totalPrice: { - currency: "USD", - value: "171", + currency: 'USD', + value: '171', counterparty: masterAccount, }, - }; + } return makeOrder( testcase.client, masterAccount, orderSpecification, - masterSecret - ); - }); - return promise; + masterSecret, + ) + }) + return promise } function teardown(this: any) { - return this.client.disconnect(); + return this.client.disconnect() } function suiteSetup(this: any) { - this.transactions = []; + this.transactions = [] return ( setup @@ -259,33 +259,33 @@ function suiteSetup(this: any) { .then(() => this.client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) - .then((response) => response.result.ledger_index) + .then((response) => response.result.ledger_index), ) .then((ledgerVersion) => { - this.startLedgerVersion = ledgerVersion; + this.startLedgerVersion = ledgerVersion }) .then(() => setupAccounts(this)) .then(() => teardown.bind(this)()) - ); + ) } -describe("integration tests", function () { - const address = wallet.getAddress(); - const instructions = { maxLedgerVersionOffset: 10 }; - this.timeout(TIMEOUT); +describe('integration tests', function () { + const address = wallet.getAddress() + const instructions = { maxLedgerVersionOffset: 10 } + this.timeout(TIMEOUT) - before(suiteSetup); - beforeEach(_.partial(setup, serverUrl)); - afterEach(teardown); + before(suiteSetup) + beforeEach(_.partial(setup, serverUrl)) + afterEach(teardown) - it("trustline", function () { + it('trustline', function () { return this.client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) .then((response) => response.result.ledger_index) .then((ledgerVersion) => { @@ -293,172 +293,172 @@ describe("integration tests", function () { .prepareTrustline( address, requests.prepareTrustline.simple, - instructions + instructions, ) .then((prepared) => - testTransaction(this, "TrustSet", ledgerVersion, prepared) - ); - }); - }); + testTransaction(this, 'TrustSet', ledgerVersion, prepared), + ) + }) + }) - it("payment", function () { - const amount = { currency: "XRP", value: "0.000001" }; + it('payment', function () { + const amount = { currency: 'XRP', value: '0.000001' } const paymentSpecification = { source: { address, maxAmount: amount, }, destination: { - address: "rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc", + address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc', amount, }, - }; + } return this.client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) .then((response) => response.result.ledger_index) .then((ledgerVersion) => { return this.client .preparePayment(address, paymentSpecification, instructions) .then((prepared) => - testTransaction(this, "Payment", ledgerVersion, prepared) - ); - }); - }); + testTransaction(this, 'Payment', ledgerVersion, prepared), + ) + }) + }) - it("order", function () { + it('order', function () { const orderSpecification = { - direction: "buy", + direction: 'buy', quantity: { - currency: "USD", - value: "237", - counterparty: "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q", + currency: 'USD', + value: '237', + counterparty: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q', }, totalPrice: { - currency: "XRP", - value: "0.0002", + currency: 'XRP', + value: '0.0002', }, - }; + } const expectedOrder = { flags: 0, - quality: "1.185", - taker_gets: "200", + quality: '1.185', + taker_gets: '200', taker_pays: { - currency: "USD", - value: "237", - issuer: "rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q", + currency: 'USD', + value: '237', + issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q', }, - }; + } return this.client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) .then((response) => response.result.ledger_index) .then((ledgerVersion) => { return this.client .prepareOrder(address, orderSpecification, instructions) .then((prepared) => - testTransaction(this, "OfferCreate", ledgerVersion, prepared) + testTransaction(this, 'OfferCreate', ledgerVersion, prepared), ) .then((result) => { - const txData = JSON.parse(result.txJSON); + const txData = JSON.parse(result.txJSON) return this.client .request({ - command: "account_offers", + command: 'account_offers', account: address, }) .then((response) => response.result.offers) .then((orders) => { - assert(orders && orders.length > 0); + assert(orders && orders.length > 0) const createdOrder = orders.filter((order) => { - return order.seq === txData.Sequence; - })[0]; - assert(createdOrder); - delete createdOrder.seq; - assert.deepEqual(createdOrder, expectedOrder); - return txData; - }); + return order.seq === txData.Sequence + })[0] + assert(createdOrder) + delete createdOrder.seq + assert.deepEqual(createdOrder, expectedOrder) + return txData + }) }) .then((txData) => this.client .prepareOrderCancellation( address, { orderSequence: txData.Sequence }, - instructions + instructions, ) .then((prepared) => - testTransaction(this, "OfferCancel", ledgerVersion, prepared) - ) - ); - }); - }); + testTransaction(this, 'OfferCancel', ledgerVersion, prepared), + ), + ) + }) + }) - it("isConnected", function () { - assert(this.client.isConnected()); - }); + it('isConnected', function () { + assert(this.client.isConnected()) + }) - it("getFee", function () { + it('getFee', function () { return this.client.getFee().then((fee) => { - assert.strictEqual(typeof fee, "string"); - assert(!isNaN(Number(fee))); - assert(parseFloat(fee) === Number(fee)); - }); - }); + assert.strictEqual(typeof fee, 'string') + assert(!isNaN(Number(fee))) + assert(parseFloat(fee) === Number(fee)) + }) + }) - it("getTrustlines", function () { - const fixture = requests.prepareTrustline.simple; - const { currency, counterparty } = fixture; - const options = { currency, counterparty }; + it('getTrustlines', function () { + const fixture = requests.prepareTrustline.simple + const { currency, counterparty } = fixture + const options = { currency, counterparty } return this.client.getTrustlines(address, options).then((data) => { - assert(data && data.length > 0 && data[0] && data[0].specification); - const specification = data[0].specification; - assert.strictEqual(Number(specification.limit), Number(fixture.limit)); - assert.strictEqual(specification.currency, fixture.currency); - assert.strictEqual(specification.counterparty, fixture.counterparty); - }); - }); + assert(data && data.length > 0 && data[0] && data[0].specification) + const specification = data[0].specification + assert.strictEqual(Number(specification.limit), Number(fixture.limit)) + assert.strictEqual(specification.currency, fixture.currency) + assert.strictEqual(specification.counterparty, fixture.counterparty) + }) + }) - it("getBalances", function () { - const fixture = requests.prepareTrustline.simple; - const { currency, counterparty } = fixture; - const options = { currency, counterparty }; + it('getBalances', function () { + const fixture = requests.prepareTrustline.simple + const { currency, counterparty } = fixture + const options = { currency, counterparty } return this.client.getBalances(address, options).then((data) => { - assert(data && data.length > 0 && data[0]); - assert.strictEqual(data[0].currency, fixture.currency); - assert.strictEqual(data[0].counterparty, fixture.counterparty); - }); - }); + assert(data && data.length > 0 && data[0]) + assert.strictEqual(data[0].currency, fixture.currency) + assert.strictEqual(data[0].counterparty, fixture.counterparty) + }) + }) - it("getOrderbook", function () { + it('getOrderbook', function () { const orderbook = { base: { - currency: "XRP", + currency: 'XRP', }, counter: { - currency: "USD", + currency: 'USD', counterparty: masterAccount, }, - }; + } return this.client.getOrderbook(address, orderbook).then((book) => { - assert(book && book.bids && book.bids.length > 0); - assert(book.asks && book.asks.length > 0); - const bid = book.bids[0]; - assert(bid && bid.specification && bid.specification.quantity); - assert(bid.specification.totalPrice); - assert.strictEqual(bid.specification.direction, "buy"); - assert.strictEqual(bid.specification.quantity.currency, "XRP"); - assert.strictEqual(bid.specification.totalPrice.currency, "USD"); - const ask = book.asks[0]; - assert(ask && ask.specification && ask.specification.quantity); - assert(ask.specification.totalPrice); - assert.strictEqual(ask.specification.direction, "sell"); - assert.strictEqual(ask.specification.quantity.currency, "XRP"); - assert.strictEqual(ask.specification.totalPrice.currency, "USD"); - }); - }); + assert(book && book.bids && book.bids.length > 0) + assert(book.asks && book.asks.length > 0) + const bid = book.bids[0] + assert(bid && bid.specification && bid.specification.quantity) + assert(bid.specification.totalPrice) + assert.strictEqual(bid.specification.direction, 'buy') + assert.strictEqual(bid.specification.quantity.currency, 'XRP') + assert.strictEqual(bid.specification.totalPrice.currency, 'USD') + const ask = book.asks[0] + assert(ask && ask.specification && ask.specification.quantity) + assert(ask.specification.totalPrice) + assert.strictEqual(ask.specification.direction, 'sell') + assert.strictEqual(ask.specification.quantity.currency, 'XRP') + assert.strictEqual(ask.specification.totalPrice.currency, 'USD') + }) + }) // it('getPaths', function () { // const pathfind = { @@ -517,104 +517,104 @@ describe("integration tests", function () { // }) // }) - it("generateWallet", function () { - const newWallet = generateXAddress(); - assert(newWallet && newWallet.xAddress && newWallet.secret); - assert(isValidXAddress(newWallet.xAddress)); - assert(isValidSecret(newWallet.secret)); - }); -}); + it('generateWallet', function () { + const newWallet = generateXAddress() + assert(newWallet && newWallet.xAddress && newWallet.secret) + assert(isValidXAddress(newWallet.xAddress)) + assert(isValidSecret(newWallet.secret)) + }) +}) -describe("integration tests - standalone rippled", function () { - const instructions = { maxLedgerVersionOffset: 10 }; - this.timeout(TIMEOUT); +describe('integration tests - standalone rippled', function () { + const instructions = { maxLedgerVersionOffset: 10 } + this.timeout(TIMEOUT) - beforeEach(_.partial(setup, serverUrl)); - afterEach(teardown); - const address = "r5nx8ZkwEbFztnc8Qyi22DE9JYjRzNmvs"; - const secret = "ss6F8381Br6wwpy9p582H8sBt19J3"; - const signer1address = "rQDhz2ZNXmhxzCYwxU6qAbdxsHA4HV45Y2"; - const signer1secret = "shK6YXzwYfnFVn3YZSaMh5zuAddKx"; - const signer2address = "r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud"; - const signer2secret = "shUHQnL4EH27V4EiBrj6EfhWvZngF"; + beforeEach(_.partial(setup, serverUrl)) + afterEach(teardown) + const address = 'r5nx8ZkwEbFztnc8Qyi22DE9JYjRzNmvs' + const secret = 'ss6F8381Br6wwpy9p582H8sBt19J3' + const signer1address = 'rQDhz2ZNXmhxzCYwxU6qAbdxsHA4HV45Y2' + const signer1secret = 'shK6YXzwYfnFVn3YZSaMh5zuAddKx' + const signer2address = 'r3RtUvGw9nMoJ5FuHxuoVJvcENhKtuF9ud' + const signer2secret = 'shUHQnL4EH27V4EiBrj6EfhWvZngF' - it("submit multisigned transaction", function () { + it('submit multisigned transaction', function () { const signers = { threshold: 2, weights: [ { address: signer1address, weight: 1 }, { address: signer2address, weight: 1 }, ], - }; - let minLedgerVersion = null; + } + let minLedgerVersion = null return payTo(this.client, address) .then(() => { return this.client .request({ - command: "ledger", - ledger_index: "validated", + command: 'ledger', + ledger_index: 'validated', }) .then((response) => response.result.ledger_index) .then((ledgerVersion) => { - minLedgerVersion = ledgerVersion; + minLedgerVersion = ledgerVersion return this.client .prepareSettings(address, { signers }, instructions) .then((prepared) => { return testTransaction( this, - "SignerListSet", + 'SignerListSet', ledgerVersion, prepared, address, - secret - ); - }); - }); + secret, + ) + }) + }) }) .then(() => { - const multisignInstructions = { ...instructions, signersCount: 2 }; + const multisignInstructions = { ...instructions, signersCount: 2 } return this.client .prepareSettings( address, - { domain: "example.com" }, - multisignInstructions + { domain: 'example.com' }, + multisignInstructions, ) .then((prepared) => { const signed1 = this.client.sign(prepared.txJSON, signer1secret, { signAs: signer1address, - }); + }) const signed2 = this.client.sign(prepared.txJSON, signer2secret, { signAs: signer2address, - }); + }) const combined = this.client.combine([ signed1.signedTransaction, signed2.signedTransaction, - ]); + ]) return this.client .request({ - command: "submit", + command: 'submit', tx_blob: combined.signedTransaction, }) .then((response) => - acceptLedger(this.client).then(() => response) + acceptLedger(this.client).then(() => response), ) .then((response) => { - assert.strictEqual(response.result.engine_result, "tesSUCCESS"); - const options = { minLedgerVersion }; + assert.strictEqual(response.result.engine_result, 'tesSUCCESS') + const options = { minLedgerVersion } return verifyTransaction( this, combined.id, - "AccountSet", + 'AccountSet', options, {}, - address - ); + address, + ) }) .catch((error) => { - console.log(error.message); - throw error; - }); - }); - }); - }); -}); + console.log(error.message) + throw error + }) + }) + }) + }) +}) diff --git a/test/mockRippled.ts b/test/mockRippled.ts index 0bbe1f8e..12b7fa12 100644 --- a/test/mockRippled.ts +++ b/test/mockRippled.ts @@ -1,21 +1,21 @@ -import { EventEmitter2 } from "eventemitter2"; -import _ from "lodash"; -import { Server as WebSocketServer } from "ws"; +import { EventEmitter2 } from 'eventemitter2' +import _ from 'lodash' +import { Server as WebSocketServer } from 'ws' -import type { Request } from "../src"; -import type { BaseResponse } from "../src/models/methods/baseMethod"; +import type { Request } from '../src' +import type { BaseResponse } from '../src/models/methods/baseMethod' -import { getFreePort } from "./testUtils"; +import { getFreePort } from './testUtils' function createResponse(request: { id: number | string }, response: object) { - if (!("type" in response) && !("error" in response)) { + if (!('type' in response) && !('error' in response)) { throw new Error( `Bad response format. Must contain \`type\` or \`error\`. ${JSON.stringify( - response - )}` - ); + response, + )}`, + ) } - return JSON.stringify({ ...response, id: request.id }); + return JSON.stringify({ ...response, id: request.id }) } function ping(conn, request) { @@ -23,144 +23,144 @@ function ping(conn, request) { conn.send( createResponse(request, { result: {}, - status: "success", - type: "response", - }) - ); - }, 1000 * 2); + status: 'success', + type: 'response', + }), + ) + }, 1000 * 2) } export interface PortResponse extends BaseResponse { result: { - port: number; - }; + port: number + } } // We mock out WebSocketServer in these tests and add a lot of custom // properties not defined on the normal WebSocketServer object. -type MockedWebSocketServer = any; +type MockedWebSocketServer = any export function createMockRippled(port) { - const mock = new WebSocketServer({ port }) as MockedWebSocketServer; - Object.assign(mock, EventEmitter2.prototype); + const mock = new WebSocketServer({ port }) as MockedWebSocketServer + Object.assign(mock, EventEmitter2.prototype) - mock.responses = {}; - mock.suppressOutput = false; + mock.responses = {} + mock.suppressOutput = false - mock.on("connection", function (this: MockedWebSocketServer, conn: any) { - this.socket = conn; - conn.on("message", function (requestJSON) { - let request; + mock.on('connection', function (this: MockedWebSocketServer, conn: any) { + this.socket = conn + conn.on('message', function (requestJSON) { + let request try { - request = JSON.parse(requestJSON); + request = JSON.parse(requestJSON) if (request.id == null) { - throw new Error("Request has no id"); + throw new Error('Request has no id') } - if (request.command === "ping") { - ping(conn, request); - } else if (request.command === "test_command") { - mock.testCommand(conn, request); + if (request.command === 'ping') { + ping(conn, request) + } else if (request.command === 'test_command') { + mock.testCommand(conn, request) } else if (request.command in mock.responses) { - conn.send(createResponse(request, mock.getResponse(request))); + conn.send(createResponse(request, mock.getResponse(request))) } else { throw new Error( - `No event handler registered in mock rippled for ${request.command}` - ); + `No event handler registered in mock rippled for ${request.command}`, + ) } } catch (err) { if (!mock.suppressOutput) { - console.error(`Error: ${err.message}`); + console.error(`Error: ${err.message}`) } if (request != null) { conn.send( createResponse(request, { - type: "response", - status: "error", + type: 'response', + status: 'error', error: err.message, - }) - ); + }), + ) } } - }); - }); + }) + }) // Adds a mocked response // If an object is passed in for `response`, then the response is static for the command // If a function is passed in for `response`, then the response can be determined by the exact request shape mock.addResponse = ( command: string, - response: object | ((r: Request) => object) + response: object | ((r: Request) => object), ) => { - if (typeof command !== "string") { - throw new Error("command is not a string"); + if (typeof command !== 'string') { + throw new Error('command is not a string') } if ( - typeof response === "object" && - !("type" in response) && - !("error" in response) + typeof response === 'object' && + !('type' in response) && + !('error' in response) ) { throw new Error( `Bad response format. Must contain \`type\` or \`error\`. ${JSON.stringify( - response - )}` - ); + response, + )}`, + ) } - mock.responses[command] = response; - }; + mock.responses[command] = response + } mock.getResponse = (request: Request): object => { if (!(request.command in mock.responses)) { - throw new Error(`No handler for ${request.command}`); + throw new Error(`No handler for ${request.command}`) } - const functionOrObject = mock.responses[request.command]; - if (typeof functionOrObject === "function") { - return functionOrObject(request); + const functionOrObject = mock.responses[request.command] + if (typeof functionOrObject === 'function') { + return functionOrObject(request) } - return functionOrObject; - }; + return functionOrObject + } mock.testCommand = function testCommand(conn, request) { if (request.data.disconnectIn) { - setTimeout(conn.terminate.bind(conn), request.data.disconnectIn); + setTimeout(conn.terminate.bind(conn), request.data.disconnectIn) conn.send( createResponse(request, { - status: "success", - type: "response", + status: 'success', + type: 'response', result: {}, - }) - ); + }), + ) } else if (request.data.openOnOtherPort) { getFreePort().then((newPort) => { - createMockRippled(newPort); + createMockRippled(newPort) conn.send( createResponse(request, { - status: "success", - type: "response", + status: 'success', + type: 'response', result: { port: newPort }, - }) - ); - }); + }), + ) + }) } else if (request.data.closeServerAndReopen) { setTimeout(() => { - conn.terminate(); + conn.terminate() mock.close.call(mock, () => { setTimeout(() => { - createMockRippled(port); - }, request.data.closeServerAndReopen); - }); - }, 10); + createMockRippled(port) + }, request.data.closeServerAndReopen) + }) + }, 10) } else if (request.data.unrecognizedResponse) { conn.send( createResponse(request, { - status: "unrecognized", - type: "response", + status: 'unrecognized', + type: 'response', result: {}, - }) - ); + }), + ) } else if (request.data.closeServer) { - conn.close(); + conn.close() } - }; + } - return mock; + return mock } diff --git a/test/mockRippledTest.ts b/test/mockRippledTest.ts index 719865ab..f72b3381 100644 --- a/test/mockRippledTest.ts +++ b/test/mockRippledTest.ts @@ -1,36 +1,36 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { RippledError } from "../src/common/errors"; +import { RippledError } from '../src/common/errors' -import setupClient from "./setupClient"; -import { assertRejects } from "./testUtils"; +import setupClient from './setupClient' +import { assertRejects } from './testUtils' -describe("mock rippled tests", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); - it("errors if a mock is not provided", async function () { - this.mockRippled.suppressOutput = true; +describe('mock rippled tests', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) + it('errors if a mock is not provided', async function () { + this.mockRippled.suppressOutput = true await assertRejects( - this.client.request({ command: "server_info" }), - RippledError - ); - }); + this.client.request({ command: 'server_info' }), + RippledError, + ) + }) - it("provide bad response shape", async function () { + it('provide bad response shape', async function () { assert.throws( - () => this.mockRippled.addResponse("account_info", { data: {} }), - Error - ); - }); + () => this.mockRippled.addResponse('account_info', { data: {} }), + Error, + ) + }) - it("provide bad response shape in function", async function () { - this.mockRippled.suppressOutput = true; - this.mockRippled.addResponse("account_info", (request) => { - return { data: request }; - }); + it('provide bad response shape in function', async function () { + this.mockRippled.suppressOutput = true + this.mockRippled.addResponse('account_info', (request) => { + return { data: request } + }) await assertRejects( - this.client.request({ command: "account_info", account: "" }), - RippledError - ); - }); -}); + this.client.request({ command: 'account_info', account: '' }), + RippledError, + ) + }) +}) diff --git a/test/mockedServer.ts b/test/mockedServer.ts index b0ea85ea..69785f8b 100644 --- a/test/mockedServer.ts +++ b/test/mockedServer.ts @@ -1,17 +1,17 @@ -import { createMockRippled } from "./mockRippled"; +import { createMockRippled } from './mockRippled' -const port = 34371; +const port = 34371 function main() { // @ts-expect-error -- mocha. if (global.describe) { // we are running inside mocha, exiting - return; + return } - console.log(`starting server on port ${port}`); - createMockRippled(port); - console.log(`starting server on port ${String(port + 1)}`); - createMockRippled(port + 1); + console.log(`starting server on port ${port}`) + createMockRippled(port) + console.log(`starting server on port ${String(port + 1)}`) + createMockRippled(port + 1) } -main(); +main() diff --git a/test/models/accountDelete.ts b/test/models/accountDelete.ts index 65e38ad0..74c0f212 100644 --- a/test/models/accountDelete.ts +++ b/test/models/accountDelete.ts @@ -1,77 +1,77 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyAccountDelete } from "../../src/models/transactions/accountDelete"; +import { verifyAccountDelete } from '../../src/models/transactions/accountDelete' /** * AccountDelete Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("AccountDelete", function () { +describe('AccountDelete', function () { it(`verifies valid AccountDelete`, function () { const validAccountDelete = { - TransactionType: "AccountDelete", - Account: "rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm", - Destination: "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe", + TransactionType: 'AccountDelete', + Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', + Destination: 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe', DestinationTag: 13, - Fee: "5000000", + Fee: '5000000', Sequence: 2470665, Flags: 2147483648, - } as any; + } as any - assert.doesNotThrow(() => verifyAccountDelete(validAccountDelete)); - }); + assert.doesNotThrow(() => verifyAccountDelete(validAccountDelete)) + }) it(`throws w/ missing Destination`, function () { const invalidDestination = { - TransactionType: "AccountDelete", - Account: "rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm", - Fee: "5000000", + TransactionType: 'AccountDelete', + Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', + Fee: '5000000', Sequence: 2470665, Flags: 2147483648, - } as any; + } as any assert.throws( () => verifyAccountDelete(invalidDestination), ValidationError, - "AccountDelete: missing field Destination" - ); - }); + 'AccountDelete: missing field Destination', + ) + }) it(`throws w/ invalid Destination`, function () { const invalidDestination = { - TransactionType: "AccountDelete", - Account: "rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm", + TransactionType: 'AccountDelete', + Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', Destination: 65478965, - Fee: "5000000", + Fee: '5000000', Sequence: 2470665, Flags: 2147483648, - } as any; + } as any assert.throws( () => verifyAccountDelete(invalidDestination), ValidationError, - "AccountDelete: invalid Destination" - ); - }); + 'AccountDelete: invalid Destination', + ) + }) it(`throws w/ invalid DestinationTag`, function () { const invalidDestinationTag = { - TransactionType: "AccountDelete", - Account: "rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm", - Destination: "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe", - DestinationTag: "gvftyujnbv", - Fee: "5000000", + TransactionType: 'AccountDelete', + Account: 'rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm', + Destination: 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe', + DestinationTag: 'gvftyujnbv', + Fee: '5000000', Sequence: 2470665, Flags: 2147483648, - } as any; + } as any assert.throws( () => verifyAccountDelete(invalidDestinationTag), ValidationError, - "AccountDelete: invalid DestinationTag" - ); - }); -}); + 'AccountDelete: invalid DestinationTag', + ) + }) +}) diff --git a/test/models/accountSet.ts b/test/models/accountSet.ts index 9747e4c9..72afbdca 100644 --- a/test/models/accountSet.ts +++ b/test/models/accountSet.ts @@ -1,111 +1,111 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyAccountSet } from "../../src/models/transactions/accountSet"; +import { verifyAccountSet } from '../../src/models/transactions/accountSet' /** * AccountSet Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("AccountSet", function () { - let account; +describe('AccountSet', function () { + let account beforeEach(function () { account = { - TransactionType: "AccountSet", - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - Fee: "12", + TransactionType: 'AccountSet', + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + Fee: '12', Sequence: 5, - Domain: "6578616D706C652E636F6D", + Domain: '6578616D706C652E636F6D', SetFlag: 5, MessageKey: - "03AB40A0490F9B7ED8DF29D246BF2D6269820A0EE7742ACDD457BEA7C7D0931EDB", - } as any; - }); + '03AB40A0490F9B7ED8DF29D246BF2D6269820A0EE7742ACDD457BEA7C7D0931EDB', + } as any + }) it(`verifies valid AccountSet`, function () { - assert.doesNotThrow(() => verifyAccountSet(account)); - }); + assert.doesNotThrow(() => verifyAccountSet(account)) + }) it(`throws w/ invalid SetFlag (out of range)`, function () { - account.SetFlag = 12; + account.SetFlag = 12 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid SetFlag" - ); - }); + 'AccountSet: invalid SetFlag', + ) + }) it(`throws w/ invalid SetFlag (incorrect type)`, function () { - account.SetFlag = "abc"; + account.SetFlag = 'abc' assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid SetFlag" - ); - }); + 'AccountSet: invalid SetFlag', + ) + }) it(`throws w/ invalid ClearFlag`, function () { - account.ClearFlag = 12; + account.ClearFlag = 12 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid ClearFlag" - ); - }); + 'AccountSet: invalid ClearFlag', + ) + }) it(`throws w/ invalid Domain`, function () { - account.Domain = 6578616; + account.Domain = 6578616 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid Domain" - ); - }); + 'AccountSet: invalid Domain', + ) + }) it(`throws w/ invalid EmailHash`, function () { - account.EmailHash = 6578656789876543; + account.EmailHash = 6578656789876543 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid EmailHash" - ); - }); + 'AccountSet: invalid EmailHash', + ) + }) it(`throws w/ invalid MessageKey`, function () { - account.MessageKey = 6578656789876543; + account.MessageKey = 6578656789876543 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid MessageKey" - ); - }); + 'AccountSet: invalid MessageKey', + ) + }) it(`throws w/ invalid TransferRate`, function () { - account.TransferRate = "1000000001"; + account.TransferRate = '1000000001' assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid TransferRate" - ); - }); + 'AccountSet: invalid TransferRate', + ) + }) it(`throws w/ invalid TickSize`, function () { - account.TickSize = 20; + account.TickSize = 20 assert.throws( () => verifyAccountSet(account), ValidationError, - "AccountSet: invalid TickSize" - ); - }); -}); + 'AccountSet: invalid TickSize', + ) + }) +}) diff --git a/test/models/baseTransaction.ts b/test/models/baseTransaction.ts index 1b12184c..386c52bf 100644 --- a/test/models/baseTransaction.ts +++ b/test/models/baseTransaction.ts @@ -1,232 +1,232 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyBaseTransaction } from "../../src/models/transactions/common"; +import { verifyBaseTransaction } from '../../src/models/transactions/common' /** * Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("BaseTransaction", function () { +describe('BaseTransaction', function () { it(`Verifies all optional BaseTransaction`, function () { const txJson = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - Fee: "12", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + Fee: '12', Sequence: 100, - AccountTxnID: "DEADBEEF", + AccountTxnID: 'DEADBEEF', Flags: 15, LastLedgerSequence: 1383, Memos: [ { Memo: { MemoType: - "687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963", - MemoData: "72656e74", + '687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963', + MemoData: '72656e74', }, }, { Memo: { MemoFormat: - "687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963", - MemoData: "72656e74", + '687474703a2f2f6578616d706c652e636f6d2f6d656d6f2f67656e65726963', + MemoData: '72656e74', }, }, { Memo: { - MemoType: "72656e74", + MemoType: '72656e74', }, }, ], Signers: [ { - Account: "r....", - TxnSignature: "DEADBEEF", - SigningPubKey: "hex-string", + Account: 'r....', + TxnSignature: 'DEADBEEF', + SigningPubKey: 'hex-string', }, ], SourceTag: 31, SigningPublicKey: - "03680DD274EE55594F7244F489CD38CF3A5A1A4657122FB8143E185B2BA043DF36", + '03680DD274EE55594F7244F489CD38CF3A5A1A4657122FB8143E185B2BA043DF36', TicketSequence: 10, TxnSignature: - "3045022100C6708538AE5A697895937C758E99A595B57A16393F370F11B8D4C032E80B532002207776A8E85BB9FAF460A92113B9C60F170CD964196B1F084E0DAB65BAEC368B66", - }; + '3045022100C6708538AE5A697895937C758E99A595B57A16393F370F11B8D4C032E80B532002207776A8E85BB9FAF460A92113B9C60F170CD964196B1F084E0DAB65BAEC368B66', + } - assert.doesNotThrow(() => verifyBaseTransaction(txJson)); - }); + assert.doesNotThrow(() => verifyBaseTransaction(txJson)) + }) it(`Verifies only required BaseTransaction`, function () { const txJson = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - }; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + } - assert.doesNotThrow(() => verifyBaseTransaction(txJson)); - }); + assert.doesNotThrow(() => verifyBaseTransaction(txJson)) + }) it(`Handles invalid Fee`, function () { const invalidFee = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', Fee: 1000, - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidFee), ValidationError, - "BaseTransaction: invalid Fee" - ); - }); + 'BaseTransaction: invalid Fee', + ) + }) it(`Handles invalid Sequence`, function () { const invalidSeq = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - Sequence: "145", - } as any; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + Sequence: '145', + } as any assert.throws( () => verifyBaseTransaction(invalidSeq), ValidationError, - "BaseTransaction: invalid Sequence" - ); - }); + 'BaseTransaction: invalid Sequence', + ) + }) it(`Handles invalid AccountTxnID`, function () { const invalidID = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - AccountTxnID: ["WRONG"], - } as any; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + AccountTxnID: ['WRONG'], + } as any assert.throws( () => verifyBaseTransaction(invalidID), ValidationError, - "BaseTransaction: invalid AccountTxnID" - ); - }); + 'BaseTransaction: invalid AccountTxnID', + ) + }) it(`Handles invalid LastLedgerSequence`, function () { const invalidLastLedgerSequence = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - LastLedgerSequence: "1000", - } as any; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + LastLedgerSequence: '1000', + } as any assert.throws( () => verifyBaseTransaction(invalidLastLedgerSequence), ValidationError, - "BaseTransaction: invalid LastLedgerSequence" - ); - }); + 'BaseTransaction: invalid LastLedgerSequence', + ) + }) it(`Handles invalid SourceTag`, function () { const invalidSourceTag = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - SourceTag: ["ARRAY"], - } as any; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + SourceTag: ['ARRAY'], + } as any assert.throws( () => verifyBaseTransaction(invalidSourceTag), ValidationError, - "BaseTransaction: invalid SourceTag" - ); - }); + 'BaseTransaction: invalid SourceTag', + ) + }) it(`Handles invalid SigningPubKey`, function () { const invalidSigningPubKey = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', SigningPubKey: 1000, - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidSigningPubKey), ValidationError, - "BaseTransaction: invalid SigningPubKey" - ); - }); + 'BaseTransaction: invalid SigningPubKey', + ) + }) it(`Handles invalid TicketSequence`, function () { const invalidTicketSequence = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", - TicketSequence: "1000", - } as any; + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', + TicketSequence: '1000', + } as any assert.throws( () => verifyBaseTransaction(invalidTicketSequence), ValidationError, - "BaseTransaction: invalid TicketSequence" - ); - }); + 'BaseTransaction: invalid TicketSequence', + ) + }) it(`Handles invalid TxnSignature`, function () { const invalidTxnSignature = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', TxnSignature: 1000, - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidTxnSignature), ValidationError, - "BaseTransaction: invalid TxnSignature" - ); - }); + 'BaseTransaction: invalid TxnSignature', + ) + }) it(`Handles invalid Signers`, function () { const invalidSigners = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', Signers: [], - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidSigners), ValidationError, - "BaseTransaction: invalid Signers" - ); + 'BaseTransaction: invalid Signers', + ) const invalidSigners2 = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', Signers: [ { - Account: "r....", + Account: 'r....', }, ], - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidSigners2), ValidationError, - "BaseTransaction: invalid Signers" - ); - }); + 'BaseTransaction: invalid Signers', + ) + }) it(`Handles invalid Memo`, function () { const invalidMemo = { - Account: "r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe", - TransactionType: "Payment", + Account: 'r97KeayHuEsDwyU1yPBVtMLLoQr79QcRFe', + TransactionType: 'Payment', Memos: [ { Memo: { - MemoData: "HI", - Address: "WRONG", + MemoData: 'HI', + Address: 'WRONG', }, }, ], - } as any; + } as any assert.throws( () => verifyBaseTransaction(invalidMemo), ValidationError, - "BaseTransaction: invalid Memos" - ); - }); -}); + 'BaseTransaction: invalid Memos', + ) + }) +}) diff --git a/test/models/checkCancel.ts b/test/models/checkCancel.ts index 2a58df00..532e2151 100644 --- a/test/models/checkCancel.ts +++ b/test/models/checkCancel.ts @@ -1,37 +1,37 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyCheckCancel } from "../../src/models/transactions/checkCancel"; +import { verifyCheckCancel } from '../../src/models/transactions/checkCancel' /** * CheckCancel Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("CheckCancel", function () { +describe('CheckCancel', function () { it(`verifies valid CheckCancel`, function () { const validCheckCancel = { - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - TransactionType: "CheckCancel", + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + TransactionType: 'CheckCancel', CheckID: - "49647F0D748DC3FE26BDACBC57F251AADEFFF391403EC9BF87C97F67E9977FB0", - } as any; + '49647F0D748DC3FE26BDACBC57F251AADEFFF391403EC9BF87C97F67E9977FB0', + } as any - assert.doesNotThrow(() => verifyCheckCancel(validCheckCancel)); - }); + assert.doesNotThrow(() => verifyCheckCancel(validCheckCancel)) + }) it(`throws w/ invalid CheckCancel`, function () { const invalidCheckID = { - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - TransactionType: "CheckCancel", + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + TransactionType: 'CheckCancel', CheckID: 4964734566545678, - } as any; + } as any assert.throws( () => verifyCheckCancel(invalidCheckID), ValidationError, - "CheckCancel: invalid CheckID" - ); - }); -}); + 'CheckCancel: invalid CheckID', + ) + }) +}) diff --git a/test/models/checkCash.ts b/test/models/checkCash.ts index 8e1b2dd2..86860798 100644 --- a/test/models/checkCash.ts +++ b/test/models/checkCash.ts @@ -1,89 +1,89 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyCheckCash } from "../../src/models/transactions/checkCash"; +import { verifyCheckCash } from '../../src/models/transactions/checkCash' /** * CheckCash Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("CheckCash", function () { +describe('CheckCash', function () { it(`verifies valid CheckCash`, function () { const validCheckCash = { - Account: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - TransactionType: "CheckCash", - Amount: "100000000", + Account: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + TransactionType: 'CheckCash', + Amount: '100000000', CheckID: - "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334", - Fee: "12", - } as any; + '838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334', + Fee: '12', + } as any - assert.doesNotThrow(() => verifyCheckCash(validCheckCash)); - }); + assert.doesNotThrow(() => verifyCheckCash(validCheckCash)) + }) it(`throws w/ invalid CheckID`, function () { const invalidCheckID = { - Account: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - TransactionType: "CheckCash", - Amount: "100000000", + Account: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + TransactionType: 'CheckCash', + Amount: '100000000', CheckID: 83876645678567890, - } as any; + } as any assert.throws( () => verifyCheckCash(invalidCheckID), ValidationError, - "CheckCash: invalid CheckID" - ); - }); + 'CheckCash: invalid CheckID', + ) + }) it(`throws w/ invalid Amount`, function () { const invalidAmount = { - Account: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - TransactionType: "CheckCash", + Account: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + TransactionType: 'CheckCash', Amount: 100000000, CheckID: - "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334", - } as any; + '838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334', + } as any assert.throws( () => verifyCheckCash(invalidAmount), ValidationError, - "CheckCash: invalid Amount" - ); - }); + 'CheckCash: invalid Amount', + ) + }) it(`throws w/ having both Amount and DeliverMin`, function () { const invalidDeliverMin = { - Account: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - TransactionType: "CheckCash", - Amount: "100000000", + Account: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + TransactionType: 'CheckCash', + Amount: '100000000', DeliverMin: 852156963, CheckID: - "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334", - } as any; + '838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334', + } as any assert.throws( () => verifyCheckCash(invalidDeliverMin), ValidationError, - "CheckCash: cannot have both Amount and DeliverMin" - ); - }); + 'CheckCash: cannot have both Amount and DeliverMin', + ) + }) it(`throws w/ invalid DeliverMin`, function () { const invalidDeliverMin = { - Account: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - TransactionType: "CheckCash", + Account: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + TransactionType: 'CheckCash', DeliverMin: 852156963, CheckID: - "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334", - } as any; + '838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334', + } as any assert.throws( () => verifyCheckCash(invalidDeliverMin), ValidationError, - "CheckCash: invalid DeliverMin" - ); - }); -}); + 'CheckCash: invalid DeliverMin', + ) + }) +}) diff --git a/test/models/checkCreate.ts b/test/models/checkCreate.ts index 54040db7..2174e083 100644 --- a/test/models/checkCreate.ts +++ b/test/models/checkCreate.ts @@ -1,127 +1,127 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyCheckCreate } from "../../src/models/transactions/checkCreate"; +import { verifyCheckCreate } from '../../src/models/transactions/checkCreate' /** * CheckCreate Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("CheckCreate", function () { +describe('CheckCreate', function () { it(`verifies valid CheckCreate`, function () { const validCheck = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - SendMax: "100000000", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + SendMax: '100000000', Expiration: 570113521, InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', DestinationTag: 1, - Fee: "12", - } as any; + Fee: '12', + } as any - assert.doesNotThrow(() => verifyCheckCreate(validCheck)); - }); + assert.doesNotThrow(() => verifyCheckCreate(validCheck)) + }) it(`throws w/ invalid Destination`, function () { const invalidDestination = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', Destination: 7896214789632154, - SendMax: "100000000", + SendMax: '100000000', Expiration: 570113521, InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', DestinationTag: 1, - Fee: "12", - } as any; + Fee: '12', + } as any assert.throws( () => verifyCheckCreate(invalidDestination), ValidationError, - "CheckCreate: invalid Destination" - ); - }); + 'CheckCreate: invalid Destination', + ) + }) it(`throws w/ invalid SendMax`, function () { const invalidSendMax = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', SendMax: 100000000, Expiration: 570113521, InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', DestinationTag: 1, - Fee: "12", - } as any; + Fee: '12', + } as any assert.throws( () => verifyCheckCreate(invalidSendMax), ValidationError, - "CheckCreate: invalid SendMax" - ); - }); + 'CheckCreate: invalid SendMax', + ) + }) it(`throws w/ invalid DestinationTag`, function () { const invalidDestinationTag = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - SendMax: "100000000", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + SendMax: '100000000', Expiration: 570113521, InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", - DestinationTag: "1", - Fee: "12", - } as any; + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', + DestinationTag: '1', + Fee: '12', + } as any assert.throws( () => verifyCheckCreate(invalidDestinationTag), ValidationError, - "CheckCreate: invalid DestinationTag" - ); - }); + 'CheckCreate: invalid DestinationTag', + ) + }) it(`throws w/ invalid Expiration`, function () { const invalidExpiration = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - SendMax: "100000000", - Expiration: "570113521", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + SendMax: '100000000', + Expiration: '570113521', InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', DestinationTag: 1, - Fee: "12", - } as any; + Fee: '12', + } as any assert.throws( () => verifyCheckCreate(invalidExpiration), ValidationError, - "CheckCreate: invalid Expiration" - ); - }); + 'CheckCreate: invalid Expiration', + ) + }) it(`throws w/ invalid InvoiceID`, function () { const invalidInvoiceID = { - TransactionType: "CheckCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", - SendMax: "100000000", + TransactionType: 'CheckCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', + SendMax: '100000000', Expiration: 570113521, InvoiceID: 789656963258531, DestinationTag: 1, - Fee: "12", - } as any; + Fee: '12', + } as any assert.throws( () => verifyCheckCreate(invalidInvoiceID), ValidationError, - "CheckCreate: invalid InvoiceID" - ); - }); -}); + 'CheckCreate: invalid InvoiceID', + ) + }) +}) diff --git a/test/models/depositPreauth.ts b/test/models/depositPreauth.ts index 12bcd50e..22830b9f 100644 --- a/test/models/depositPreauth.ts +++ b/test/models/depositPreauth.ts @@ -1,85 +1,85 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyDepositPreauth } from "../../src/models/transactions/depositPreauth"; +import { verifyDepositPreauth } from '../../src/models/transactions/depositPreauth' /** * DepositPreauth Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("DepositPreauth", function () { - let depositPreauth; +describe('DepositPreauth', function () { + let depositPreauth beforeEach(function () { depositPreauth = { - TransactionType: "DepositPreauth", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - } as any; - }); + TransactionType: 'DepositPreauth', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + } as any + }) - it("verifies valid DepositPreauth when only Authorize is provided", function () { - depositPreauth.Authorize = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; - assert.doesNotThrow(() => verifyDepositPreauth(depositPreauth)); - }); + it('verifies valid DepositPreauth when only Authorize is provided', function () { + depositPreauth.Authorize = 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW' + assert.doesNotThrow(() => verifyDepositPreauth(depositPreauth)) + }) - it("verifies valid DepositPreauth when only Unauthorize is provided", function () { - depositPreauth.Unauthorize = "raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n"; - assert.doesNotThrow(() => verifyDepositPreauth(depositPreauth)); - }); + it('verifies valid DepositPreauth when only Unauthorize is provided', function () { + depositPreauth.Unauthorize = 'raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n' + assert.doesNotThrow(() => verifyDepositPreauth(depositPreauth)) + }) - it("throws when both Authorize and Unauthorize are provided", function () { - depositPreauth.Authorize = "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW"; - depositPreauth.Unauthorize = "raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n"; + it('throws when both Authorize and Unauthorize are provided', function () { + depositPreauth.Authorize = 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW' + depositPreauth.Unauthorize = 'raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n' assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: can't provide both Authorize and Unauthorize fields" - ); - }); + "DepositPreauth: can't provide both Authorize and Unauthorize fields", + ) + }) - it("throws when neither Authorize nor Unauthorize are provided", function () { + it('throws when neither Authorize nor Unauthorize are provided', function () { assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: must provide either Authorize or Unauthorize field" - ); - }); + 'DepositPreauth: must provide either Authorize or Unauthorize field', + ) + }) - it("throws when Authorize is not a string", function () { - depositPreauth.Authorize = 1234; + it('throws when Authorize is not a string', function () { + depositPreauth.Authorize = 1234 assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: Authorize must be a string" - ); - }); + 'DepositPreauth: Authorize must be a string', + ) + }) - it("throws when an Account attempts to preauthorize its own address", function () { - depositPreauth.Authorize = depositPreauth.Account; + it('throws when an Account attempts to preauthorize its own address', function () { + depositPreauth.Authorize = depositPreauth.Account assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: Account can't preauthorize its own address" - ); - }); + "DepositPreauth: Account can't preauthorize its own address", + ) + }) - it("throws when Unauthorize is not a string", function () { - depositPreauth.Unauthorize = 1234; + it('throws when Unauthorize is not a string', function () { + depositPreauth.Unauthorize = 1234 assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: Unauthorize must be a string" - ); - }); + 'DepositPreauth: Unauthorize must be a string', + ) + }) - it("throws when an Account attempts to unauthorize its own address", function () { - depositPreauth.Unauthorize = depositPreauth.Account; + it('throws when an Account attempts to unauthorize its own address', function () { + depositPreauth.Unauthorize = depositPreauth.Account assert.throws( () => verifyDepositPreauth(depositPreauth), ValidationError, - "DepositPreauth: Account can't unauthorize its own address" - ); - }); -}); + "DepositPreauth: Account can't unauthorize its own address", + ) + }) +}) diff --git a/test/models/escrowCancel.ts b/test/models/escrowCancel.ts index 46f1418a..9a1a115d 100644 --- a/test/models/escrowCancel.ts +++ b/test/models/escrowCancel.ts @@ -1,66 +1,66 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "../../src/common/errors"; -import { verifyEscrowCancel } from "../../src/models/transactions/escrowCancel"; +import { ValidationError } from '../../src/common/errors' +import { verifyEscrowCancel } from '../../src/models/transactions/escrowCancel' /** * Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("EscrowCancel", function () { - let cancel; +describe('EscrowCancel', function () { + let cancel beforeEach(function () { cancel = { - TransactionType: "EscrowCancel", - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - Owner: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", + TransactionType: 'EscrowCancel', + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + Owner: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', OfferSequence: 7, - }; - }); + } + }) it(`Valid EscrowCancel`, function () { - assert.doesNotThrow(() => verifyEscrowCancel(cancel)); - }); + assert.doesNotThrow(() => verifyEscrowCancel(cancel)) + }) it(`Invalid EscrowCancel missing owner`, function () { - delete cancel.Owner; + delete cancel.Owner assert.throws( () => verifyEscrowCancel(cancel), ValidationError, - "EscrowCancel: missing Owner" - ); - }); + 'EscrowCancel: missing Owner', + ) + }) it(`Invalid EscrowCancel missing offerSequence`, function () { - delete cancel.OfferSequence; + delete cancel.OfferSequence assert.throws( () => verifyEscrowCancel(cancel), ValidationError, - "EscrowCancel: missing OfferSequence" - ); - }); + 'EscrowCancel: missing OfferSequence', + ) + }) it(`Invalid OfferSequence`, function () { - cancel.Owner = 10; + cancel.Owner = 10 assert.throws( () => verifyEscrowCancel(cancel), ValidationError, - "EscrowCancel: Owner must be a string" - ); - }); + 'EscrowCancel: Owner must be a string', + ) + }) it(`Invalid owner`, function () { - cancel.OfferSequence = "10"; + cancel.OfferSequence = '10' assert.throws( () => verifyEscrowCancel(cancel), ValidationError, - "EscrowCancel: OfferSequence must be a number" - ); - }); -}); + 'EscrowCancel: OfferSequence must be a number', + ) + }) +}) diff --git a/test/models/escrowCreate.ts b/test/models/escrowCreate.ts index d838fbc5..606f7c37 100644 --- a/test/models/escrowCreate.ts +++ b/test/models/escrowCreate.ts @@ -1,135 +1,135 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyEscrowCreate } from "../../src/models/transactions/escrowCreate"; +import { verifyEscrowCreate } from '../../src/models/transactions/escrowCreate' /** * EscrowCreate Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("EscrowCreate", function () { - let escrow; +describe('EscrowCreate', function () { + let escrow beforeEach(function () { escrow = { - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - TransactionType: "EscrowCreate", - Amount: "10000", - Destination: "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW", + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + TransactionType: 'EscrowCreate', + Amount: '10000', + Destination: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', CancelAfter: 533257958, FinishAfter: 533171558, Condition: - "A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100", + 'A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100', DestinationTag: 23480, SourceTag: 11747, - }; - }); + } + }) it(`verifies valid EscrowCreate`, function () { - assert.doesNotThrow(() => verifyEscrowCreate(escrow)); - }); + assert.doesNotThrow(() => verifyEscrowCreate(escrow)) + }) it(`Missing amount`, function () { - delete escrow.Amount; + delete escrow.Amount assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: missing field Amount" - ); - }); + 'EscrowCreate: missing field Amount', + ) + }) it(`Missing destination`, function () { - delete escrow.Destination; + delete escrow.Destination assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: missing field Destination" - ); - }); + 'EscrowCreate: missing field Destination', + ) + }) it(`throws w/ invalid Destination`, function () { - escrow.Destination = 10; + escrow.Destination = 10 assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: Destination must be a string" - ); - }); + 'EscrowCreate: Destination must be a string', + ) + }) it(`throws w/ invalid Amount`, function () { - escrow.Amount = 1000; + escrow.Amount = 1000 assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: Amount must be a string" - ); - }); + 'EscrowCreate: Amount must be a string', + ) + }) it(`invalid CancelAfter`, function () { - escrow.CancelAfter = "100"; + escrow.CancelAfter = '100' assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: CancelAfter must be a number" - ); - }); + 'EscrowCreate: CancelAfter must be a number', + ) + }) it(`invalid FinishAfter`, function () { - escrow.FinishAfter = "1000"; + escrow.FinishAfter = '1000' assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: FinishAfter must be a number" - ); - }); + 'EscrowCreate: FinishAfter must be a number', + ) + }) it(`invalid Condition`, function () { - escrow.Condition = 0x141243; + escrow.Condition = 0x141243 assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: Condition must be a string" - ); - }); + 'EscrowCreate: Condition must be a string', + ) + }) it(`invalid DestinationTag`, function () { - escrow.DestinationTag = "100"; + escrow.DestinationTag = '100' assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: DestinationTag must be a number" - ); - }); + 'EscrowCreate: DestinationTag must be a number', + ) + }) it(`Missing both CancelAfter and FinishAfter`, function () { - delete escrow.CancelAfter; - delete escrow.FinishAfter; + delete escrow.CancelAfter + delete escrow.FinishAfter assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: Either CancelAfter or FinishAfter must be specified" - ); - }); + 'EscrowCreate: Either CancelAfter or FinishAfter must be specified', + ) + }) it(`Missing both Condition and FinishAfter`, function () { - delete escrow.Condition; - delete escrow.FinishAfter; + delete escrow.Condition + delete escrow.FinishAfter assert.throws( () => verifyEscrowCreate(escrow), ValidationError, - "EscrowCreate: Either Condition or FinishAfter must be specified" - ); - }); -}); + 'EscrowCreate: Either Condition or FinishAfter must be specified', + ) + }) +}) diff --git a/test/models/escrowFinish.ts b/test/models/escrowFinish.ts index 6ac04313..5525e451 100644 --- a/test/models/escrowFinish.ts +++ b/test/models/escrowFinish.ts @@ -1,76 +1,76 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyEscrowFinish } from "../../src/models/transactions/escrowFinish"; +import { verifyEscrowFinish } from '../../src/models/transactions/escrowFinish' /** * EscrowFinish Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("EscrowFinish", function () { - let escrow; +describe('EscrowFinish', function () { + let escrow beforeEach(function () { escrow = { - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - TransactionType: "EscrowFinish", - Owner: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + TransactionType: 'EscrowFinish', + Owner: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', OfferSequence: 7, Condition: - "A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100", - Fulfillment: "A0028000", - }; - }); + 'A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100', + Fulfillment: 'A0028000', + } + }) it(`verifies valid EscrowFinish`, function () { - assert.doesNotThrow(() => verifyEscrowFinish(escrow)); - }); + assert.doesNotThrow(() => verifyEscrowFinish(escrow)) + }) it(`verifies valid EscrowFinish w/o optional`, function () { - delete escrow.Condition; - delete escrow.Fulfillment; + delete escrow.Condition + delete escrow.Fulfillment - assert.doesNotThrow(() => verifyEscrowFinish(escrow)); - }); + assert.doesNotThrow(() => verifyEscrowFinish(escrow)) + }) it(`throws w/ invalid Owner`, function () { - escrow.Owner = 0x15415253; + escrow.Owner = 0x15415253 assert.throws( () => verifyEscrowFinish(escrow), ValidationError, - "EscrowFinish: Owner must be a string" - ); - }); + 'EscrowFinish: Owner must be a string', + ) + }) it(`throws w/ invalid OfferSequence`, function () { - escrow.OfferSequence = "10"; + escrow.OfferSequence = '10' assert.throws( () => verifyEscrowFinish(escrow), ValidationError, - "EscrowFinish: OfferSequence must be a number" - ); - }); + 'EscrowFinish: OfferSequence must be a number', + ) + }) it(`throws w/ invalid Condition`, function () { - escrow.Condition = 10; + escrow.Condition = 10 assert.throws( () => verifyEscrowFinish(escrow), ValidationError, - "EscrowFinish: Condition must be a string" - ); - }); + 'EscrowFinish: Condition must be a string', + ) + }) it(`throws w/ invalid Fulfillment`, function () { - escrow.Fulfillment = 0x142341; + escrow.Fulfillment = 0x142341 assert.throws( () => verifyEscrowFinish(escrow), ValidationError, - "EscrowFinish: Fulfillment must be a string" - ); - }); -}); + 'EscrowFinish: Fulfillment must be a string', + ) + }) +}) diff --git a/test/models/offerCancel.ts b/test/models/offerCancel.ts index 909a5b28..318e5694 100644 --- a/test/models/offerCancel.ts +++ b/test/models/offerCancel.ts @@ -1,57 +1,57 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyOfferCancel } from "../../src/models/transactions/offerCancel"; +import { verifyOfferCancel } from '../../src/models/transactions/offerCancel' /** * OfferCancel Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("OfferCancel", function () { - let offer; +describe('OfferCancel', function () { + let offer beforeEach(function () { offer = { - Account: "rnKiczmiQkZFiDES8THYyLA2pQohC5C6EF", - Fee: "10", + Account: 'rnKiczmiQkZFiDES8THYyLA2pQohC5C6EF', + Fee: '10', LastLedgerSequence: 65477334, OfferSequence: 60797528, Sequence: 60797535, SigningPubKey: - "0361BFD43D1EEA54B77CC152887312949EBF052997FBFFCDAF6F2653164B55B21...", - TransactionType: "OfferCancel", + '0361BFD43D1EEA54B77CC152887312949EBF052997FBFFCDAF6F2653164B55B21...', + TransactionType: 'OfferCancel', TxnSignature: - "30450221008C43BDCFC68B4793857CA47DF454C07E5B45D3F80E8E6785CAB9292...", - date: "2021-08-06T21:04:11Z", - } as any; - }); + '30450221008C43BDCFC68B4793857CA47DF454C07E5B45D3F80E8E6785CAB9292...', + date: '2021-08-06T21:04:11Z', + } as any + }) it(`verifies valid OfferCancel`, function () { - assert.doesNotThrow(() => verifyOfferCancel(offer)); - }); + assert.doesNotThrow(() => verifyOfferCancel(offer)) + }) it(`verifies valid OfferCancel with flags`, function () { - offer.Flags = 2147483648; - assert.doesNotThrow(() => verifyOfferCancel(offer)); - }); + offer.Flags = 2147483648 + assert.doesNotThrow(() => verifyOfferCancel(offer)) + }) it(`throws w/ OfferSequence must be a number`, function () { - offer.OfferSequence = "99"; + offer.OfferSequence = '99' assert.throws( () => verifyOfferCancel(offer), ValidationError, - "OfferCancel: OfferSequence must be a number" - ); - }); + 'OfferCancel: OfferSequence must be a number', + ) + }) it(`throws w/ missing OfferSequence`, function () { - delete offer.OfferSequence; + delete offer.OfferSequence assert.throws( () => verifyOfferCancel(offer), ValidationError, - "OfferCancel: missing field OfferSequence" - ); - }); -}); + 'OfferCancel: missing field OfferSequence', + ) + }) +}) diff --git a/test/models/offerCreate.ts b/test/models/offerCreate.ts index 87e8fed2..394d4a12 100644 --- a/test/models/offerCreate.ts +++ b/test/models/offerCreate.ts @@ -1,191 +1,191 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyOfferCreate } from "../../src/models/transactions/offerCreate"; +import { verifyOfferCreate } from '../../src/models/transactions/offerCreate' /** * OfferCreate Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("OfferCreate", function () { +describe('OfferCreate', function () { it(`verifies valid OfferCreate`, function () { const offer = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', Expiration: 10, OfferSequence: 12, TakerGets: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TakerPays: "12928290425", - TransactionType: "OfferCreate", + TakerPays: '12928290425', + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any - assert.doesNotThrow(() => verifyOfferCreate(offer)); + assert.doesNotThrow(() => verifyOfferCreate(offer)) const offer2 = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", - TakerGets: "12928290425", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', + TakerGets: '12928290425', TakerPays: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any - assert.doesNotThrow(() => verifyOfferCreate(offer2)); + assert.doesNotThrow(() => verifyOfferCreate(offer2)) const offer3 = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', TakerGets: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, TakerPays: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any - assert.doesNotThrow(() => verifyOfferCreate(offer3)); - }); + assert.doesNotThrow(() => verifyOfferCreate(offer3)) + }) it(`throws w/ invalid Expiration`, function () { const offer = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", - Expiration: "11", - TakerGets: "12928290425", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', + Expiration: '11', + TakerGets: '12928290425', TakerPays: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any assert.throws( () => verifyOfferCreate(offer), ValidationError, - "OfferCreate: invalid Expiration" - ); - }); + 'OfferCreate: invalid Expiration', + ) + }) it(`throws w/ invalid OfferSequence`, function () { const offer = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", - OfferSequence: "11", - TakerGets: "12928290425", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', + OfferSequence: '11', + TakerGets: '12928290425', TakerPays: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any assert.throws( () => verifyOfferCreate(offer), ValidationError, - "OfferCreate: invalid OfferSequence" - ); - }); + 'OfferCreate: invalid OfferSequence', + ) + }) it(`throws w/ invalid TakerPays`, function () { const offer = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", - OfferSequence: "11", - TakerGets: "12928290425", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', + OfferSequence: '11', + TakerGets: '12928290425', TakerPays: 10, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any assert.throws( () => verifyOfferCreate(offer), ValidationError, - "OfferCreate: invalid TakerPays" - ); - }); + 'OfferCreate: invalid TakerPays', + ) + }) it(`throws w/ invalid TakerGets`, function () { const offer = { - Account: "r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W", - Fee: "10", + Account: 'r3rhWeE31Jt5sWmi4QiGLMZnY3ENgqw96W', + Fee: '10', Flags: 0, LastLedgerSequence: 65453019, Sequence: 40949322, SigningPubKey: - "03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22", - OfferSequence: "11", + '03C48299E57F5AE7C2BE1391B581D313F1967EA2301628C07AC412092FDC15BA22', + OfferSequence: '11', TakerGets: 11, TakerPays: { - currency: "DSH", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "43.11584856965009", + currency: 'DSH', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '43.11584856965009', }, - TransactionType: "OfferCreate", + TransactionType: 'OfferCreate', TxnSignature: - "3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91", - } as any; + '3045022100D874CDDD6BB24ED66E83B1D3574D3ECAC753A78F26DB7EBA89EAB8E7D72B95F802207C8CCD6CEA64E4AE2014E59EE9654E02CA8F03FE7FCE0539E958EAE182234D91', + } as any assert.throws( () => verifyOfferCreate(offer), ValidationError, - "OfferCreate: invalid TakerGets" - ); - }); -}); + 'OfferCreate: invalid TakerGets', + ) + }) +}) diff --git a/test/models/payment.ts b/test/models/payment.ts index 2801ac90..e3b89ba7 100644 --- a/test/models/payment.ts +++ b/test/models/payment.ts @@ -1,138 +1,138 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' import { PaymentTransactionFlagsEnum, verifyPayment, -} from "../../src/models/transactions/payment"; +} from '../../src/models/transactions/payment' /** * PaymentTransaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("Payment", function () { - let paymentTransaction; +describe('Payment', function () { + let paymentTransaction beforeEach(function () { paymentTransaction = { - TransactionType: "Payment", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", - Amount: "1234", - Destination: "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy", + TransactionType: 'Payment', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', + Amount: '1234', + Destination: 'rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy', DestinationTag: 1, InvoiceID: - "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B", - Paths: [[{ currency: "BTC", issuer: "apsoeijf90wp34fh" }]], - SendMax: "100000000", - } as any; - }); + '6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B', + Paths: [[{ currency: 'BTC', issuer: 'apsoeijf90wp34fh' }]], + SendMax: '100000000', + } as any + }) it(`verifies valid PaymentTransaction`, function () { - assert.doesNotThrow(() => verifyPayment(paymentTransaction)); - }); + assert.doesNotThrow(() => verifyPayment(paymentTransaction)) + }) it(`throws when Amount is missing`, function () { - delete paymentTransaction.Amount; + delete paymentTransaction.Amount assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: missing field Amount" - ); - }); + 'PaymentTransaction: missing field Amount', + ) + }) it(`throws when Amount is invalid`, function () { - paymentTransaction.Amount = 1234; + paymentTransaction.Amount = 1234 assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: invalid Amount" - ); - }); + 'PaymentTransaction: invalid Amount', + ) + }) it(`throws when Destination is missing`, function () { - delete paymentTransaction.Destination; + delete paymentTransaction.Destination assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: missing field Destination" - ); - }); + 'PaymentTransaction: missing field Destination', + ) + }) it(`throws when Destination is invalid`, function () { - paymentTransaction.Destination = 7896214; + paymentTransaction.Destination = 7896214 assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: invalid Destination" - ); - }); + 'PaymentTransaction: invalid Destination', + ) + }) it(`throws when DestinationTag is not a number`, function () { - paymentTransaction.DestinationTag = "1"; + paymentTransaction.DestinationTag = '1' assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: DestinationTag must be a number" - ); - }); + 'PaymentTransaction: DestinationTag must be a number', + ) + }) it(`throws when InvoiceID is not a string`, function () { - paymentTransaction.InvoiceID = 19832; + paymentTransaction.InvoiceID = 19832 assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: InvoiceID must be a string" - ); - }); + 'PaymentTransaction: InvoiceID must be a string', + ) + }) it(`throws when Paths is invalid`, function () { - paymentTransaction.Paths = [[{ account: 123 }]]; + paymentTransaction.Paths = [[{ account: 123 }]] assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: invalid Paths" - ); - }); + 'PaymentTransaction: invalid Paths', + ) + }) it(`throws when SendMax is invalid`, function () { - paymentTransaction.SendMax = 100000000; + paymentTransaction.SendMax = 100000000 assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: invalid SendMax" - ); - }); + 'PaymentTransaction: invalid SendMax', + ) + }) it(`verifies valid DeliverMin with tfPartialPayment flag set as a number`, function () { - paymentTransaction.DeliverMin = "10000"; - paymentTransaction.Flags = PaymentTransactionFlagsEnum.tfPartialPayment; - assert.doesNotThrow(() => verifyPayment(paymentTransaction)); - }); + paymentTransaction.DeliverMin = '10000' + paymentTransaction.Flags = PaymentTransactionFlagsEnum.tfPartialPayment + assert.doesNotThrow(() => verifyPayment(paymentTransaction)) + }) it(`verifies valid DeliverMin with tfPartialPayment flag set as a boolean`, function () { - paymentTransaction.DeliverMin = "10000"; - paymentTransaction.Flags = { tfPartialPayment: true }; - assert.doesNotThrow(() => verifyPayment(paymentTransaction)); - }); + paymentTransaction.DeliverMin = '10000' + paymentTransaction.Flags = { tfPartialPayment: true } + assert.doesNotThrow(() => verifyPayment(paymentTransaction)) + }) it(`throws when DeliverMin is invalid`, function () { - paymentTransaction.DeliverMin = 10000; - paymentTransaction.Flags = { tfPartialPayment: true }; + paymentTransaction.DeliverMin = 10000 + paymentTransaction.Flags = { tfPartialPayment: true } assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: invalid DeliverMin" - ); - }); + 'PaymentTransaction: invalid DeliverMin', + ) + }) it(`throws when tfPartialPayment flag is missing with valid DeliverMin`, function () { - paymentTransaction.DeliverMin = "10000"; + paymentTransaction.DeliverMin = '10000' assert.throws( () => verifyPayment(paymentTransaction), ValidationError, - "PaymentTransaction: tfPartialPayment flag required with DeliverMin" - ); - }); -}); + 'PaymentTransaction: tfPartialPayment flag required with DeliverMin', + ) + }) +}) diff --git a/test/models/paymentChannelClaim.ts b/test/models/paymentChannelClaim.ts index a7fa0544..248fbecd 100644 --- a/test/models/paymentChannelClaim.ts +++ b/test/models/paymentChannelClaim.ts @@ -1,102 +1,102 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyPaymentChannelClaim } from "../../src/models/transactions/paymentChannelClaim"; +import { verifyPaymentChannelClaim } from '../../src/models/transactions/paymentChannelClaim' /** * PaymentChannelClaim Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("PaymentChannelClaim", function () { - let channel; +describe('PaymentChannelClaim', function () { + let channel beforeEach(function () { channel = { - Account: "r...", - TransactionType: "PaymentChannelClaim", + Account: 'r...', + TransactionType: 'PaymentChannelClaim', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Balance: "1000000", - Amount: "1000000", + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Balance: '1000000', + Amount: '1000000', Signature: - "30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B", + '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B', PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A", - }; - }); + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', + } + }) it(`verifies valid PaymentChannelClaim`, function () { - assert.doesNotThrow(() => verifyPaymentChannelClaim(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelClaim(channel)) + }) it(`verifies valid PaymentChannelClaim w/o optional`, function () { - delete channel.Balance; - delete channel.Amount; - delete channel.Signature; - delete channel.PublicKey; + delete channel.Balance + delete channel.Amount + delete channel.Signature + delete channel.PublicKey - assert.doesNotThrow(() => verifyPaymentChannelClaim(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelClaim(channel)) + }) it(`throws w/ missing Channel`, function () { - delete channel.Channel; + delete channel.Channel assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: missing Channel" - ); - }); + 'PaymentChannelClaim: missing Channel', + ) + }) it(`throws w/ invalid Channel`, function () { - channel.Channel = 100; + channel.Channel = 100 assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: Channel must be a string" - ); - }); + 'PaymentChannelClaim: Channel must be a string', + ) + }) it(`throws w/ invalid Balance`, function () { - channel.Balance = 100; + channel.Balance = 100 assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: Balance must be a string" - ); - }); + 'PaymentChannelClaim: Balance must be a string', + ) + }) it(`throws w/ invalid Amount`, function () { - channel.Amount = 1000; + channel.Amount = 1000 assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: Amount must be a string" - ); - }); + 'PaymentChannelClaim: Amount must be a string', + ) + }) it(`throws w/ invalid Signature`, function () { - channel.Signature = 1000; + channel.Signature = 1000 assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: Signature must be a string" - ); - }); + 'PaymentChannelClaim: Signature must be a string', + ) + }) it(`throws w/ invalid PublicKey`, function () { - channel.PublicKey = ["100000"]; + channel.PublicKey = ['100000'] assert.throws( () => verifyPaymentChannelClaim(channel), ValidationError, - "PaymentChannelClaim: PublicKey must be a string" - ); - }); -}); + 'PaymentChannelClaim: PublicKey must be a string', + ) + }) +}) diff --git a/test/models/paymentChannelCreate.ts b/test/models/paymentChannelCreate.ts index c481b58d..6768f7f5 100644 --- a/test/models/paymentChannelCreate.ts +++ b/test/models/paymentChannelCreate.ts @@ -1,141 +1,141 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyPaymentChannelCreate } from "../../src/models/transactions/paymentChannelCreate"; +import { verifyPaymentChannelCreate } from '../../src/models/transactions/paymentChannelCreate' /** * PaymentChannelCreate Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("PaymentChannelCreate", function () { - let channel; +describe('PaymentChannelCreate', function () { + let channel beforeEach(function () { channel = { - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - TransactionType: "PaymentChannelCreate", - Amount: "10000", - Destination: "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW", + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + TransactionType: 'PaymentChannelCreate', + Amount: '10000', + Destination: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', SettleDelay: 86400, PublicKey: - "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A", + '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', CancelAfter: 533171558, DestinationTag: 23480, SourceTag: 11747, - }; - }); + } + }) it(`verifies valid PaymentChannelCreate`, function () { - assert.doesNotThrow(() => verifyPaymentChannelCreate(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelCreate(channel)) + }) it(`verifies valid PaymentChannelCreate w/o optional`, function () { - delete channel.CancelAfter; - delete channel.DestinationTag; - delete channel.SourceTag; + delete channel.CancelAfter + delete channel.DestinationTag + delete channel.SourceTag - assert.doesNotThrow(() => verifyPaymentChannelCreate(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelCreate(channel)) + }) it(`missing Amount`, function () { - delete channel.Amount; + delete channel.Amount assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: missing Amount" - ); - }); + 'PaymentChannelCreate: missing Amount', + ) + }) it(`missing Destination`, function () { - delete channel.Destination; + delete channel.Destination assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: missing Destination" - ); - }); + 'PaymentChannelCreate: missing Destination', + ) + }) it(`missing SettleDelay`, function () { - delete channel.SettleDelay; + delete channel.SettleDelay assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: missing SettleDelay" - ); - }); + 'PaymentChannelCreate: missing SettleDelay', + ) + }) it(`missing PublicKey`, function () { - delete channel.PublicKey; + delete channel.PublicKey assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: missing PublicKey" - ); - }); + 'PaymentChannelCreate: missing PublicKey', + ) + }) it(`invalid Amount`, function () { - channel.Amount = 1000; + channel.Amount = 1000 assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: Amount must be a string" - ); - }); + 'PaymentChannelCreate: Amount must be a string', + ) + }) it(`invalid Destination`, function () { - channel.Destination = 10; + channel.Destination = 10 assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: Destination must be a string" - ); - }); + 'PaymentChannelCreate: Destination must be a string', + ) + }) it(`invalid SettleDelay`, function () { - channel.SettleDelay = "10"; + channel.SettleDelay = '10' assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: SettleDelay must be a number" - ); - }); + 'PaymentChannelCreate: SettleDelay must be a number', + ) + }) it(`invalid PublicKey`, function () { - channel.PublicKey = 10; + channel.PublicKey = 10 assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: PublicKey must be a string" - ); - }); + 'PaymentChannelCreate: PublicKey must be a string', + ) + }) it(`invalid DestinationTag`, function () { - channel.DestinationTag = "10"; + channel.DestinationTag = '10' assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: DestinationTag must be a number" - ); - }); + 'PaymentChannelCreate: DestinationTag must be a number', + ) + }) it(`invalid CancelAfter`, function () { - channel.CancelAfter = "100"; + channel.CancelAfter = '100' assert.throws( () => verifyPaymentChannelCreate(channel), ValidationError, - "PaymentChannelCreate: CancelAfter must be a number" - ); - }); -}); + 'PaymentChannelCreate: CancelAfter must be a number', + ) + }) +}) diff --git a/test/models/paymentChannelFund.ts b/test/models/paymentChannelFund.ts index 6050a896..39af86af 100644 --- a/test/models/paymentChannelFund.ts +++ b/test/models/paymentChannelFund.ts @@ -1,85 +1,85 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyPaymentChannelFund } from "../../src/models/transactions/paymentChannelFund"; +import { verifyPaymentChannelFund } from '../../src/models/transactions/paymentChannelFund' /** * PaymentChannelFund Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("PaymentChannelFund", function () { - let channel; +describe('PaymentChannelFund', function () { + let channel beforeEach(function () { channel = { - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - TransactionType: "PaymentChannelFund", + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + TransactionType: 'PaymentChannelFund', Channel: - "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198", - Amount: "200000", + 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', + Amount: '200000', Expiration: 543171558, - }; - }); + } + }) it(`verifies valid PaymentChannelFund`, function () { - assert.doesNotThrow(() => verifyPaymentChannelFund(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelFund(channel)) + }) it(`verifies valid PaymentChannelFund w/o optional`, function () { - delete channel.Expiration; + delete channel.Expiration - assert.doesNotThrow(() => verifyPaymentChannelFund(channel)); - }); + assert.doesNotThrow(() => verifyPaymentChannelFund(channel)) + }) it(`throws w/ missing Amount`, function () { - delete channel.Amount; + delete channel.Amount assert.throws( () => verifyPaymentChannelFund(channel), ValidationError, - "PaymentChannelFund: missing Amount" - ); - }); + 'PaymentChannelFund: missing Amount', + ) + }) it(`throws w/ missing Channel`, function () { - delete channel.Channel; + delete channel.Channel assert.throws( () => verifyPaymentChannelFund(channel), ValidationError, - "PaymentChannelFund: missing Channel" - ); - }); + 'PaymentChannelFund: missing Channel', + ) + }) it(`throws w/ invalid Amount`, function () { - channel.Amount = 100; + channel.Amount = 100 assert.throws( () => verifyPaymentChannelFund(channel), ValidationError, - "PaymentChannelFund: Amount must be a string" - ); - }); + 'PaymentChannelFund: Amount must be a string', + ) + }) it(`throws w/ invalid Channel`, function () { - channel.Channel = 1000; + channel.Channel = 1000 assert.throws( () => verifyPaymentChannelFund(channel), ValidationError, - "PaymentChannelFund: Channel must be a string" - ); - }); + 'PaymentChannelFund: Channel must be a string', + ) + }) it(`throws w/ invalid Expiration`, function () { - channel.Expiration = "1000"; + channel.Expiration = '1000' assert.throws( () => verifyPaymentChannelFund(channel), ValidationError, - "PaymentChannelFund: Expiration must be a number" - ); - }); -}); + 'PaymentChannelFund: Expiration must be a number', + ) + }) +}) diff --git a/test/models/setRegularKey.ts b/test/models/setRegularKey.ts index 5379d7be..4e3e661a 100644 --- a/test/models/setRegularKey.ts +++ b/test/models/setRegularKey.ts @@ -1,43 +1,43 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifySetRegularKey } from "../../src/models/transactions/setRegularKey"; +import { verifySetRegularKey } from '../../src/models/transactions/setRegularKey' /** * SetRegularKey Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("SetRegularKey", function () { - let account; +describe('SetRegularKey', function () { + let account beforeEach(function () { account = { - TransactionType: "SetRegularKey", - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - Fee: "12", + TransactionType: 'SetRegularKey', + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + Fee: '12', Flags: 0, - RegularKey: "rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD", - } as any; - }); + RegularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD', + } as any + }) it(`verifies valid SetRegularKey`, function () { - assert.doesNotThrow(() => verifySetRegularKey(account)); - }); + assert.doesNotThrow(() => verifySetRegularKey(account)) + }) it(`verifies w/o SetRegularKey`, function () { - account.RegularKey = undefined; - assert.doesNotThrow(() => verifySetRegularKey(account)); - }); + account.RegularKey = undefined + assert.doesNotThrow(() => verifySetRegularKey(account)) + }) it(`throws w/ invalid RegularKey`, function () { - account.RegularKey = 12369846963; + account.RegularKey = 12369846963 assert.throws( () => verifySetRegularKey(account), ValidationError, - "SetRegularKey: RegularKey must be a string" - ); - }); -}); + 'SetRegularKey: RegularKey must be a string', + ) + }) +}) diff --git a/test/models/signerListSet.ts b/test/models/signerListSet.ts index feb59071..663ca72d 100644 --- a/test/models/signerListSet.ts +++ b/test/models/signerListSet.ts @@ -1,78 +1,78 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifySignerListSet } from "../../src/models/transactions/signerListSet"; +import { verifySignerListSet } from '../../src/models/transactions/signerListSet' /** * SignerListSet Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("SignerListSet", function () { - let SignerListSetTx; +describe('SignerListSet', function () { + let SignerListSetTx beforeEach(function () { SignerListSetTx = { Flags: 0, - TransactionType: "SignerListSet", - Account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", - Fee: "12", + TransactionType: 'SignerListSet', + Account: 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn', + Fee: '12', SignerQuorum: 3, SignerEntries: [ { SignerEntry: { - Account: "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW", + Account: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', SignerWeight: 2, }, }, { SignerEntry: { - Account: "rUpy3eEg8rqjqfUoLeBnZkscbKbFsKXC3v", + Account: 'rUpy3eEg8rqjqfUoLeBnZkscbKbFsKXC3v', SignerWeight: 1, }, }, { SignerEntry: { - Account: "raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n", + Account: 'raKEEVSGnKSD9Zyvxu4z6Pqpm4ABH8FS6n', SignerWeight: 1, }, }, ], - } as any; - }); + } as any + }) it(`verifies valid SignerListSet`, function () { - assert.doesNotThrow(() => verifySignerListSet(SignerListSetTx)); - }); + assert.doesNotThrow(() => verifySignerListSet(SignerListSetTx)) + }) it(`throws w/ missing SignerQuorum`, function () { - SignerListSetTx.SignerQuorum = undefined; + SignerListSetTx.SignerQuorum = undefined assert.throws( () => verifySignerListSet(SignerListSetTx), ValidationError, - "SignerListSet: missing field SignerQuorum" - ); - }); + 'SignerListSet: missing field SignerQuorum', + ) + }) it(`throws w/ empty SignerEntries`, function () { - SignerListSetTx.SignerEntries = []; + SignerListSetTx.SignerEntries = [] assert.throws( () => verifySignerListSet(SignerListSetTx), ValidationError, - "SignerListSet: need atleast 1 member in SignerEntries" - ); - }); + 'SignerListSet: need atleast 1 member in SignerEntries', + ) + }) it(`throws w/ invalid SignerEntries`, function () { - SignerListSetTx.SignerEntries = "khgfgyhujk"; + SignerListSetTx.SignerEntries = 'khgfgyhujk' assert.throws( () => verifySignerListSet(SignerListSetTx), ValidationError, - "SignerListSet: invalid SignerEntries" - ); - }); -}); + 'SignerListSet: invalid SignerEntries', + ) + }) +}) diff --git a/test/models/ticketCreate.ts b/test/models/ticketCreate.ts index ddf4398e..ffb23451 100644 --- a/test/models/ticketCreate.ts +++ b/test/models/ticketCreate.ts @@ -1,71 +1,71 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyTicketCreate } from "../../src/models/transactions/ticketCreate"; +import { verifyTicketCreate } from '../../src/models/transactions/ticketCreate' /** * TicketCreate Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("TicketCreate", function () { - let ticketCreate; +describe('TicketCreate', function () { + let ticketCreate beforeEach(function () { ticketCreate = { - TransactionType: "TicketCreate", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", + TransactionType: 'TicketCreate', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', TicketCount: 150, - } as any; - }); + } as any + }) - it("verifies valid TicketCreate", function () { - assert.doesNotThrow(() => verifyTicketCreate(ticketCreate)); - }); + it('verifies valid TicketCreate', function () { + assert.doesNotThrow(() => verifyTicketCreate(ticketCreate)) + }) - it("throws when TicketCount is missing", function () { - delete ticketCreate.TicketCount; + it('throws when TicketCount is missing', function () { + delete ticketCreate.TicketCount assert.throws( () => verifyTicketCreate(ticketCreate), ValidationError, - "TicketCreate: missing field TicketCount" - ); - }); + 'TicketCreate: missing field TicketCount', + ) + }) - it("throws when TicketCount is not a number", function () { - ticketCreate.TicketCount = "150"; + it('throws when TicketCount is not a number', function () { + ticketCreate.TicketCount = '150' assert.throws( () => verifyTicketCreate(ticketCreate), ValidationError, - "TicketCreate: TicketCount must be a number" - ); - }); + 'TicketCreate: TicketCount must be a number', + ) + }) - it("throws when TicketCount is not an integer", function () { - ticketCreate.TicketCount = 12.5; + it('throws when TicketCount is not an integer', function () { + ticketCreate.TicketCount = 12.5 assert.throws( () => verifyTicketCreate(ticketCreate), ValidationError, - "TicketCreate: TicketCount must be an integer from 1 to 250" - ); - }); + 'TicketCreate: TicketCount must be an integer from 1 to 250', + ) + }) - it("throws when TicketCount is < 1", function () { - ticketCreate.TicketCount = 0; + it('throws when TicketCount is < 1', function () { + ticketCreate.TicketCount = 0 assert.throws( () => verifyTicketCreate(ticketCreate), ValidationError, - "TicketCreate: TicketCount must be an integer from 1 to 250" - ); - }); + 'TicketCreate: TicketCount must be an integer from 1 to 250', + ) + }) - it("throws when TicketCount is > 250", function () { - ticketCreate.TicketCount = 251; + it('throws when TicketCount is > 250', function () { + ticketCreate.TicketCount = 251 assert.throws( () => verifyTicketCreate(ticketCreate), ValidationError, - "TicketCreate: TicketCount must be an integer from 1 to 250" - ); - }); -}); + 'TicketCreate: TicketCount must be an integer from 1 to 250', + ) + }) +}) diff --git a/test/models/trustSet.ts b/test/models/trustSet.ts index 14fef87e..c5c24a8f 100644 --- a/test/models/trustSet.ts +++ b/test/models/trustSet.ts @@ -1,68 +1,68 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "xrpl-local/common/errors"; +import { ValidationError } from 'xrpl-local/common/errors' -import { verifyTrustSet } from "../../src/models/transactions/trustSet"; +import { verifyTrustSet } from '../../src/models/transactions/trustSet' /** * TrustSet Transaction Verification Testing. * * Providing runtime verification testing for each specific transaction type. */ -describe("TrustSet", function () { - let trustSet; +describe('TrustSet', function () { + let trustSet beforeEach(function () { trustSet = { - TransactionType: "TrustSet", - Account: "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo", + TransactionType: 'TrustSet', + Account: 'rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo', LimitAmount: { - currency: "XRP", - issuer: "rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX", - value: "4329.23", + currency: 'XRP', + issuer: 'rcXY84C4g14iFp6taFXjjQGVeHqSCh9RX', + value: '4329.23', }, QualityIn: 1234, QualityOut: 4321, - } as any; - }); + } as any + }) - it("verifies valid TrustSet", function () { - assert.doesNotThrow(() => verifyTrustSet(trustSet)); - }); + it('verifies valid TrustSet', function () { + assert.doesNotThrow(() => verifyTrustSet(trustSet)) + }) - it("throws when LimitAmount is missing", function () { - delete trustSet.LimitAmount; + it('throws when LimitAmount is missing', function () { + delete trustSet.LimitAmount assert.throws( () => verifyTrustSet(trustSet), ValidationError, - "TrustSet: missing field LimitAmount" - ); - }); + 'TrustSet: missing field LimitAmount', + ) + }) - it("throws when LimitAmount is invalid", function () { - trustSet.LimitAmount = 1234; + it('throws when LimitAmount is invalid', function () { + trustSet.LimitAmount = 1234 assert.throws( () => verifyTrustSet(trustSet), ValidationError, - "TrustSet: invalid LimitAmount" - ); - }); + 'TrustSet: invalid LimitAmount', + ) + }) - it("throws when QualityIn is not a number", function () { - trustSet.QualityIn = "1234"; + it('throws when QualityIn is not a number', function () { + trustSet.QualityIn = '1234' assert.throws( () => verifyTrustSet(trustSet), ValidationError, - "TrustSet: QualityIn must be a number" - ); - }); + 'TrustSet: QualityIn must be a number', + ) + }) - it("throws when QualityOut is not a number", function () { - trustSet.QualityOut = "4321"; + it('throws when QualityOut is not a number', function () { + trustSet.QualityOut = '4321' assert.throws( () => verifyTrustSet(trustSet), ValidationError, - "TrustSet: QualityOut must be a number" - ); - }); -}); + 'TrustSet: QualityOut must be a number', + ) + }) +}) diff --git a/test/models/utils.ts b/test/models/utils.ts index 4f329d6f..6ff4b5cf 100644 --- a/test/models/utils.ts +++ b/test/models/utils.ts @@ -1,30 +1,30 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { isFlagEnabled } from "../../src/models/utils"; +import { isFlagEnabled } from '../../src/models/utils' /** * Utils Testing. * * Provides tests for utils used in models. */ -describe("Models Utils", function () { - describe("isFlagEnabled", function () { - let flags: number; - const flag1 = 0x00010000; - const flag2 = 0x00020000; +describe('Models Utils', function () { + describe('isFlagEnabled', function () { + let flags: number + const flag1 = 0x00010000 + const flag2 = 0x00020000 beforeEach(function () { - flags = 0x00000000; - }); + flags = 0x00000000 + }) - it("verifies a flag is enabled", function () { - flags += flag1 + flag2; - assert.isTrue(isFlagEnabled(flags, flag1)); - }); + it('verifies a flag is enabled', function () { + flags += flag1 + flag2 + assert.isTrue(isFlagEnabled(flags, flag1)) + }) - it("verifies a flag is not enabled", function () { - flags += flag2; - assert.isFalse(isFlagEnabled(flags, flag1)); - }); - }); -}); + it('verifies a flag is not enabled', function () { + flags += flag2 + assert.isFalse(isFlagEnabled(flags, flag1)) + }) + }) +}) diff --git a/test/runClientTests.ts b/test/runClientTests.ts index 40ccfdbd..21f297ee 100644 --- a/test/runClientTests.ts +++ b/test/runClientTests.ts @@ -1,7 +1,7 @@ -import fs from "fs"; -import path from "path"; +import fs from 'fs' +import path from 'path' -import { Client } from "xrpl-local"; +import { Client } from 'xrpl-local' /** * Client Test Runner. @@ -9,34 +9,34 @@ import { Client } from "xrpl-local"; * Throws errors when we detect the absence of tests. * Puts all the client methods under one "describe" umbrella. */ -describe("Client [Test Runner]", function () { +describe('Client [Test Runner]', function () { // doesn't need a functional client, just needs to instantiate to get a list of public methods // (to determine what methods are missing from ) - const allPublicMethods = getAllPublicMethods(new Client("wss://")); + const allPublicMethods = getAllPublicMethods(new Client('wss://')) - const allTestSuites = loadTestSuites(); + const allTestSuites = loadTestSuites() // Report any missing tests. - const allTestedMethods = new Set(allTestSuites.map((s) => s.name)); + const allTestedMethods = new Set(allTestSuites.map((s) => s.name)) for (const methodName of allPublicMethods) { if (!allTestedMethods.has(methodName)) { // TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures. it.skip(`${methodName} - no test suite found`, function () { throw new Error( - `Test file not found! Create file "test/client/${methodName}.ts".` - ); - }); + `Test file not found! Create file "test/client/${methodName}.ts".`, + ) + }) } } -}); +}) function getAllPublicMethods(client: Client) { return Array.from( new Set([ ...Object.getOwnPropertyNames(client), ...Object.getOwnPropertyNames(Client.prototype), - ]) - ).filter((key) => !key.startsWith("_")); // removes private methods + ]), + ).filter((key) => !key.startsWith('_')) // removes private methods } /** @@ -46,28 +46,28 @@ function getAllPublicMethods(client: Client) { * so that we can report it. */ interface LoadedTestSuite { - name: string; - tests: Array<[string, () => void | PromiseLike]>; + name: string + tests: Array<[string, () => void | PromiseLike]> } function loadTestSuites(): LoadedTestSuite[] { - const allTests: any[] = fs.readdirSync(path.join(__dirname, "client"), { - encoding: "utf8", - }); + const allTests: any[] = fs.readdirSync(path.join(__dirname, 'client'), { + encoding: 'utf8', + }) return allTests .map((methodName) => { - if (methodName.startsWith(".DS_Store")) { - return null; + if (methodName.startsWith('.DS_Store')) { + return null } - if (methodName.endsWith(".ts")) { - methodName = methodName.slice(0, -3); + if (methodName.endsWith('.ts')) { + methodName = methodName.slice(0, -3) } - const testSuite = require(`./client/${methodName}`); + const testSuite = require(`./client/${methodName}`) return { name: methodName, config: testSuite.config || {}, tests: Object.entries(testSuite.default || {}), - } as LoadedTestSuite; + } as LoadedTestSuite }) - .filter(Boolean) as LoadedTestSuite[]; + .filter(Boolean) as LoadedTestSuite[] } diff --git a/test/setupClient.ts b/test/setupClient.ts index 618495db..652d6397 100644 --- a/test/setupClient.ts +++ b/test/setupClient.ts @@ -1,36 +1,36 @@ -import { Client, BroadcastClient } from "xrpl-local"; +import { Client, BroadcastClient } from 'xrpl-local' -import { createMockRippled } from "./mockRippled"; -import { getFreePort } from "./testUtils"; +import { createMockRippled } from './mockRippled' +import { getFreePort } from './testUtils' -function setupMockRippledConnection(testcase, port) { +async function setupMockRippledConnection(testcase, port) { return new Promise((resolve, reject) => { - testcase.mockRippled = createMockRippled(port); - testcase._mockedServerPort = port; - testcase.client = new Client(`ws://localhost:${port}`); - testcase.client.connect().then(resolve).catch(reject); - }); + testcase.mockRippled = createMockRippled(port) + testcase._mockedServerPort = port + testcase.client = new Client(`ws://localhost:${port}`) + testcase.client.connect().then(resolve).catch(reject) + }) } -function setupMockRippledConnectionForBroadcast(testcase, ports) { +async function setupMockRippledConnectionForBroadcast(testcase, ports) { return new Promise((resolve, reject) => { - const servers = ports.map((port) => `ws://localhost:${port}`); - testcase.mocks = ports.map((port) => createMockRippled(port)); - testcase.client = new BroadcastClient(servers); - testcase.client.connect().then(resolve).catch(reject); - }); + const servers = ports.map((port) => `ws://localhost:${port}`) + testcase.mocks = ports.map((port) => createMockRippled(port)) + testcase.client = new BroadcastClient(servers) + testcase.client.connect().then(resolve).catch(reject) + }) } -function setup(this: any) { - return getFreePort().then((port) => { - return setupMockRippledConnection(this, port); - }); +async function setup(this: any) { + return getFreePort().then(async (port) => { + return setupMockRippledConnection(this, port) + }) } -function setupBroadcast(this: any) { - return Promise.all([getFreePort(), getFreePort()]).then((ports) => { - return setupMockRippledConnectionForBroadcast(this, ports); - }); +async function setupBroadcast(this: any) { + return Promise.all([getFreePort(), getFreePort()]).then(async (ports) => { + return setupMockRippledConnectionForBroadcast(this, ports) + }) } function teardown(this: any, done) { @@ -38,13 +38,13 @@ function teardown(this: any, done) { .disconnect() .then(() => { if (this.mockRippled != null) { - this.mockRippled.close(); + this.mockRippled.close() } else { - this.mocks.forEach((mock) => mock.close()); + this.mocks.forEach((mock) => mock.close()) } - setImmediate(done); + setImmediate(done) }) - .catch(done); + .catch(done) } export default { @@ -52,4 +52,4 @@ export default { teardown, setupBroadcast, createMockRippled, -}; +} diff --git a/test/setupClientWeb.ts b/test/setupClientWeb.ts index b502b481..614b2818 100644 --- a/test/setupClientWeb.ts +++ b/test/setupClientWeb.ts @@ -1,48 +1,48 @@ -import { Client, BroadcastClient } from "xrpl-local"; +import { Client, BroadcastClient } from 'xrpl-local' -import { PortResponse } from "./mockRippled"; +import { PortResponse } from './mockRippled' -const port = 34371; -const baseUrl = "ws://testripple.circleci.com:"; +const port = 34371 +const baseUrl = 'ws://testripple.circleci.com:' -function setup(this: any, port_ = port) { - const tclient = new Client(baseUrl + port_); +async function setup(this: any, port_ = port) { + const tclient = new Client(baseUrl + port_) return tclient .connect() - .then(() => { + .then(async () => { return tclient.connection.request({ - command: "test_command", + command: 'test_command', data: { openOnOtherPort: true }, - }); + }) }) - .then((got) => { + .then(async (got) => { return new Promise((resolve, reject) => { - this.client = new Client(baseUrl + (got as PortResponse).result.port); - this.client.connect().then(resolve).catch(reject); - }); + this.client = new Client(baseUrl + (got as PortResponse).result.port) + this.client.connect().then(resolve).catch(reject) + }) + }) + .then(async () => { + return tclient.disconnect() }) - .then(() => { - return tclient.disconnect(); - }); } -function setupBroadcast(this: any) { - const servers = [port, port + 1].map((port_) => baseUrl + port_); - this.client = new BroadcastClient(servers); +async function setupBroadcast(this: any) { + const servers = [port, port + 1].map((port_) => baseUrl + port_) + this.client = new BroadcastClient(servers) return new Promise((resolve, reject) => { - this.client.connect().then(resolve).catch(reject); - }); + this.client.connect().then(resolve).catch(reject) + }) } function teardown(this: any) { if (this.client.isConnected()) { - return this.client.disconnect(); + return this.client.disconnect() } - return undefined; + return undefined } export default { setup, teardown, setupBroadcast, -}; +} diff --git a/test/shamap.ts b/test/shamap.ts index 50c98034..5615591e 100644 --- a/test/shamap.ts +++ b/test/shamap.ts @@ -1,11 +1,11 @@ -import assert from "assert"; +import assert from 'assert' -import { SHAMap, NodeType } from "../src/utils/hashes/shamap"; +import { SHAMap, NodeType } from '../src/utils/hashes/shamap' -const TYPE_TRANSACTION_NO_METADATA = NodeType.TRANSACTION_NO_METADATA; +const TYPE_TRANSACTION_NO_METADATA = NodeType.TRANSACTION_NO_METADATA const HEX_ZERO = - "00000000000000000000000000000000" + "00000000000000000000000000000000"; + '00000000000000000000000000000000' + '00000000000000000000000000000000' /** * Generates data to hash for testing. @@ -13,51 +13,51 @@ const HEX_ZERO = * @param v */ function intToVuc(v: number): string { - let ret = ""; + let ret = '' for (let i = 0; i < 32; i++) { - ret += "0"; - ret += v.toString(16).toUpperCase(); + ret += '0' + ret += v.toString(16).toUpperCase() } - return ret; + return ret } function fillShamapTest(shamap: any, keys: string[], hashes: string[]) { for (let i = 0; i < keys.length; i++) { - const data = intToVuc(i); - shamap.addItem(keys[i].toUpperCase(), data, TYPE_TRANSACTION_NO_METADATA); - assert.equal(shamap.hash, hashes[i]); + const data = intToVuc(i) + shamap.addItem(keys[i].toUpperCase(), data, TYPE_TRANSACTION_NO_METADATA) + assert.equal(shamap.hash, hashes[i]) } } -describe("SHAMap", function () { - describe("#addItem", function () { - it("will add new nodes to v1", function () { +describe('SHAMap', function () { + describe('#addItem', function () { + it('will add new nodes to v1', function () { const keys = [ - "b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - "292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8", - ]; + 'b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + 'f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + '292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8', + ] const hashesv1 = [ - "B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C64B6281F7F", - "FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A8831845467FB2ECE266", - "4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51AE756795B75", - "7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC6C74F93E07", - "395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596462B0E3A3E", - "D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D98A84D9DDE4", - "76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF94361143615", - "DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA02BBE7230E5", - ]; + 'B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C64B6281F7F', + 'FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A8831845467FB2ECE266', + '4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51AE756795B75', + '7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC6C74F93E07', + '395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596462B0E3A3E', + 'D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D98A84D9DDE4', + '76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF94361143615', + 'DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA02BBE7230E5', + ] - const shamapv1 = new SHAMap(); - assert.equal(shamapv1.hash, HEX_ZERO); - fillShamapTest(shamapv1, keys, hashesv1); - }); - }); -}); + const shamapv1 = new SHAMap() + assert.equal(shamapv1.hash, HEX_ZERO) + fillShamapTest(shamapv1, keys, hashesv1) + }) + }) +}) diff --git a/test/testUtils.ts b/test/testUtils.ts index aa3e2fce..beed1710 100644 --- a/test/testUtils.ts +++ b/test/testUtils.ts @@ -1,17 +1,17 @@ -import net from "net"; +import net from 'net' -import { assert } from "chai"; -import _ from "lodash"; +import { assert } from 'chai' +import _ from 'lodash' -import addresses from "./fixtures/addresses.json"; +import addresses from './fixtures/addresses.json' /** * Setup to run tests on both classic addresses and X-addresses. */ export const addressTests = [ - { type: "Classic Address", address: addresses.ACCOUNT }, - { type: "X-Address", address: addresses.ACCOUNT_X }, -]; + { type: 'Classic Address', address: addresses.ACCOUNT }, + { type: 'X-Address', address: addresses.ACCOUNT_X }, +] /** * Check the response against the expected result. Optionally validate @@ -24,28 +24,28 @@ export const addressTests = [ export function assertResultMatch( response: any, expected: any, - schemaName?: string + schemaName?: string, ) { if (expected.txJSON) { - assert(response.txJSON); + assert(response.txJSON) assert.deepEqual( JSON.parse(response.txJSON), JSON.parse(expected.txJSON), - "checkResult: txJSON must match" - ); + 'checkResult: txJSON must match', + ) } if (expected.tx_json) { - assert(response.tx_json); + assert(response.tx_json) assert.deepEqual( response.tx_json, expected.tx_json, - "checkResult: tx_json must match" - ); + 'checkResult: tx_json must match', + ) } assert.deepEqual( - _.omit(response, ["txJSON", "tx_json"]), - _.omit(expected, ["txJSON", "tx_json"]) - ); + _.omit(response, ['txJSON', 'tx_json']), + _.omit(expected, ['txJSON', 'tx_json']), + ) } /** @@ -58,38 +58,38 @@ export function assertResultMatch( export async function assertRejects( promise: PromiseLike, instanceOf: any, - message?: string | RegExp + message?: string | RegExp, ) { try { - await promise; - assert(false, "Expected an error to be thrown"); + await promise + assert(false, 'Expected an error to be thrown') } catch (error) { - assert(error instanceof instanceOf, error.message); - if (typeof message === "string") { - assert.strictEqual(error.message, message); + assert(error instanceof instanceOf, error.message) + if (typeof message === 'string') { + assert.strictEqual(error.message, message) } else if (message instanceof RegExp) { - assert(message.test(error.message)); + assert(message.test(error.message)) } } } // using a free port instead of a constant port enables parallelization -export function getFreePort() { +export async function getFreePort() { return new Promise((resolve, reject) => { - const server = net.createServer(); - let port; - server.on("listening", function () { - port = (server.address() as any).port; - server.close(); - }); - server.on("close", function () { - resolve(port); - }); - server.on("error", function (error) { - reject(error); - }); - server.listen(0); - }); + const server = net.createServer() + let port + server.on('listening', function () { + port = (server.address() as any).port + server.close() + }) + server.on('close', function () { + resolve(port) + }) + server.on('error', function (error) { + reject(error) + }) + server.listen(0) + }) } /** @@ -100,8 +100,8 @@ export function getFreePort() { * @param error - Thrown error. */ export function ignoreWebSocketDisconnect(error: Error): void { - if (error.message === "websocket was closed") { - return; + if (error.message === 'websocket was closed') { + return } - throw error; + throw error } diff --git a/test/utils/computeLedgerHash.ts b/test/utils/computeLedgerHash.ts index 40186d4a..62cec814 100644 --- a/test/utils/computeLedgerHash.ts +++ b/test/utils/computeLedgerHash.ts @@ -1,139 +1,139 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { ValidationError } from "../../src/common/errors"; -import { computeLedgerHeaderHash } from "../../src/utils"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import { assertResultMatch } from "../testUtils"; +import { ValidationError } from '../../src/common/errors' +import { computeLedgerHeaderHash } from '../../src/utils' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import { assertResultMatch } from '../testUtils' -const { computeLedgerHash: REQUEST_FIXTURES } = requests; +const { computeLedgerHash: REQUEST_FIXTURES } = requests -describe("computeLedgerHash", function () { - it("given corrupt data - should fail", function () { - const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)); +describe('computeLedgerHash', function () { + it('given corrupt data - should fail', function () { + const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)) ledger.transactions[0].rawTransaction = - '{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Amount":"12000000000","Destination":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Fee":"10","Flags":0,"Sequence":62,"SigningPubKey":"034AADB09CFF4A4804073701EC53C3510CDC95917C2BB0150FB742D0C66E6CEE9E","TransactionType":"Payment","TxnSignature":"3045022022EB32AECEF7C644C891C19F87966DF9C62B1F34BABA6BE774325E4BB8E2DD62022100A51437898C28C2B297112DF8131F2BB39EA5FE613487DDD611525F1796264639","hash":"3B1A4E1C9BB6A7208EB146BCDB86ECEA6068ED01466D933528CA2B4C64F753EF","meta":{"AffectedNodes":[{"CreatedNode":{"LedgerEntryType":"AccountRoot","LedgerIndex":"4C6ACBD635B0F07101F7FA25871B0925F8836155462152172755845CE691C49E","NewFields":{"Account":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Balance":"10000000000","Sequence":1}}},{"ModifiedNode":{"FinalFields":{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Balance":"981481999380","Flags":0,"OwnerCount":0,"Sequence":63},"LedgerEntryType":"AccountRoot","LedgerIndex":"B33FDD5CF3445E1A7F2BE9B06336BEBD73A5E3EE885D3EF93F7E3E2992E46F1A","PreviousFields":{"Balance":"991481999390","Sequence":62},"PreviousTxnID":"2485FDC606352F1B0785DA5DE96FB9DBAF43EB60ECBB01B7F6FA970F512CDA5F","PreviousTxnLgrSeq":31317}}],"TransactionIndex":0,"TransactionResult":"tesSUCCESS"},"ledger_index":38129}'; - ledger.parentCloseTime = ledger.closeTime; - let hash: string; + '{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Amount":"12000000000","Destination":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Fee":"10","Flags":0,"Sequence":62,"SigningPubKey":"034AADB09CFF4A4804073701EC53C3510CDC95917C2BB0150FB742D0C66E6CEE9E","TransactionType":"Payment","TxnSignature":"3045022022EB32AECEF7C644C891C19F87966DF9C62B1F34BABA6BE774325E4BB8E2DD62022100A51437898C28C2B297112DF8131F2BB39EA5FE613487DDD611525F1796264639","hash":"3B1A4E1C9BB6A7208EB146BCDB86ECEA6068ED01466D933528CA2B4C64F753EF","meta":{"AffectedNodes":[{"CreatedNode":{"LedgerEntryType":"AccountRoot","LedgerIndex":"4C6ACBD635B0F07101F7FA25871B0925F8836155462152172755845CE691C49E","NewFields":{"Account":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Balance":"10000000000","Sequence":1}}},{"ModifiedNode":{"FinalFields":{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Balance":"981481999380","Flags":0,"OwnerCount":0,"Sequence":63},"LedgerEntryType":"AccountRoot","LedgerIndex":"B33FDD5CF3445E1A7F2BE9B06336BEBD73A5E3EE885D3EF93F7E3E2992E46F1A","PreviousFields":{"Balance":"991481999390","Sequence":62},"PreviousTxnID":"2485FDC606352F1B0785DA5DE96FB9DBAF43EB60ECBB01B7F6FA970F512CDA5F","PreviousTxnLgrSeq":31317}}],"TransactionIndex":0,"TransactionResult":"tesSUCCESS"},"ledger_index":38129}' + ledger.parentCloseTime = ledger.closeTime + let hash: string try { - hash = computeLedgerHeaderHash(ledger, { computeTreeHashes: true }); + hash = computeLedgerHeaderHash(ledger, { computeTreeHashes: true }) } catch (error) { - assert(error instanceof ValidationError); + assert(error instanceof ValidationError) assert.strictEqual( error.message, - "transactionHash in header does not match computed hash of transactions" - ); + 'transactionHash in header does not match computed hash of transactions', + ) assert.deepStrictEqual(error.data, { transactionHashInHeader: - "DB83BF807416C5B3499A73130F843CF615AB8E797D79FE7D330ADF1BFA93951A", + 'DB83BF807416C5B3499A73130F843CF615AB8E797D79FE7D330ADF1BFA93951A', computedHashOfTransactions: - "EAA1ADF4D627339450F0E95EA88B7069186DD64230BAEBDCF3EEC4D616A9FC68", - }); - return; + 'EAA1ADF4D627339450F0E95EA88B7069186DD64230BAEBDCF3EEC4D616A9FC68', + }) + return } assert( false, - `Should throw ValidationError instead of producing hash: ${hash}` - ); - }); + `Should throw ValidationError instead of producing hash: ${hash}`, + ) + }) - it("given ledger without raw transactions - should throw", function () { - const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)); - delete ledger.transactions[0].rawTransaction; - ledger.parentCloseTime = ledger.closeTime; - let hash: string; + it('given ledger without raw transactions - should throw', function () { + const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)) + delete ledger.transactions[0].rawTransaction + ledger.parentCloseTime = ledger.closeTime + let hash: string try { - hash = computeLedgerHeaderHash(ledger, { computeTreeHashes: true }); + hash = computeLedgerHeaderHash(ledger, { computeTreeHashes: true }) } catch (error) { - assert(error instanceof ValidationError); - assert.strictEqual(error.message, "ledger is missing raw transactions"); - return; + assert(error instanceof ValidationError) + assert.strictEqual(error.message, 'ledger is missing raw transactions') + return } assert( false, - `Should throw ValidationError instead of producing hash: ${hash}` - ); - }); + `Should throw ValidationError instead of producing hash: ${hash}`, + ) + }) - it("given ledger without state or transactions - only compute ledger hash", function () { - const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)); + it('given ledger without state or transactions - only compute ledger hash', function () { + const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)) assert.strictEqual( ledger.transactions[0].rawTransaction, - '{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Amount":"10000000000","Destination":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Fee":"10","Flags":0,"Sequence":62,"SigningPubKey":"034AADB09CFF4A4804073701EC53C3510CDC95917C2BB0150FB742D0C66E6CEE9E","TransactionType":"Payment","TxnSignature":"3045022022EB32AECEF7C644C891C19F87966DF9C62B1F34BABA6BE774325E4BB8E2DD62022100A51437898C28C2B297112DF8131F2BB39EA5FE613487DDD611525F1796264639","hash":"3B1A4E1C9BB6A7208EB146BCDB86ECEA6068ED01466D933528CA2B4C64F753EF","meta":{"AffectedNodes":[{"CreatedNode":{"LedgerEntryType":"AccountRoot","LedgerIndex":"4C6ACBD635B0F07101F7FA25871B0925F8836155462152172755845CE691C49E","NewFields":{"Account":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Balance":"10000000000","Sequence":1}}},{"ModifiedNode":{"FinalFields":{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Balance":"981481999380","Flags":0,"OwnerCount":0,"Sequence":63},"LedgerEntryType":"AccountRoot","LedgerIndex":"B33FDD5CF3445E1A7F2BE9B06336BEBD73A5E3EE885D3EF93F7E3E2992E46F1A","PreviousFields":{"Balance":"991481999390","Sequence":62},"PreviousTxnID":"2485FDC606352F1B0785DA5DE96FB9DBAF43EB60ECBB01B7F6FA970F512CDA5F","PreviousTxnLgrSeq":31317}}],"TransactionIndex":0,"TransactionResult":"tesSUCCESS"},"ledger_index":38129}' - ); - ledger.parentCloseTime = ledger.closeTime; - const computeLedgerHash = computeLedgerHeaderHash; + '{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Amount":"10000000000","Destination":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Fee":"10","Flags":0,"Sequence":62,"SigningPubKey":"034AADB09CFF4A4804073701EC53C3510CDC95917C2BB0150FB742D0C66E6CEE9E","TransactionType":"Payment","TxnSignature":"3045022022EB32AECEF7C644C891C19F87966DF9C62B1F34BABA6BE774325E4BB8E2DD62022100A51437898C28C2B297112DF8131F2BB39EA5FE613487DDD611525F1796264639","hash":"3B1A4E1C9BB6A7208EB146BCDB86ECEA6068ED01466D933528CA2B4C64F753EF","meta":{"AffectedNodes":[{"CreatedNode":{"LedgerEntryType":"AccountRoot","LedgerIndex":"4C6ACBD635B0F07101F7FA25871B0925F8836155462152172755845CE691C49E","NewFields":{"Account":"rLQBHVhFnaC5gLEkgr6HgBJJ3bgeZHg9cj","Balance":"10000000000","Sequence":1}}},{"ModifiedNode":{"FinalFields":{"Account":"r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV","Balance":"981481999380","Flags":0,"OwnerCount":0,"Sequence":63},"LedgerEntryType":"AccountRoot","LedgerIndex":"B33FDD5CF3445E1A7F2BE9B06336BEBD73A5E3EE885D3EF93F7E3E2992E46F1A","PreviousFields":{"Balance":"991481999390","Sequence":62},"PreviousTxnID":"2485FDC606352F1B0785DA5DE96FB9DBAF43EB60ECBB01B7F6FA970F512CDA5F","PreviousTxnLgrSeq":31317}}],"TransactionIndex":0,"TransactionResult":"tesSUCCESS"},"ledger_index":38129}', + ) + ledger.parentCloseTime = ledger.closeTime + const computeLedgerHash = computeLedgerHeaderHash function testCompute(ledgerToCompute, expectedError): void { - let hash = computeLedgerHash(ledgerToCompute); + let hash = computeLedgerHash(ledgerToCompute) assert.strictEqual( hash, - "E6DB7365949BF9814D76BCC730B01818EB9136A89DB224F3F9F5AAE4569D758E" - ); + 'E6DB7365949BF9814D76BCC730B01818EB9136A89DB224F3F9F5AAE4569D758E', + ) // fail if required to compute tree hashes try { - hash = computeLedgerHash(ledgerToCompute, { computeTreeHashes: true }); + hash = computeLedgerHash(ledgerToCompute, { computeTreeHashes: true }) } catch (error) { - assert(error instanceof ValidationError); - assert.strictEqual(error.message, expectedError); - return; + assert(error instanceof ValidationError) + assert.strictEqual(error.message, expectedError) + return } assert( false, - `Should throw ValidationError instead of producing hash: ${hash}` - ); + `Should throw ValidationError instead of producing hash: ${hash}`, + ) } - const transactions = ledger.transactions; - delete ledger.transactions; - testCompute(ledger, "transactions property is missing from the ledger"); - delete ledger.rawState; - testCompute(ledger, "transactions property is missing from the ledger"); - ledger.transactions = transactions; - testCompute(ledger, "rawState property is missing from the ledger"); - }); + const transactions = ledger.transactions + delete ledger.transactions + testCompute(ledger, 'transactions property is missing from the ledger') + delete ledger.rawState + testCompute(ledger, 'transactions property is missing from the ledger') + ledger.transactions = transactions + testCompute(ledger, 'rawState property is missing from the ledger') + }) - it("wrong hash", function () { - const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)); - assertResultMatch(ledger, responses.getLedger.full, "getLedger"); + it('wrong hash', function () { + const ledger = JSON.parse(JSON.stringify(responses.getLedger.full)) + assertResultMatch(ledger, responses.getLedger.full, 'getLedger') const newLedger = { ...ledger, parentCloseTime: ledger.closeTime, stateHash: - "D9ABF622DA26EEEE48203085D4BC23B0F77DC6F8724AC33D975DA3CA492D2E44", - }; + 'D9ABF622DA26EEEE48203085D4BC23B0F77DC6F8724AC33D975DA3CA492D2E44', + } assert.throws(() => { - computeLedgerHeaderHash(newLedger); - }, /does not match computed hash of state/u); - }); + computeLedgerHeaderHash(newLedger) + }, /does not match computed hash of state/u) + }) - it("computeLedgerHash", function () { - const header = REQUEST_FIXTURES.header; - const ledgerHash = computeLedgerHeaderHash(header); + it('computeLedgerHash', function () { + const header = REQUEST_FIXTURES.header + const ledgerHash = computeLedgerHeaderHash(header) assert.strictEqual( ledgerHash, - "F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349" - ); - }); + 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349', + ) + }) - it("computeLedgerHash - with transactions", function () { + it('computeLedgerHash - with transactions', function () { const header = { ...REQUEST_FIXTURES.header, transactionHash: undefined, rawTransactions: JSON.stringify(REQUEST_FIXTURES.transactions), - }; - const ledgerHash = computeLedgerHeaderHash(header); + } + const ledgerHash = computeLedgerHeaderHash(header) assert.strictEqual( ledgerHash, - "F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349" - ); - }); + 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349', + ) + }) - it("computeLedgerHash - incorrent transaction_hash", function () { + it('computeLedgerHash - incorrent transaction_hash', function () { const header = { ...REQUEST_FIXTURES.header, transactionHash: - "325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9", - }; - assert.throws(() => computeLedgerHeaderHash(header)); - }); -}); + '325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9', + } + assert.throws(() => computeLedgerHeaderHash(header)) + }) +}) diff --git a/test/utils/dropsToXrp.ts b/test/utils/dropsToXrp.ts index 4e565613..a53b9514 100644 --- a/test/utils/dropsToXrp.ts +++ b/test/utils/dropsToXrp.ts @@ -1,124 +1,124 @@ -import BigNumber from "bignumber.js"; -import { assert } from "chai"; +import BigNumber from 'bignumber.js' +import { assert } from 'chai' -import { dropsToXrp } from "../../src/utils"; +import { dropsToXrp } from '../../src/utils' -describe("dropsToXrp", function () { - it("works with a typical amount", function () { - const xrp = dropsToXrp("2000000"); - assert.strictEqual(xrp, "2", "2 million drops equals 2 XRP"); - }); +describe('dropsToXrp', function () { + it('works with a typical amount', function () { + const xrp = dropsToXrp('2000000') + assert.strictEqual(xrp, '2', '2 million drops equals 2 XRP') + }) - it("works with fractions", function () { - let xrp = dropsToXrp("3456789"); - assert.strictEqual(xrp, "3.456789", "3,456,789 drops equals 3.456789 XRP"); + it('works with fractions', function () { + let xrp = dropsToXrp('3456789') + assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP') - xrp = dropsToXrp("3400000"); - assert.strictEqual(xrp, "3.4", "3,400,000 drops equals 3.4 XRP"); + xrp = dropsToXrp('3400000') + assert.strictEqual(xrp, '3.4', '3,400,000 drops equals 3.4 XRP') - xrp = dropsToXrp("1"); - assert.strictEqual(xrp, "0.000001", "1 drop equals 0.000001 XRP"); + xrp = dropsToXrp('1') + assert.strictEqual(xrp, '0.000001', '1 drop equals 0.000001 XRP') - xrp = dropsToXrp("1.0"); - assert.strictEqual(xrp, "0.000001", "1.0 drops equals 0.000001 XRP"); + xrp = dropsToXrp('1.0') + assert.strictEqual(xrp, '0.000001', '1.0 drops equals 0.000001 XRP') - xrp = dropsToXrp("1.00"); - assert.strictEqual(xrp, "0.000001", "1.00 drops equals 0.000001 XRP"); - }); + xrp = dropsToXrp('1.00') + assert.strictEqual(xrp, '0.000001', '1.00 drops equals 0.000001 XRP') + }) - it("works with zero", function () { - let xrp = dropsToXrp("0"); - assert.strictEqual(xrp, "0", "0 drops equals 0 XRP"); + it('works with zero', function () { + let xrp = dropsToXrp('0') + assert.strictEqual(xrp, '0', '0 drops equals 0 XRP') // negative zero is equivalent to zero - xrp = dropsToXrp("-0"); - assert.strictEqual(xrp, "0", "-0 drops equals 0 XRP"); + xrp = dropsToXrp('-0') + assert.strictEqual(xrp, '0', '-0 drops equals 0 XRP') - xrp = dropsToXrp("0.00"); - assert.strictEqual(xrp, "0", "0.00 drops equals 0 XRP"); + xrp = dropsToXrp('0.00') + assert.strictEqual(xrp, '0', '0.00 drops equals 0 XRP') - xrp = dropsToXrp("000000000"); - assert.strictEqual(xrp, "0", "000000000 drops equals 0 XRP"); - }); + xrp = dropsToXrp('000000000') + assert.strictEqual(xrp, '0', '000000000 drops equals 0 XRP') + }) - it("works with a negative value", function () { - const xrp = dropsToXrp("-2000000"); - assert.strictEqual(xrp, "-2", "-2 million drops equals -2 XRP"); - }); + it('works with a negative value', function () { + const xrp = dropsToXrp('-2000000') + assert.strictEqual(xrp, '-2', '-2 million drops equals -2 XRP') + }) - it("works with a value ending with a decimal point", function () { - let xrp = dropsToXrp("2000000."); - assert.strictEqual(xrp, "2", "2000000. drops equals 2 XRP"); + it('works with a value ending with a decimal point', function () { + let xrp = dropsToXrp('2000000.') + assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP') - xrp = dropsToXrp("-2000000."); - assert.strictEqual(xrp, "-2", "-2000000. drops equals -2 XRP"); - }); + xrp = dropsToXrp('-2000000.') + assert.strictEqual(xrp, '-2', '-2000000. drops equals -2 XRP') + }) - it("works with BigNumber objects", function () { - let xrp = dropsToXrp(new BigNumber(2000000)); - assert.strictEqual(xrp, "2", "(BigNumber) 2 million drops equals 2 XRP"); + it('works with BigNumber objects', function () { + let xrp = dropsToXrp(new BigNumber(2000000)) + assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP') - xrp = dropsToXrp(new BigNumber(-2000000)); - assert.strictEqual(xrp, "-2", "(BigNumber) -2 million drops equals -2 XRP"); + xrp = dropsToXrp(new BigNumber(-2000000)) + assert.strictEqual(xrp, '-2', '(BigNumber) -2 million drops equals -2 XRP') - xrp = dropsToXrp(new BigNumber(2345678)); + xrp = dropsToXrp(new BigNumber(2345678)) assert.strictEqual( xrp, - "2.345678", - "(BigNumber) 2,345,678 drops equals 2.345678 XRP" - ); + '2.345678', + '(BigNumber) 2,345,678 drops equals 2.345678 XRP', + ) - xrp = dropsToXrp(new BigNumber(-2345678)); + xrp = dropsToXrp(new BigNumber(-2345678)) assert.strictEqual( xrp, - "-2.345678", - "(BigNumber) -2,345,678 drops equals -2.345678 XRP" - ); - }); + '-2.345678', + '(BigNumber) -2,345,678 drops equals -2.345678 XRP', + ) + }) - it("works with a number", function () { + it('works with a number', function () { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. - let xrp = dropsToXrp(2000000); - assert.strictEqual(xrp, "2", "(number) 2 million drops equals 2 XRP"); - xrp = dropsToXrp(-2000000); - assert.strictEqual(xrp, "-2", "(number) -2 million drops equals -2 XRP"); - }); + let xrp = dropsToXrp(2000000) + assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP') + xrp = dropsToXrp(-2000000) + assert.strictEqual(xrp, '-2', '(number) -2 million drops equals -2 XRP') + }) - it("throws with an amount with too many decimal places", function () { + it('throws with an amount with too many decimal places', function () { assert.throws(() => { - dropsToXrp("1.2"); - }, /has too many decimal places/u); + dropsToXrp('1.2') + }, /has too many decimal places/u) assert.throws(() => { - dropsToXrp("0.10"); - }, /has too many decimal places/u); - }); + dropsToXrp('0.10') + }, /has too many decimal places/u) + }) - it("throws with an invalid value", function () { + it('throws with an invalid value', function () { assert.throws(() => { - dropsToXrp("FOO"); - }, /invalid value/u); + dropsToXrp('FOO') + }, /invalid value/u) assert.throws(() => { - dropsToXrp("1e-7"); - }, /invalid value/u); + dropsToXrp('1e-7') + }, /invalid value/u) assert.throws(() => { - dropsToXrp("2,0"); - }, /invalid value/u); + dropsToXrp('2,0') + }, /invalid value/u) assert.throws(() => { - dropsToXrp("."); - }, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./u); - }); + dropsToXrp('.') + }, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./u) + }) - it("throws with an amount more than one decimal point", function () { + it('throws with an amount more than one decimal point', function () { assert.throws(() => { - dropsToXrp("1.0.0"); - }, /dropsToXrp: invalid value '1\.0\.0'/u); + dropsToXrp('1.0.0') + }, /dropsToXrp: invalid value '1\.0\.0'/u) assert.throws(() => { - dropsToXrp("..."); - }, /dropsToXrp: invalid value '\.\.\.'/u); - }); -}); + dropsToXrp('...') + }, /dropsToXrp: invalid value '\.\.\.'/u) + }) +}) diff --git a/test/utils/generateAddress.ts b/test/utils/generateAddress.ts index 61b3c518..82e13bb7 100644 --- a/test/utils/generateAddress.ts +++ b/test/utils/generateAddress.ts @@ -1,240 +1,240 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import ECDSA from "../../src/common/ecdsa"; -import { UnexpectedError } from "../../src/common/errors"; +import ECDSA from '../../src/common/ecdsa' +import { UnexpectedError } from '../../src/common/errors' import { generateXAddress, GenerateAddressOptions, -} from "../../src/utils/generateAddress"; -import responses from "../fixtures/responses"; +} from '../../src/utils/generateAddress' +import responses from '../fixtures/responses' -describe("generateAddress", function () { - it("generateAddress", function () { +describe('generateAddress', function () { + it('generateAddress', function () { assert.deepEqual( // GIVEN entropy of all zeros // WHEN generating an address generateXAddress({ entropy: new Array(16).fill(0) }), // THEN we get the expected return value - responses.generateXAddress - ); - }); + responses.generateXAddress, + ) + }) - it("generateAddress invalid entropy", function () { + it('generateAddress invalid entropy', function () { assert.throws(() => { // GIVEN entropy of 1 byte // WHEN generating an address - generateXAddress({ entropy: new Array(1).fill(0) }); + generateXAddress({ entropy: new Array(1).fill(0) }) // THEN an UnexpectedError is thrown // because 16 bytes of entropy are required - }, UnexpectedError); - }); + }, UnexpectedError) + }) - it("generateAddress with no options object", function () { + it('generateAddress with no options object', function () { // GIVEN no options // WHEN generating an address - const account = generateXAddress(); + const account = generateXAddress() // THEN we get an object with an xAddress starting with 'x' and a secret starting with 's' - assert(account.xAddress.startsWith("X"), "Address must start with `X`"); - assert(account.secret.startsWith("s"), "Secret must start with `s`"); - }); + assert(account.xAddress.startsWith('X'), 'Address must start with `X`') + assert(account.secret.startsWith('s'), 'Secret must start with `s`') + }) - it("generateAddress with empty options object", function () { + it('generateAddress with empty options object', function () { // GIVEN an empty options object - const options = {}; + const options = {} // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get an object with an xAddress starting with 'x' and a secret starting with 's' - assert(account.xAddress.startsWith("X"), "Address must start with `X`"); - assert(account.secret.startsWith("s"), "Secret must start with `s`"); - }); + assert(account.xAddress.startsWith('X'), 'Address must start with `X`') + assert(account.secret.startsWith('s'), 'Secret must start with `s`') + }) - it("generateAddress with algorithm `ecdsa-secp256k1`", function () { + it('generateAddress with algorithm `ecdsa-secp256k1`', function () { // GIVEN we want to use 'ecdsa-secp256k1' const options: GenerateAddressOptions = { algorithm: ECDSA.secp256k1, includeClassicAddress: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get an object with an address starting with 'r' and a secret starting with 's' (not 'sEd') assert( - account.classicAddress?.startsWith("r"), - "Address must start with `r`" - ); + account.classicAddress?.startsWith('r'), + 'Address must start with `r`', + ) assert.deepEqual( account.secret.slice(0, 1), - "s", - `Secret ${account.secret} must start with 's'` - ); + 's', + `Secret ${account.secret} must start with 's'`, + ) assert.notStrictEqual( account.secret.slice(0, 3), - "sEd", - `secp256k1 secret ${account.secret} must not start with 'sEd'` - ); - }); + 'sEd', + `secp256k1 secret ${account.secret} must not start with 'sEd'`, + ) + }) - it("generateAddress with algorithm `ed25519`", function () { + it('generateAddress with algorithm `ed25519`', function () { // GIVEN we want to use 'ed25519' const options: GenerateAddressOptions = { algorithm: ECDSA.ed25519, includeClassicAddress: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get an object with an address starting with 'r' and a secret starting with 'sEd' assert( - account.classicAddress?.startsWith("r"), - "Address must start with `r`" - ); + account.classicAddress?.startsWith('r'), + 'Address must start with `r`', + ) assert.deepEqual( account.secret.slice(0, 3), - "sEd", - `Ed25519 secret ${account.secret} must start with 'sEd'` - ); - }); + 'sEd', + `Ed25519 secret ${account.secret} must start with 'sEd'`, + ) + }) - it("generateAddress with algorithm `ecdsa-secp256k1` and given entropy", function () { + it('generateAddress with algorithm `ecdsa-secp256k1` and given entropy', function () { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.secp256k1, entropy: new Array(16).fill(0), - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value - assert.deepEqual(account, responses.generateXAddress); - }); + assert.deepEqual(account, responses.generateXAddress) + }) - it("generateAddress with algorithm `ed25519` and given entropy", function () { + it('generateAddress with algorithm `ed25519` and given entropy', function () { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.ed25519, entropy: new Array(16).fill(0), - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { // generateAddress return value always includes xAddress to encourage X-address adoption - xAddress: "X7xq1YJ4xmLSGGLhuakFQB9CebWYthQkgsvFC4LGFH871HB", - secret: "sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE", - }); - }); + xAddress: 'X7xq1YJ4xmLSGGLhuakFQB9CebWYthQkgsvFC4LGFH871HB', + secret: 'sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE', + }) + }) - it("generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address", function () { + it('generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address', function () { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.secp256k1, entropy: new Array(16).fill(0), includeClassicAddress: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value - assert.deepEqual(account, responses.generateAddress); - }); + assert.deepEqual(account, responses.generateAddress) + }) - it("generateAddress with algorithm `ed25519` and given entropy; include classic address", function () { + it('generateAddress with algorithm `ed25519` and given entropy; include classic address', function () { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.ed25519, entropy: new Array(16).fill(0), includeClassicAddress: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { // generateAddress return value always includes xAddress to encourage X-address adoption - xAddress: "X7xq1YJ4xmLSGGLhuakFQB9CebWYthQkgsvFC4LGFH871HB", + xAddress: 'X7xq1YJ4xmLSGGLhuakFQB9CebWYthQkgsvFC4LGFH871HB', - secret: "sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE", - classicAddress: "r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7", - address: "r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7", - }); - }); + secret: 'sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE', + classicAddress: 'r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7', + address: 'r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7', + }) + }) - it("generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use", function () { + it('generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use', function () { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.secp256k1, entropy: new Array(16).fill(0), includeClassicAddress: true, test: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value const response = { // generateAddress return value always includes xAddress to encourage X-address adoption ...responses.generateAddress, - xAddress: "TVG3TcCD58BD6MZqsNuTihdrhZwR8SzvYS8U87zvHsAcNw4", - }; - assert.deepEqual(account, response); - }); + xAddress: 'TVG3TcCD58BD6MZqsNuTihdrhZwR8SzvYS8U87zvHsAcNw4', + } + assert.deepEqual(account, response) + }) - it("generateAddress with algorithm `ed25519` and given entropy; include classic address; for test network use", function () { + it('generateAddress with algorithm `ed25519` and given entropy; include classic address; for test network use', function () { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.ed25519, entropy: new Array(16).fill(0), includeClassicAddress: true, test: true, - }; + } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { // generateAddress return value always includes xAddress to encourage X-address adoption - xAddress: "T7t4HeTMF5tT68agwuVbJwu23ssMPeh8dDtGysZoQiij1oo", - secret: "sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE", - classicAddress: "r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7", - address: "r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7", - }); - }); + xAddress: 'T7t4HeTMF5tT68agwuVbJwu23ssMPeh8dDtGysZoQiij1oo', + secret: 'sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE', + classicAddress: 'r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7', + address: 'r9zRhGr7b6xPekLvT6wP4qNdWMryaumZS7', + }) + }) - it("generateAddress for test network use", function () { + it('generateAddress for test network use', function () { // GIVEN we want an address for test network use - const options: GenerateAddressOptions = { test: true }; + const options: GenerateAddressOptions = { test: true } // WHEN generating an address - const account = generateXAddress(options); + const account = generateXAddress(options) // THEN we get an object with xAddress starting with 'T' and a secret starting with 's' // generateAddress return value always includes xAddress to encourage X-address adoption assert.deepEqual( account.xAddress.slice(0, 1), - "T", - "Test addresses start with T" - ); + 'T', + 'Test addresses start with T', + ) assert.deepEqual( account.secret.slice(0, 1), - "s", - `Secret ${account.secret} must start with 's'` - ); - }); -}); + 's', + `Secret ${account.secret} must start with 's'`, + ) + }) +}) diff --git a/test/utils/hashes.ts b/test/utils/hashes.ts index a84507cc..30b39eb8 100644 --- a/test/utils/hashes.ts +++ b/test/utils/hashes.ts @@ -1,6 +1,6 @@ -import assert from "assert"; -import fs from "fs"; -import { join } from "path"; +import assert from 'assert' +import fs from 'fs' +import { join } from 'path' import { computeStateTreeHash, @@ -11,7 +11,7 @@ import { computeSignerListIndex, computeEscrowHash, computePaymentChannelHash, -} from "../../src/utils/hashes"; +} from '../../src/utils/hashes' /** * Expects a corresponding ledger dump in $repo/test/fixtures/rippled folder. @@ -19,20 +19,19 @@ import { * @param ledgerIndex - The ledger index of the desired dump. */ function createLedgerTest(ledgerIndex: number): void { - const ledgerIndexString = String(ledgerIndex); + const ledgerIndexString = String(ledgerIndex) const path = join( __dirname, - "..", - `fixtures/rippled/ledgerFull${ledgerIndex}.json` - ); + '..', + `fixtures/rippled/ledgerFull${ledgerIndex}.json`, + ) // eslint-disable-next-line node/no-sync -- must be sync version when not in async method - const ledgerRaw = fs.readFileSync(path, { encoding: "utf8" }); - const ledgerJSON = JSON.parse(ledgerRaw); + const ledgerRaw = fs.readFileSync(path, { encoding: 'utf8' }) + const ledgerJSON = JSON.parse(ledgerRaw) const hasAccounts = - Array.isArray(ledgerJSON.accountState) && - ledgerJSON.accountState.length > 0; + Array.isArray(ledgerJSON.accountState) && ledgerJSON.accountState.length > 0 describe(`ledger hashes ${ledgerIndexString}`, function () { if (hasAccounts) { @@ -40,136 +39,136 @@ function createLedgerTest(ledgerIndex: number): void { it(`has account_hash of ${ledgerJSON.account_hash}`, function () { assert.equal( ledgerJSON.account_hash, - computeStateTreeHash(ledgerJSON.accountState) - ); - }); + computeStateTreeHash(ledgerJSON.accountState), + ) + }) } // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- known to be a string it(`has transaction_hash of ${ledgerJSON.transaction_hash}`, function () { assert.equal( ledgerJSON.transaction_hash, - computeTransactionTreeHash(ledgerJSON.transactions) - ); - }); - }); + computeTransactionTreeHash(ledgerJSON.transactions), + ) + }) + }) } -describe("Hashes", function () { +describe('Hashes', function () { // This is the first recorded ledger with a non empty transaction set // eslint-disable-next-line mocha/no-setup-in-describe -- runs tests - createLedgerTest(38129); + createLedgerTest(38129) // Because, why not. // eslint-disable-next-line mocha/no-setup-in-describe -- runs tests - createLedgerTest(40000); + createLedgerTest(40000) // 1311 AffectedNodes, no accounts // eslint-disable-next-line mocha/no-setup-in-describe -- runs tests - createLedgerTest(7501326); + createLedgerTest(7501326) - describe("calcAccountRootEntryHash", function () { - it("will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", function () { - const account = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + describe('calcAccountRootEntryHash', function () { + it('will calculate the AccountRoot entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', function () { + const account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' const expectedEntryHash = - "2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8"; - const actualEntryHash = computeAccountRootIndex(account); + '2B6AC232AA4C4BE41BF49D2459FA4A0347E1B543A4C92FCEE0821C0201E2E9A8' + const actualEntryHash = computeAccountRootIndex(account) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) - describe("calcRippleStateEntryHash", function () { - it("will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD", function () { - const account1 = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; - const account2 = "rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY"; - const currency = "USD"; + describe('calcRippleStateEntryHash', function () { + it('will calculate the RippleState entry hash for rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh and rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY in USD', function () { + const account1 = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' + const account2 = 'rB5TihdPbKgMrkFqrqUC3yLdE8hhv4BdeY' + const currency = 'USD' const expectedEntryHash = - "C683B5BB928F025F1E860D9D69D6C554C2202DE0D45877ADB3077DA4CB9E125C"; + 'C683B5BB928F025F1E860D9D69D6C554C2202DE0D45877ADB3077DA4CB9E125C' const actualEntryHash1 = computeTrustlineHash( account1, account2, - currency - ); + currency, + ) const actualEntryHash2 = computeTrustlineHash( account2, account1, - currency - ); + currency, + ) - assert.equal(actualEntryHash1, expectedEntryHash); - assert.equal(actualEntryHash2, expectedEntryHash); - }); + assert.equal(actualEntryHash1, expectedEntryHash) + assert.equal(actualEntryHash2, expectedEntryHash) + }) - it("will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM", function () { - const account1 = "r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV"; - const account2 = "rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj"; - const currency = "UAM"; + it('will calculate the RippleState entry hash for r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV and rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj in UAM', function () { + const account1 = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV' + const account2 = 'rUAMuQTfVhbfqUDuro7zzy4jj4Wq57MPTj' + const currency = 'UAM' const expectedEntryHash = - "AE9ADDC584358E5847ADFC971834E471436FC3E9DE6EA1773DF49F419DC0F65E"; + 'AE9ADDC584358E5847ADFC971834E471436FC3E9DE6EA1773DF49F419DC0F65E' const actualEntryHash1 = computeTrustlineHash( account1, account2, - currency - ); + currency, + ) const actualEntryHash2 = computeTrustlineHash( account2, account1, - currency - ); + currency, + ) - assert.equal(actualEntryHash1, expectedEntryHash); - assert.equal(actualEntryHash2, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash1, expectedEntryHash) + assert.equal(actualEntryHash2, expectedEntryHash) + }) + }) - describe("calcOfferEntryHash", function () { - it("will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137", function () { - const account = "r32UufnaCGL82HubijgJGDmdE5hac7ZvLw"; - const sequence = 137; + describe('calcOfferEntryHash', function () { + it('will calculate the Offer entry hash for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw, sequence 137', function () { + const account = 'r32UufnaCGL82HubijgJGDmdE5hac7ZvLw' + const sequence = 137 const expectedEntryHash = - "03F0AED09DEEE74CEF85CD57A0429D6113507CF759C597BABB4ADB752F734CE3"; - const actualEntryHash = computeOfferIndex(account, sequence); + '03F0AED09DEEE74CEF85CD57A0429D6113507CF759C597BABB4ADB752F734CE3' + const actualEntryHash = computeOfferIndex(account, sequence) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) - describe("computeSignerListIndex", function () { - it("will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw", function () { - const account = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh"; + describe('computeSignerListIndex', function () { + it('will calculate the SignerList index for r32UufnaCGL82HubijgJGDmdE5hac7ZvLw', function () { + const account = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' const expectedEntryHash = - "778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF"; - const actualEntryHash = computeSignerListIndex(account); - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + '778365D5180F5DF3016817D1F318527AD7410D83F8636CF48C43E8AF72AB49BF' + const actualEntryHash = computeSignerListIndex(account) + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) - describe("calcEscrowEntryHash", function () { - it("will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84", function () { - const account = "rDx69ebzbowuqztksVDmZXjizTd12BVr4x"; - const sequence = 84; + describe('calcEscrowEntryHash', function () { + it('will calculate the Escrow entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x, sequence 84', function () { + const account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' + const sequence = 84 const expectedEntryHash = - "61E8E8ED53FA2CEBE192B23897071E9A75217BF5A410E9CB5B45AAB7AECA567A"; - const actualEntryHash = computeEscrowHash(account, sequence); + '61E8E8ED53FA2CEBE192B23897071E9A75217BF5A410E9CB5B45AAB7AECA567A' + const actualEntryHash = computeEscrowHash(account, sequence) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) - describe("calcPaymentChannelEntryHash", function () { - it("will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82", function () { - const account = "rDx69ebzbowuqztksVDmZXjizTd12BVr4x"; - const dstAccount = "rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso"; - const sequence = 82; + describe('calcPaymentChannelEntryHash', function () { + it('will calculate the PaymentChannel entry hash for rDx69ebzbowuqztksVDmZXjizTd12BVr4x and rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso, sequence 82', function () { + const account = 'rDx69ebzbowuqztksVDmZXjizTd12BVr4x' + const dstAccount = 'rLFtVprxUEfsH54eCWKsZrEQzMDsx1wqso' + const sequence = 82 const expectedEntryHash = - "E35708503B3C3143FB522D749AAFCC296E8060F0FB371A9A56FAE0B1ED127366"; + 'E35708503B3C3143FB522D749AAFCC296E8060F0FB371A9A56FAE0B1ED127366' const actualEntryHash = computePaymentChannelHash( account, dstAccount, - sequence - ); + sequence, + ) - assert.equal(actualEntryHash, expectedEntryHash); - }); - }); -}); + assert.equal(actualEntryHash, expectedEntryHash) + }) + }) +}) diff --git a/test/utils/signPaymentChannelClaim.ts b/test/utils/signPaymentChannelClaim.ts index 9e48ba7f..111af7cc 100644 --- a/test/utils/signPaymentChannelClaim.ts +++ b/test/utils/signPaymentChannelClaim.ts @@ -1,21 +1,21 @@ -import signPaymentChannelClaim from "../../src/utils/signPaymentChannelClaim"; -import responses from "../fixtures/responses"; -import { assertResultMatch } from "../testUtils"; +import signPaymentChannelClaim from '../../src/utils/signPaymentChannelClaim' +import responses from '../fixtures/responses' +import { assertResultMatch } from '../testUtils' -describe("signPaymentChannelClaim", function () { - it("basic signature matches", function () { +describe('signPaymentChannelClaim', function () { + it('basic signature matches', function () { const channel = - "3E18C05AD40319B809520F1A136370C4075321B285217323396D6FD9EE1E9037"; - const amount = ".00001"; + '3E18C05AD40319B809520F1A136370C4075321B285217323396D6FD9EE1E9037' + const amount = '.00001' const privateKey = - "ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A"; + 'ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A' - const result = signPaymentChannelClaim(channel, amount, privateKey); + const result = signPaymentChannelClaim(channel, amount, privateKey) assertResultMatch( result, responses.signPaymentChannelClaim, - "signPaymentChannelClaim" - ); - }); -}); + 'signPaymentChannelClaim', + ) + }) +}) diff --git a/test/utils/verifyPaymentChannelClaim.ts b/test/utils/verifyPaymentChannelClaim.ts index bdb7992e..7506d8ff 100644 --- a/test/utils/verifyPaymentChannelClaim.ts +++ b/test/utils/verifyPaymentChannelClaim.ts @@ -1,30 +1,30 @@ -import { verifyPaymentChannelClaim } from "../../src"; -import requests from "../fixtures/requests"; -import responses from "../fixtures/responses"; -import { assertResultMatch } from "../testUtils"; +import { verifyPaymentChannelClaim } from '../../src' +import requests from '../fixtures/requests' +import responses from '../fixtures/responses' +import { assertResultMatch } from '../testUtils' -describe("verifyPaymentChannelClaim", function () { - it("basic verification works", function () { +describe('verifyPaymentChannelClaim', function () { + it('basic verification works', function () { const publicKey = - "02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"; + '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' const result = verifyPaymentChannelClaim( requests.signPaymentChannelClaim.channel, requests.signPaymentChannelClaim.amount, responses.signPaymentChannelClaim, - publicKey - ); - assertResultMatch(result, true, "verifyPaymentChannelClaim"); - }); + publicKey, + ) + assertResultMatch(result, true, 'verifyPaymentChannelClaim') + }) - it("invalid payment channel claim fails", function () { + it('invalid payment channel claim fails', function () { const publicKey = - "03A6523FE4281DA48A6FD77FAF3CB77F5C7001ABA0B32BCEDE0369AC009758D7D9"; + '03A6523FE4281DA48A6FD77FAF3CB77F5C7001ABA0B32BCEDE0369AC009758D7D9' const result = verifyPaymentChannelClaim( requests.signPaymentChannelClaim.channel, requests.signPaymentChannelClaim.amount, responses.signPaymentChannelClaim, - publicKey - ); - assertResultMatch(result, false, "verifyPaymentChannelClaim"); - }); -}); + publicKey, + ) + assertResultMatch(result, false, 'verifyPaymentChannelClaim') + }) +}) diff --git a/test/utils/xrpToDrops.ts b/test/utils/xrpToDrops.ts index 0895916a..93b67aa3 100644 --- a/test/utils/xrpToDrops.ts +++ b/test/utils/xrpToDrops.ts @@ -1,110 +1,110 @@ -import BigNumber from "bignumber.js"; -import { assert } from "chai"; +import BigNumber from 'bignumber.js' +import { assert } from 'chai' -import { xrpToDrops } from "../../src/utils"; +import { xrpToDrops } from '../../src/utils' -describe("xrpToDrops", function () { - it("works with a typical amount", function () { - const drops = xrpToDrops("2"); - assert.strictEqual(drops, "2000000", "2 XRP equals 2 million drops"); - }); +describe('xrpToDrops', function () { + it('works with a typical amount', function () { + const drops = xrpToDrops('2') + assert.strictEqual(drops, '2000000', '2 XRP equals 2 million drops') + }) - it("works with fractions", function () { - let drops = xrpToDrops("3.456789"); - assert.strictEqual(drops, "3456789", "3.456789 XRP equals 3,456,789 drops"); - drops = xrpToDrops("3.400000"); - assert.strictEqual(drops, "3400000", "3.400000 XRP equals 3,400,000 drops"); - drops = xrpToDrops("0.000001"); - assert.strictEqual(drops, "1", "0.000001 XRP equals 1 drop"); - drops = xrpToDrops("0.0000010"); - assert.strictEqual(drops, "1", "0.0000010 XRP equals 1 drop"); - }); + it('works with fractions', function () { + let drops = xrpToDrops('3.456789') + assert.strictEqual(drops, '3456789', '3.456789 XRP equals 3,456,789 drops') + drops = xrpToDrops('3.400000') + assert.strictEqual(drops, '3400000', '3.400000 XRP equals 3,400,000 drops') + drops = xrpToDrops('0.000001') + assert.strictEqual(drops, '1', '0.000001 XRP equals 1 drop') + drops = xrpToDrops('0.0000010') + assert.strictEqual(drops, '1', '0.0000010 XRP equals 1 drop') + }) - it("works with zero", function () { - let drops = xrpToDrops("0"); - assert.strictEqual(drops, "0", "0 XRP equals 0 drops"); + it('works with zero', function () { + let drops = xrpToDrops('0') + assert.strictEqual(drops, '0', '0 XRP equals 0 drops') // negative zero is equivalent to zero - drops = xrpToDrops("-0"); - assert.strictEqual(drops, "0", "-0 XRP equals 0 drops"); - drops = xrpToDrops("0.000000"); - assert.strictEqual(drops, "0", "0.000000 XRP equals 0 drops"); - drops = xrpToDrops("0.0000000"); - assert.strictEqual(drops, "0", "0.0000000 XRP equals 0 drops"); - }); + drops = xrpToDrops('-0') + assert.strictEqual(drops, '0', '-0 XRP equals 0 drops') + drops = xrpToDrops('0.000000') + assert.strictEqual(drops, '0', '0.000000 XRP equals 0 drops') + drops = xrpToDrops('0.0000000') + assert.strictEqual(drops, '0', '0.0000000 XRP equals 0 drops') + }) - it("works with a negative value", function () { - const drops = xrpToDrops("-2"); - assert.strictEqual(drops, "-2000000", "-2 XRP equals -2 million drops"); - }); + it('works with a negative value', function () { + const drops = xrpToDrops('-2') + assert.strictEqual(drops, '-2000000', '-2 XRP equals -2 million drops') + }) - it("works with a value ending with a decimal point", function () { - let drops = xrpToDrops("2."); - assert.strictEqual(drops, "2000000", "2. XRP equals 2000000 drops"); - drops = xrpToDrops("-2."); - assert.strictEqual(drops, "-2000000", "-2. XRP equals -2000000 drops"); - }); + it('works with a value ending with a decimal point', function () { + let drops = xrpToDrops('2.') + assert.strictEqual(drops, '2000000', '2. XRP equals 2000000 drops') + drops = xrpToDrops('-2.') + assert.strictEqual(drops, '-2000000', '-2. XRP equals -2000000 drops') + }) - it("works with BigNumber objects", function () { - let drops = xrpToDrops(new BigNumber(2)); + it('works with BigNumber objects', function () { + let drops = xrpToDrops(new BigNumber(2)) assert.strictEqual( drops, - "2000000", - "(BigNumber) 2 XRP equals 2 million drops" - ); - drops = xrpToDrops(new BigNumber(-2)); + '2000000', + '(BigNumber) 2 XRP equals 2 million drops', + ) + drops = xrpToDrops(new BigNumber(-2)) assert.strictEqual( drops, - "-2000000", - "(BigNumber) -2 XRP equals -2 million drops" - ); - }); + '-2000000', + '(BigNumber) -2 XRP equals -2 million drops', + ) + }) - it("works with a number", function () { + it('works with a number', function () { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. - let drops = xrpToDrops(2); + let drops = xrpToDrops(2) assert.strictEqual( drops, - "2000000", - "(number) 2 XRP equals 2 million drops" - ); - drops = xrpToDrops(-2); + '2000000', + '(number) 2 XRP equals 2 million drops', + ) + drops = xrpToDrops(-2) assert.strictEqual( drops, - "-2000000", - "(number) -2 XRP equals -2 million drops" - ); - }); + '-2000000', + '(number) -2 XRP equals -2 million drops', + ) + }) - it("throws with an amount with too many decimal places", function () { + it('throws with an amount with too many decimal places', function () { assert.throws(() => { - xrpToDrops("1.1234567"); - }, /has too many decimal places/u); + xrpToDrops('1.1234567') + }, /has too many decimal places/u) assert.throws(() => { - xrpToDrops("0.0000001"); - }, /has too many decimal places/u); - }); + xrpToDrops('0.0000001') + }, /has too many decimal places/u) + }) - it("throws with an invalid value", function () { + it('throws with an invalid value', function () { assert.throws(() => { - xrpToDrops("FOO"); - }, /invalid value/u); + xrpToDrops('FOO') + }, /invalid value/u) assert.throws(() => { - xrpToDrops("1e-7"); - }, /invalid value/u); + xrpToDrops('1e-7') + }, /invalid value/u) assert.throws(() => { - xrpToDrops("2,0"); - }, /invalid value/u); + xrpToDrops('2,0') + }, /invalid value/u) assert.throws(() => { - xrpToDrops("."); - }, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./u); - }); + xrpToDrops('.') + }, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./u) + }) - it("throws with an amount more than one decimal point", function () { + it('throws with an amount more than one decimal point', function () { assert.throws(() => { - xrpToDrops("1.0.0"); - }, /xrpToDrops: invalid value '1\.0\.0'/u); + xrpToDrops('1.0.0') + }, /xrpToDrops: invalid value '1\.0\.0'/u) assert.throws(() => { - xrpToDrops("..."); - }, /xrpToDrops: invalid value '\.\.\.'/u); - }); -}); + xrpToDrops('...') + }, /xrpToDrops: invalid value '\.\.\.'/u) + }) +}) diff --git a/test/wallet/index.ts b/test/wallet/index.ts index 8011677e..6a92a56c 100644 --- a/test/wallet/index.ts +++ b/test/wallet/index.ts @@ -1,236 +1,236 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import ECDSA from "../../src/common/ecdsa"; -import Wallet from "../../src/wallet"; +import ECDSA from '../../src/common/ecdsa' +import Wallet from '../../src/wallet' /** * Wallet testing. * * Provides tests for Wallet class. */ -describe("Wallet", function () { - describe("generate", function () { - const classicAddressPrefix = "r"; - const ed25519KeyPrefix = "ED"; - const secp256k1PrivateKeyPrefix = "00"; +describe('Wallet', function () { + describe('generate', function () { + const classicAddressPrefix = 'r' + const ed25519KeyPrefix = 'ED' + const secp256k1PrivateKeyPrefix = '00' - it("generates a new wallet using default algorithm", function () { - const wallet = Wallet.generate(); + it('generates a new wallet using default algorithm', function () { + const wallet = Wallet.generate() - assert.isString(wallet.publicKey); - assert.isString(wallet.privateKey); - assert.isString(wallet.classicAddress); - assert.isString(wallet.seed); - assert.isTrue(wallet.publicKey.startsWith(ed25519KeyPrefix)); - assert.isTrue(wallet.privateKey.startsWith(ed25519KeyPrefix)); - assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)); - }); + assert.isString(wallet.publicKey) + assert.isString(wallet.privateKey) + assert.isString(wallet.classicAddress) + assert.isString(wallet.seed) + assert.isTrue(wallet.publicKey.startsWith(ed25519KeyPrefix)) + assert.isTrue(wallet.privateKey.startsWith(ed25519KeyPrefix)) + assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)) + }) - it("generates a new wallet using algorithm ecdsa-secp256k1", function () { - const algorithm = ECDSA.secp256k1; - const wallet = Wallet.generate(algorithm); + it('generates a new wallet using algorithm ecdsa-secp256k1', function () { + const algorithm = ECDSA.secp256k1 + const wallet = Wallet.generate(algorithm) - assert.isString(wallet.publicKey); - assert.isString(wallet.privateKey); - assert.isString(wallet.classicAddress); - assert.isString(wallet.seed); - assert.isTrue(wallet.privateKey.startsWith(secp256k1PrivateKeyPrefix)); - assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)); - }); + assert.isString(wallet.publicKey) + assert.isString(wallet.privateKey) + assert.isString(wallet.classicAddress) + assert.isString(wallet.seed) + assert.isTrue(wallet.privateKey.startsWith(secp256k1PrivateKeyPrefix)) + assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)) + }) - it("generates a new wallet using algorithm ed25519", function () { - const algorithm = ECDSA.ed25519; - const wallet = Wallet.generate(algorithm); + it('generates a new wallet using algorithm ed25519', function () { + const algorithm = ECDSA.ed25519 + const wallet = Wallet.generate(algorithm) - assert.isString(wallet.publicKey); - assert.isString(wallet.privateKey); - assert.isString(wallet.classicAddress); - assert.isString(wallet.seed); - assert.isTrue(wallet.publicKey.startsWith(ed25519KeyPrefix)); - assert.isTrue(wallet.privateKey.startsWith(ed25519KeyPrefix)); - assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)); - }); - }); + assert.isString(wallet.publicKey) + assert.isString(wallet.privateKey) + assert.isString(wallet.classicAddress) + assert.isString(wallet.seed) + assert.isTrue(wallet.publicKey.startsWith(ed25519KeyPrefix)) + assert.isTrue(wallet.privateKey.startsWith(ed25519KeyPrefix)) + assert.isTrue(wallet.classicAddress.startsWith(classicAddressPrefix)) + }) + }) - describe("fromSeed", function () { - const seed = "ssL9dv2W5RK8L3tuzQxYY6EaZhSxW"; + describe('fromSeed', function () { + const seed = 'ssL9dv2W5RK8L3tuzQxYY6EaZhSxW' const publicKey = - "030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D"; + '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' const privateKey = - "00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F"; + '00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F' - it("derives a wallet using default algorithm", function () { - const wallet = Wallet.fromSeed(seed); + it('derives a wallet using default algorithm', function () { + const wallet = Wallet.fromSeed(seed) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) - it("derives a wallet using algorithm ecdsa-secp256k1", function () { - const algorithm = ECDSA.secp256k1; - const wallet = Wallet.fromSeed(seed, algorithm); + it('derives a wallet using algorithm ecdsa-secp256k1', function () { + const algorithm = ECDSA.secp256k1 + const wallet = Wallet.fromSeed(seed, algorithm) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) - it("derives a wallet using algorithm ed25519", function () { - const algorithm = ECDSA.ed25519; - const wallet = Wallet.fromSeed(seed, algorithm); + it('derives a wallet using algorithm ed25519', function () { + const algorithm = ECDSA.ed25519 + const wallet = Wallet.fromSeed(seed, algorithm) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) + }) - describe("fromMnemonic", function () { + describe('fromMnemonic', function () { const mnemonic = - "try milk link drift aware pass obtain again music stick pluck fold"; + 'try milk link drift aware pass obtain again music stick pluck fold' const publicKey = - "0257B550BA2FDCCF0ADDA3DEB2A5411700F3ADFDCC7C68E1DCD1E2B63E6B0C63E6"; + '0257B550BA2FDCCF0ADDA3DEB2A5411700F3ADFDCC7C68E1DCD1E2B63E6B0C63E6' const privateKey = - "008F942B6E229C0E9CEE47E7A94253DABB6A9855F4BA2D8A741FA31851A1D423C3"; + '008F942B6E229C0E9CEE47E7A94253DABB6A9855F4BA2D8A741FA31851A1D423C3' - it("derives a wallet using default derivation path", function () { - const wallet = Wallet.fromMnemonic(mnemonic); + it('derives a wallet using default derivation path', function () { + const wallet = Wallet.fromMnemonic(mnemonic) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) - it("derives a wallet using an input derivation path", function () { - const derivationPath = "m/44'/144'/0'/0/0"; - const wallet = Wallet.fromMnemonic(mnemonic, derivationPath); + it('derives a wallet using an input derivation path', function () { + const derivationPath = "m/44'/144'/0'/0/0" + const wallet = Wallet.fromMnemonic(mnemonic, derivationPath) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) + }) - describe("fromEntropy", function () { - let entropy; + describe('fromEntropy', function () { + let entropy const publicKey = - "0390A196799EE412284A5D80BF78C3E84CBB80E1437A0AECD9ADF94D7FEAAFA284"; + '0390A196799EE412284A5D80BF78C3E84CBB80E1437A0AECD9ADF94D7FEAAFA284' const privateKey = - "002512BBDFDBB77510883B7DCCBEF270B86DEAC8B64AC762873D75A1BEE6298665"; + '002512BBDFDBB77510883B7DCCBEF270B86DEAC8B64AC762873D75A1BEE6298665' const publicKeyED25519 = - "ED1A7C082846CFF58FF9A892BA4BA2593151CCF1DBA59F37714CC9ED39824AF85F"; + 'ED1A7C082846CFF58FF9A892BA4BA2593151CCF1DBA59F37714CC9ED39824AF85F' const privateKeyED25519 = - "ED0B6CBAC838DFE7F47EA1BD0DF00EC282FDF45510C92161072CCFB84035390C4D"; + 'ED0B6CBAC838DFE7F47EA1BD0DF00EC282FDF45510C92161072CCFB84035390C4D' beforeEach(function () { - const entropySize = 16; - entropy = new Array(entropySize).fill(0); - }); + const entropySize = 16 + entropy = new Array(entropySize).fill(0) + }) - it("derives a wallet using entropy", function () { - const wallet = Wallet.fromEntropy(entropy); + it('derives a wallet using entropy', function () { + const wallet = Wallet.fromEntropy(entropy) - assert.equal(wallet.publicKey, publicKeyED25519); - assert.equal(wallet.privateKey, privateKeyED25519); - }); + assert.equal(wallet.publicKey, publicKeyED25519) + assert.equal(wallet.privateKey, privateKeyED25519) + }) - it("derives a wallet using algorithm ecdsa-secp256k1", function () { - const algorithm = ECDSA.secp256k1; - const wallet = Wallet.fromEntropy(entropy, algorithm); + it('derives a wallet using algorithm ecdsa-secp256k1', function () { + const algorithm = ECDSA.secp256k1 + const wallet = Wallet.fromEntropy(entropy, algorithm) - assert.equal(wallet.publicKey, publicKey); - assert.equal(wallet.privateKey, privateKey); - }); + assert.equal(wallet.publicKey, publicKey) + assert.equal(wallet.privateKey, privateKey) + }) - it("derives a wallet using algorithm ed25519", function () { - const algorithm = ECDSA.ed25519; - const wallet = Wallet.fromEntropy(entropy, algorithm); + it('derives a wallet using algorithm ed25519', function () { + const algorithm = ECDSA.ed25519 + const wallet = Wallet.fromEntropy(entropy, algorithm) - assert.equal(wallet.publicKey, publicKeyED25519); - assert.equal(wallet.privateKey, privateKeyED25519); - }); - }); + assert.equal(wallet.publicKey, publicKeyED25519) + assert.equal(wallet.privateKey, privateKeyED25519) + }) + }) - describe("signTransaction", function () { + describe('signTransaction', function () { const publicKey = - "030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D"; + '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' const privateKey = - "00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F"; - const address = "rhvh5SrgBL5V8oeV9EpDuVszeJSSCEkbPc"; + '00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F' + const address = 'rhvh5SrgBL5V8oeV9EpDuVszeJSSCEkbPc' - it("signs a transaction offline", function () { + it('signs a transaction offline', function () { const txJSON = { - TransactionType: "Payment", + TransactionType: 'Payment', Account: address, - Destination: "rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r", - Amount: "20000000", + Destination: 'rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r', + Amount: '20000000', Sequence: 1, - Fee: "12", + Fee: '12', SigningPubKey: publicKey, - }; - const wallet = new Wallet(publicKey, privateKey); + } + const wallet = new Wallet(publicKey, privateKey) const signedTx: { signedTransaction: string; id: string } = - wallet.signTransaction(txJSON); + wallet.signTransaction(txJSON) - assert.hasAllKeys(signedTx, ["id", "signedTransaction"]); - assert.isString(signedTx.id); - assert.isString(signedTx.signedTransaction); - }); - }); + assert.hasAllKeys(signedTx, ['id', 'signedTransaction']) + assert.isString(signedTx.id) + assert.isString(signedTx.signedTransaction) + }) + }) - describe("verifyTransaction", function () { + describe('verifyTransaction', function () { const publicKey = - "030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D"; + '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' const privateKey = - "00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F"; + '00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F' const prepared = { signedTransaction: - "1200002400000001614000000001312D0068400000000000000C7321030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D74473045022100CAF99A63B241F5F62B456C68A593D2835397101533BB5D0C4DC17362AC22046F022016A2CA2CF56E777B10E43B56541A4C2FB553E7E298CDD39F7A8A844DA491E51D81142AF1861DEC1316AEEC995C94FF9E2165B1B784608314FDB08D07AAA0EB711793A3027304D688E10C3648", - id: "30D9ECA2A7FB568C5A8607E5850D9567572A9E7C6094C26BEFD4DC4C2CF2657A", - }; + '1200002400000001614000000001312D0068400000000000000C7321030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D74473045022100CAF99A63B241F5F62B456C68A593D2835397101533BB5D0C4DC17362AC22046F022016A2CA2CF56E777B10E43B56541A4C2FB553E7E298CDD39F7A8A844DA491E51D81142AF1861DEC1316AEEC995C94FF9E2165B1B784608314FDB08D07AAA0EB711793A3027304D688E10C3648', + id: '30D9ECA2A7FB568C5A8607E5850D9567572A9E7C6094C26BEFD4DC4C2CF2657A', + } - it("returns true when verifying a transaction signed by the same wallet", function () { - const wallet = new Wallet(publicKey, privateKey); + it('returns true when verifying a transaction signed by the same wallet', function () { + const wallet = new Wallet(publicKey, privateKey) const isVerified: boolean = wallet.verifyTransaction( - prepared.signedTransaction - ); + prepared.signedTransaction, + ) - assert.equal(isVerified, true); - }); + assert.equal(isVerified, true) + }) - it("returns false when verifying a transaction signed by a different wallet", function () { + it('returns false when verifying a transaction signed by a different wallet', function () { const diffPublicKey = - "02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"; + '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' const diffPrivateKey = - "00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A"; - const wallet = new Wallet(diffPublicKey, diffPrivateKey); + '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A' + const wallet = new Wallet(diffPublicKey, diffPrivateKey) const isVerified: boolean = wallet.verifyTransaction( - prepared.signedTransaction - ); + prepared.signedTransaction, + ) - assert.equal(isVerified, false); - }); - }); + assert.equal(isVerified, false) + }) + }) - describe("getXAddress", function () { + describe('getXAddress', function () { const publicKey = - "030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D"; + '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' const privateKey = - "00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F"; - const wallet = new Wallet(publicKey, privateKey); - const tag = 1337; - const mainnetXAddress = "X7gJ5YK8abHf2eTPWPFHAAot8Knck11QGqmQ7a6a3Z8PJvk"; - const testnetXAddress = "T7bq3e7kxYq9pwDz8UZhqAZoEkcRGTXSNr5immvcj3DYRaV"; + '00141BA006D3363D2FB2785E8DF4E44D3A49908780CB4FB51F6D217C08C021429F' + const wallet = new Wallet(publicKey, privateKey) + const tag = 1337 + const mainnetXAddress = 'X7gJ5YK8abHf2eTPWPFHAAot8Knck11QGqmQ7a6a3Z8PJvk' + const testnetXAddress = 'T7bq3e7kxYq9pwDz8UZhqAZoEkcRGTXSNr5immvcj3DYRaV' - it("returns a Testnet X-address when test is true", function () { - const result = wallet.getXAddress(tag, true); - assert.equal(result, testnetXAddress); - }); + it('returns a Testnet X-address when test is true', function () { + const result = wallet.getXAddress(tag, true) + assert.equal(result, testnetXAddress) + }) - it("returns a Mainnet X-address when test is false", function () { - const result = wallet.getXAddress(tag, false); - assert.equal(result, mainnetXAddress); - }); + it('returns a Mainnet X-address when test is false', function () { + const result = wallet.getXAddress(tag, false) + assert.equal(result, mainnetXAddress) + }) it("returns a Mainnet X-address when test isn't provided", function () { - const result = wallet.getXAddress(tag); - assert.equal(result, mainnetXAddress); - }); - }); -}); + const result = wallet.getXAddress(tag) + assert.equal(result, mainnetXAddress) + }) + }) +}) diff --git a/test/walletGeneration.ts b/test/walletGeneration.ts index 24d990fb..1205e8e9 100644 --- a/test/walletGeneration.ts +++ b/test/walletGeneration.ts @@ -1,39 +1,36 @@ -import { assert } from "chai"; +import { assert } from 'chai' -import { - getFaucetUrl, - FaucetNetwork, -} from "../src/wallet/generateFaucetWallet"; +import { getFaucetUrl, FaucetNetwork } from '../src/wallet/generateFaucetWallet' -import setupClient from "./setupClient"; +import setupClient from './setupClient' -describe("Get Faucet URL", function () { - beforeEach(setupClient.setup); - afterEach(setupClient.teardown); +describe('Get Faucet URL', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it("returns the Devnet URL", function () { - const expectedFaucet = FaucetNetwork.Devnet; - this.client.connection.url = FaucetNetwork.Devnet; + it('returns the Devnet URL', function () { + const expectedFaucet = FaucetNetwork.Devnet + this.client.connection.url = FaucetNetwork.Devnet - assert.strictEqual(getFaucetUrl(this.client), expectedFaucet); - }); + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) + }) - it("returns the Testnet URL", function () { - const expectedFaucet = FaucetNetwork.Testnet; - this.client.connection.url = FaucetNetwork.Testnet; + it('returns the Testnet URL', function () { + const expectedFaucet = FaucetNetwork.Testnet + this.client.connection.url = FaucetNetwork.Testnet - assert.strictEqual(getFaucetUrl(this.client), expectedFaucet); - }); + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) + }) - it("returns the Testnet URL with the XRPL Labs server", function () { - const expectedFaucet = FaucetNetwork.Testnet; - this.client.connection.url = "wss://testnet.xrpl-labs.com"; + it('returns the Testnet URL with the XRPL Labs server', function () { + const expectedFaucet = FaucetNetwork.Testnet + this.client.connection.url = 'wss://testnet.xrpl-labs.com' - assert.strictEqual(getFaucetUrl(this.client), expectedFaucet); - }); + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) + }) - it("returns undefined if not a Testnet or Devnet server URL", function () { + it('returns undefined if not a Testnet or Devnet server URL', function () { // Info: setupClient.setup creates a connection to 'localhost' - assert.strictEqual(getFaucetUrl(this.client), undefined); - }); -}); + assert.strictEqual(getFaucetUrl(this.client), undefined) + }) +})