From e27e1ec36838ba5548ab0961eb0b842d516d5ee8 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Tue, 17 Aug 2021 11:16:42 -0700 Subject: [PATCH] Rename RippleAPI client to Client (#1520) * rename RippleAPI -> XrplClient * more renames * move API stuff to client folder * rename all api -> client * fix tests * make tests run * fix integ tests * fix urls * fix merge issues * XrplClient -> Client * fix merge issues * rename xrpl-client npm symlink to xrpl-local --- scripts/ci.sh | 2 +- snippets/src/getTransaction.ts | 10 +- snippets/src/parseAccountFlags.ts | 10 +- snippets/src/paths.ts | 14 +- snippets/src/reliableTransactionSubmission.ts | 20 +- src/broadcast.ts | 44 +-- src/{api.ts => client/index.ts} | 141 ++++----- src/{server/server.ts => client/utils.ts} | 20 +- src/common/connection.ts | 2 +- src/common/schemas/input/get-fee.json | 2 +- src/common/schemas/objects/instructions.json | 2 +- src/common/serverinfo.ts | 6 +- src/index.ts | 6 +- src/ledger/accountinfo.ts | 4 +- src/ledger/accountobjects.ts | 4 +- src/ledger/balance-sheet.ts | 4 +- src/ledger/balances.ts | 4 +- src/ledger/ledger.ts | 4 +- src/ledger/orderbook.ts | 8 +- src/ledger/orders.ts | 4 +- src/ledger/pathfind.ts | 4 +- src/ledger/payment-channel.ts | 4 +- src/ledger/settings.ts | 4 +- src/ledger/transaction.ts | 4 +- src/ledger/transactions.ts | 4 +- src/ledger/trustlines.ts | 4 +- src/ledger/utils.ts | 4 +- src/transaction/check-cancel.ts | 4 +- src/transaction/check-cash.ts | 4 +- src/transaction/check-create.ts | 4 +- src/transaction/escrow-cancellation.ts | 4 +- src/transaction/escrow-creation.ts | 4 +- src/transaction/escrow-execution.ts | 4 +- src/transaction/order.ts | 4 +- src/transaction/ordercancellation.ts | 4 +- src/transaction/payment-channel-claim.ts | 4 +- src/transaction/payment-channel-create.ts | 4 +- src/transaction/payment-channel-fund.ts | 4 +- src/transaction/payment.ts | 4 +- src/transaction/settings.ts | 4 +- src/transaction/sign.ts | 18 +- src/transaction/submit.ts | 10 +- src/transaction/ticket.ts | 4 +- src/transaction/trustline.ts | 4 +- src/transaction/utils.ts | 24 +- src/wallet/wallet-generation.ts | 26 +- test/api/constructor/index.ts | 29 -- test/api/getBalanceSheet/index.ts | 26 -- test/api/hasNextPage/index.ts | 24 -- test/api/isConnected/index.ts | 15 - test/api/isValidAddress/index.ts | 17 -- test/api/isValidSecret/index.ts | 12 - test/api/requestNextPage/index.ts | 38 --- ...t-api-test.ts => broadcast-client-test.ts} | 26 +- test/{api => client}/combine/index.ts | 10 +- .../computeLedgerHash/index.ts | 50 ++-- test/client/constructor/index.ts | 29 ++ test/{api => client}/deriveAddress/index.ts | 6 +- test/{api => client}/deriveKeypair/index.ts | 14 +- test/{api => client}/deriveXAddress/index.ts | 10 +- test/{api => client}/dropsToXrp/index.ts | 76 ++--- test/{api => client}/errors/index.ts | 10 +- .../formatBidsAndAsks/index.ts | 116 ++++---- test/{api => client}/generateAddress/index.ts | 56 ++-- .../{api => client}/generateXAddress/index.ts | 56 ++-- test/{api => client}/getAccountInfo/index.ts | 16 +- .../getAccountObjects/index.ts | 10 +- test/client/getBalanceSheet/index.ts | 26 ++ test/{api => client}/getBalances/index.ts | 18 +- test/{api => client}/getFee/index.ts | 44 +-- test/{api => client}/getFeeBase/index.ts | 6 +- test/{api => client}/getFeeRef/index.ts | 6 +- test/{api => client}/getLedger/index.ts | 36 +-- .../{api => client}/getLedgerVersion/index.ts | 6 +- test/{api => client}/getOrderbook/index.ts | 36 +-- test/{api => client}/getOrders/index.ts | 16 +- test/{api => client}/getPaths/index.ts | 72 ++--- .../getPaymentChannel/index.ts | 22 +- test/{api => client}/getServerInfo/index.ts | 26 +- test/{api => client}/getSettings/index.ts | 16 +- test/{api => client}/getTransaction/index.ts | 232 +++++++-------- test/{api => client}/getTransactions/index.ts | 62 ++-- test/{api => client}/getTrustlines/index.ts | 22 +- test/client/hasNextPage/index.ts | 24 ++ test/client/isConnected/index.ts | 15 + test/client/isValidAddress/index.ts | 17 ++ test/client/isValidSecret/index.ts | 12 + .../prepareCheckCancel/index.ts | 10 +- .../{api => client}/prepareCheckCash/index.ts | 14 +- .../prepareCheckCreate/index.ts | 14 +- .../prepareEscrowCancellation/index.ts | 14 +- .../prepareEscrowCreation/index.ts | 20 +- .../prepareEscrowExecution/index.ts | 26 +- test/{api => client}/prepareOrder/index.ts | 24 +- .../prepareOrderCancellation/index.ts | 24 +- test/{api => client}/preparePayment/index.ts | 140 ++++----- .../preparePaymentChannelClaim/index.ts | 26 +- .../preparePaymentChannelCreate/index.ts | 14 +- .../preparePaymentChannelFund/index.ts | 14 +- test/{api => client}/prepareSettings/index.ts | 82 +++--- test/{api => client}/prepareTicket/index.ts | 16 +- .../prepareTransaction/index.ts | 270 +++++++++--------- .../{api => client}/prepareTrustline/index.ts | 28 +- test/{api => client}/request/index.ts | 10 +- test/client/requestNextPage/index.ts | 38 +++ test/{api => client}/sign/index.ts | 112 ++++---- .../signPaymentChannelClaim/index.ts | 6 +- test/{api => client}/submit/index.ts | 10 +- .../verifyPaymentChannelClaim/index.ts | 10 +- test/{api => client}/xrpToDrops/index.ts | 70 ++--- test/connection-test.ts | 186 ++++++------ test/integration/integration-test.ts | 144 +++++----- test/integration/utils.js | 18 +- test/localrunner.html | 4 +- test/localrunnermin.html | 4 +- test/models/baseTransaction.ts | 2 +- test/models/checkCancel.ts | 2 +- test/models/checkCash.ts | 2 +- test/models/checkCreate.ts | 2 +- test/models/offerCreate.ts | 2 +- test/node_modules/{ripple-api => xrpl-local} | 0 test/rangeset-test.ts | 4 +- ...ivate.ts => ripple-client-test-private.ts} | 56 ++-- ...pple-api-test.ts => ripple-client-test.ts} | 30 +- .../{setup-api-web.ts => setup-client-web.ts} | 30 +- test/{setup-api.ts => setup-client.ts} | 18 +- test/utils.ts | 18 +- test/wallet-generation-test.ts | 22 +- test/wallet/signTransaction/index.ts | 4 +- test/wallet/verifyTransaction/index.ts | 2 +- webpack.config.js | 2 +- 131 files changed, 1688 insertions(+), 1693 deletions(-) rename src/{api.ts => client/index.ts} (81%) rename src/{server/server.ts => client/utils.ts} (50%) delete mode 100644 test/api/constructor/index.ts delete mode 100644 test/api/getBalanceSheet/index.ts delete mode 100644 test/api/hasNextPage/index.ts delete mode 100644 test/api/isConnected/index.ts delete mode 100644 test/api/isValidAddress/index.ts delete mode 100644 test/api/isValidSecret/index.ts delete mode 100644 test/api/requestNextPage/index.ts rename test/{broadcast-api-test.ts => broadcast-client-test.ts} (75%) rename test/{api => client}/combine/index.ts (74%) rename test/{api => client}/computeLedgerHash/index.ts (88%) create mode 100644 test/client/constructor/index.ts rename test/{api => client}/deriveAddress/index.ts (67%) rename test/{api => client}/deriveKeypair/index.ts (64%) rename test/{api => client}/deriveXAddress/index.ts (74%) rename test/{api => client}/dropsToXrp/index.ts (58%) rename test/{api => client}/errors/index.ts (55%) rename test/{api => client}/formatBidsAndAsks/index.ts (71%) rename test/{api => client}/generateAddress/index.ts (84%) rename test/{api => client}/generateXAddress/index.ts (83%) rename test/{api => client}/getAccountInfo/index.ts (52%) rename test/{api => client}/getAccountObjects/index.ts (61%) create mode 100644 test/client/getBalanceSheet/index.ts rename test/{api => client}/getBalances/index.ts (67%) rename test/{api => client}/getFee/index.ts (51%) rename test/{api => client}/getFeeBase/index.ts (60%) rename test/{api => client}/getFeeRef/index.ts (60%) rename test/{api => client}/getLedger/index.ts (67%) rename test/{api => client}/getLedgerVersion/index.ts (61%) rename test/{api => client}/getOrderbook/index.ts (79%) rename test/{api => client}/getOrders/index.ts (63%) rename test/{api => client}/getPaths/index.ts (50%) rename test/{api => client}/getPaymentChannel/index.ts (63%) rename test/{api => client}/getServerInfo/index.ts (56%) rename test/{api => client}/getSettings/index.ts (55%) rename test/{api => client}/getTransaction/index.ts (65%) rename test/{api => client}/getTransactions/index.ts (69%) rename test/{api => client}/getTrustlines/index.ts (53%) create mode 100644 test/client/hasNextPage/index.ts create mode 100644 test/client/isConnected/index.ts create mode 100644 test/client/isValidAddress/index.ts create mode 100644 test/client/isValidSecret/index.ts rename test/{api => client}/prepareCheckCancel/index.ts (75%) rename test/{api => client}/prepareCheckCash/index.ts (71%) rename test/{api => client}/prepareCheckCreate/index.ts (73%) rename test/{api => client}/prepareEscrowCancellation/index.ts (72%) rename test/{api => client}/prepareEscrowCreation/index.ts (74%) rename test/{api => client}/prepareEscrowExecution/index.ts (70%) rename test/{api => client}/prepareOrder/index.ts (71%) rename test/{api => client}/prepareOrderCancellation/index.ts (70%) rename test/{api => client}/preparePayment/index.ts (82%) rename test/{api => client}/preparePaymentChannelClaim/index.ts (80%) rename test/{api => client}/preparePaymentChannelCreate/index.ts (76%) rename test/{api => client}/preparePaymentChannelFund/index.ts (74%) rename test/{api => client}/prepareSettings/index.ts (73%) rename test/{api => client}/prepareTicket/index.ts (78%) rename test/{api => client}/prepareTransaction/index.ts (83%) rename test/{api => client}/prepareTrustline/index.ts (72%) rename test/{api => client}/request/index.ts (65%) create mode 100644 test/client/requestNextPage/index.ts rename test/{api => client}/sign/index.ts (84%) rename test/{api => client}/signPaymentChannelClaim/index.ts (77%) rename test/{api => client}/submit/index.ts (56%) rename test/{api => client}/verifyPaymentChannelClaim/index.ts (75%) rename test/{api => client}/xrpToDrops/index.ts (61%) rename test/node_modules/{ripple-api => xrpl-local} (100%) rename test/{ripple-api-test-private.ts => ripple-client-test-private.ts} (77%) rename test/{ripple-api-test.ts => ripple-client-test.ts} (71%) rename test/{setup-api-web.ts => setup-client-web.ts} (62%) rename test/{setup-api.ts => setup-client.ts} (80%) diff --git a/scripts/ci.sh b/scripts/ci.sh index 33565d5a..28d84070 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -25,7 +25,7 @@ unittest() { $(npm bin)/babel -D --optional runtime --ignore "**/node_modules/**" -d test-compiled/ test/ echo "--reporter spec --timeout 5000 --slow 500" > test-compiled/mocha.opts mkdir -p test-compiled/node_modules - ln -nfs ../../dist/npm test-compiled/node_modules/ripple-api + ln -nfs ../../dist/npm test-compiled/node_modules/xrpl-local mocha --opts test-compiled/mocha.opts test-compiled #compile tests for browser testing diff --git a/snippets/src/getTransaction.ts b/snippets/src/getTransaction.ts index caed4dab..ea75f8e6 100644 --- a/snippets/src/getTransaction.ts +++ b/snippets/src/getTransaction.ts @@ -1,16 +1,16 @@ -import {RippleAPI} from '../../dist/npm' +import {Client} from '../../dist/npm' -const api = new RippleAPI({ +const client = new Client({ server: 'wss://s.altnet.rippletest.net:51233' }) getTransaction() async function getTransaction() { - await api.connect() - const ledger = await api.getLedger({includeTransactions: true}) + await client.connect() + const ledger = await client.getLedger({includeTransactions: true}) console.log(ledger) - const tx = await api.getTransaction(ledger.transactionHashes[0]) + const tx = await client.getTransaction(ledger.transactionHashes[0]) console.log(tx) console.log('deliveredAmount:', tx.outcome.deliveredAmount) process.exit(0) diff --git a/snippets/src/parseAccountFlags.ts b/snippets/src/parseAccountFlags.ts index 53a8fb0c..29a7ec91 100644 --- a/snippets/src/parseAccountFlags.ts +++ b/snippets/src/parseAccountFlags.ts @@ -1,13 +1,13 @@ -import {RippleAPI} from '../../dist/npm' +import {Client} from '../../dist/npm' -const api = new RippleAPI({server: 'wss://s.altnet.rippletest.net:51233'}) +const client = new Client({server: 'wss://s.altnet.rippletest.net:51233'}) parseAccountFlags() async function parseAccountFlags() { - await api.connect() - const account_info = await api.request('account_info', {account: 'rKsdkGhyZH6b2Zzd5hNnEqSv2wpznn4n6N'}) - const flags = api.parseAccountFlags(account_info.account_data.Flags) + await client.connect() + const account_info = await client.request('account_info', {account: 'rKsdkGhyZH6b2Zzd5hNnEqSv2wpznn4n6N'}) + const flags = client.parseAccountFlags(account_info.account_data.Flags) console.log(JSON.stringify(flags, null, 2)) process.exit(0) } diff --git a/snippets/src/paths.ts b/snippets/src/paths.ts index 4a46c1c4..c663ad28 100644 --- a/snippets/src/paths.ts +++ b/snippets/src/paths.ts @@ -1,6 +1,6 @@ -import {RippleAPI} from '../../dist/npm' +import {Client} from '../../dist/npm' -const api = new RippleAPI({ +const client = new Client({ // server: 'wss://s.altnet.rippletest.net:51233' // server: 'ws://35.158.96.209:51233' server: 'ws://34.210.87.206:51233' @@ -9,7 +9,7 @@ const api = new RippleAPI({ sign() async function sign() { - await api.connect() + await client.connect() const pathfind: any = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', @@ -27,14 +27,14 @@ async function sign() { } } - await api.getPaths(pathfind).then(async (data) => { + await client.getPaths(pathfind).then(async (data) => { console.log('paths:', JSON.stringify(data)) const fakeSecret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' pathfind.paths = data[0].paths pathfind.destination = data[0].destination - await api.preparePayment('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', pathfind).then(ret => { - const signed = api.sign(ret.txJSON, fakeSecret) + await client.preparePayment('r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', pathfind).then(ret => { + const signed = client.sign(ret.txJSON, fakeSecret) console.log('signed:', signed) }).catch(err => { console.log('ERR 1:', JSON.stringify(err)) @@ -43,5 +43,5 @@ async function sign() { console.log('ERR 2:', err) }) - api.disconnect() + client.disconnect() } diff --git a/snippets/src/reliableTransactionSubmission.ts b/snippets/src/reliableTransactionSubmission.ts index 2ef28a84..ee7bf06d 100644 --- a/snippets/src/reliableTransactionSubmission.ts +++ b/snippets/src/reliableTransactionSubmission.ts @@ -1,5 +1,5 @@ import { - RippleAPI, + Client, AccountInfoResponse, LedgerClosedEvent } from '../../dist/npm' @@ -68,16 +68,16 @@ async function reliableTransactionSubmissionExample() { async function performPayments(payments) { const finalResults = [] const txFinalizedPromises = [] - const api = new RippleAPI({server: 'wss://s.altnet.rippletest.net:51233'}) - await api.connect() + const client = new Client({server: 'wss://s.altnet.rippletest.net:51233'}) + await client.connect() for (let i = 0; i < payments.length; i++) { const payment = payments[i] - const account_info: AccountInfoResponse = await api.request('account_info', { + const account_info: AccountInfoResponse = await client.request('account_info', { account: payment.source.classicAddress, ledger_index: 'current'}) const sequence = account_info.account_data.Sequence - const preparedPayment = await api.preparePayment(payment.source.classicAddress, { + const preparedPayment = await client.preparePayment(payment.source.classicAddress, { source: { address: payment.source.classicAddress, amount: { @@ -95,11 +95,11 @@ async function performPayments(payments) { }, { sequence }) - const signed = api.sign(preparedPayment.txJSON, payment.source.secret) + const signed = client.sign(preparedPayment.txJSON, payment.source.secret) finalResults.push({ id: signed.id }) - const result = await api.submit(signed.signedTransaction) + const result = await client.submit(signed.signedTransaction) // Most of the time we'll get 'tesSUCCESS' or (after many submissions) 'terQUEUED' console.log(`tx ${i} - tentative: ${result.resultCode}`) @@ -108,7 +108,7 @@ async function performPayments(payments) { const ledgerClosedCallback = async (event: LedgerClosedEvent) => { let status try { - status = await api.getTransaction(signed.id) + status = await client.getTransaction(signed.id) } catch (e) { // Typical error when the tx hasn't been validated yet: if (e.name !== 'MissingLedgerHistoryError') { @@ -125,7 +125,7 @@ async function performPayments(payments) { } } else { // Check again later: - api.connection.once('ledgerClosed', ledgerClosedCallback) + client.connection.once('ledgerClosed', ledgerClosedCallback) return } } @@ -145,7 +145,7 @@ async function performPayments(payments) { } } } - api.connection.once('ledgerClosed', ledgerClosedCallback) + client.connection.once('ledgerClosed', ledgerClosedCallback) }) txFinalizedPromises.push(txFinalizedPromise) } diff --git a/src/broadcast.ts b/src/broadcast.ts index 4d132629..a319490a 100644 --- a/src/broadcast.ts +++ b/src/broadcast.ts @@ -1,47 +1,47 @@ -import {RippleAPI, APIOptions} from './api' +import {Client, ClientOptions} from './client' -class RippleAPIBroadcast extends RippleAPI { +class ClientBroadcast extends Client { ledgerVersion: number | undefined = undefined - private _apis: RippleAPI[] + private _clients: Client[] - constructor(servers, options: APIOptions = {}) { + constructor(servers, options: ClientOptions = {}) { super(options) - const apis: RippleAPI[] = servers.map( - (server) => new RippleAPI(Object.assign({}, options, {server})) + const clients: Client[] = servers.map( + (server) => new Client(Object.assign({}, options, {server})) ) // exposed for testing - this._apis = apis + this._clients = clients this.getMethodNames().forEach((name) => { this[name] = function () { // eslint-disable-line no-loop-func - return Promise.race(apis.map((api) => api[name](...arguments))) + return Promise.race(clients.map((client) => client[name](...arguments))) } }) - // connection methods must be overridden to apply to all api instances + // connection methods must be overridden to apply to all client instances this.connect = async function () { - await Promise.all(apis.map((api) => api.connect())) + await Promise.all(clients.map((client) => client.connect())) } this.disconnect = async function () { - await Promise.all(apis.map((api) => api.disconnect())) + await Promise.all(clients.map((client) => client.disconnect())) } this.isConnected = function () { - return apis.map((api) => api.isConnected()).every(Boolean) + return clients.map((client) => client.isConnected()).every(Boolean) } - // synchronous methods are all passed directly to the first api instance - const defaultAPI = apis[0] + // synchronous methods are all passed directly to the first client instance + const defaultClient = clients[0] const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash'] syncMethods.forEach((name) => { - this[name] = defaultAPI[name].bind(defaultAPI) + this[name] = defaultClient[name].bind(defaultClient) }) - apis.forEach((api) => { - api.on('ledger', this.onLedgerEvent.bind(this)) - api.on('error', (errorCode, errorMessage, data) => + clients.forEach((client) => { + client.on('ledger', this.onLedgerEvent.bind(this)) + client.on('error', (errorCode, errorMessage, data) => this.emit('error', errorCode, errorMessage, data) ) }) @@ -59,9 +59,9 @@ class RippleAPIBroadcast extends RippleAPI { getMethodNames() { const methodNames: string[] = [] - const rippleAPI = this._apis[0] - for (const name of Object.getOwnPropertyNames(rippleAPI)) { - if (typeof rippleAPI[name] === 'function') { + const Client = this._clients[0] + for (const name of Object.getOwnPropertyNames(Client)) { + if (typeof Client[name] === 'function') { methodNames.push(name) } } @@ -69,4 +69,4 @@ class RippleAPIBroadcast extends RippleAPI { } } -export {RippleAPIBroadcast} +export {ClientBroadcast} diff --git a/src/api.ts b/src/client/index.ts similarity index 81% rename from src/api.ts rename to src/client/index.ts index 6f1ef1ce..bd2a4449 100644 --- a/src/api.ts +++ b/src/client/index.ts @@ -9,52 +9,48 @@ import { rippleTimeToISO8601, iso8601ToRippleTime, txFlags, - ensureClassicAddress -} from './common' + ensureClassicAddress, +} from '../common' import { - connect, - disconnect, - isConnected, getLedgerVersion, formatLedgerClose -} from './server/server' -import getTransaction from './ledger/transaction' -import getTransactions from './ledger/transactions' -import getTrustlines from './ledger/trustlines' -import getBalances from './ledger/balances' -import getBalanceSheet from './ledger/balance-sheet' -import getPaths from './ledger/pathfind' -import getOrders from './ledger/orders' -import {getOrderbook, formatBidsAndAsks} from './ledger/orderbook' -import {getSettings, parseAccountFlags} from './ledger/settings' -import getAccountInfo from './ledger/accountinfo' -import getAccountObjects from './ledger/accountobjects' -import getPaymentChannel from './ledger/payment-channel' -import preparePayment from './transaction/payment' -import prepareTrustline from './transaction/trustline' -import prepareOrder from './transaction/order' -import prepareOrderCancellation from './transaction/ordercancellation' -import prepareEscrowCreation from './transaction/escrow-creation' -import prepareEscrowExecution from './transaction/escrow-execution' -import prepareEscrowCancellation from './transaction/escrow-cancellation' -import preparePaymentChannelCreate from './transaction/payment-channel-create' -import preparePaymentChannelFund from './transaction/payment-channel-fund' -import preparePaymentChannelClaim from './transaction/payment-channel-claim' -import prepareCheckCreate from './transaction/check-create' -import prepareCheckCancel from './transaction/check-cancel' -import prepareCheckCash from './transaction/check-cash' -import prepareSettings from './transaction/settings' -import prepareTicketCreate from './transaction/ticket' -import {sign} from './transaction/sign' -import combine from './transaction/combine' -import submit from './transaction/submit' -import {generateAddress, generateXAddress} from './offline/utils' -import {deriveKeypair, deriveAddress, deriveXAddress} from './offline/derive' -import computeLedgerHash from './offline/ledgerhash' -import signPaymentChannelClaim from './offline/sign-payment-channel-claim' -import verifyPaymentChannelClaim from './offline/verify-payment-channel-claim' -import getLedger from './ledger/ledger' - +} from './utils' +import getTransaction from '../ledger/transaction' +import getTransactions from '../ledger/transactions' +import getTrustlines from '../ledger/trustlines' +import getBalances from '../ledger/balances' +import getBalanceSheet from '../ledger/balance-sheet' +import getPaths from '../ledger/pathfind' +import getOrders from '../ledger/orders' +import {getOrderbook, formatBidsAndAsks} from '../ledger/orderbook' +import {getSettings, parseAccountFlags} from '../ledger/settings' +import getAccountInfo from '../ledger/accountinfo' +import getAccountObjects from '../ledger/accountobjects' +import getPaymentChannel from '../ledger/payment-channel' +import preparePayment from '../transaction/payment' +import prepareTrustline from '../transaction/trustline' +import prepareOrder from '../transaction/order' +import prepareOrderCancellation from '../transaction/ordercancellation' +import prepareEscrowCreation from '../transaction/escrow-creation' +import prepareEscrowExecution from '../transaction/escrow-execution' +import prepareEscrowCancellation from '../transaction/escrow-cancellation' +import preparePaymentChannelCreate from '../transaction/payment-channel-create' +import preparePaymentChannelFund from '../transaction/payment-channel-fund' +import preparePaymentChannelClaim from '../transaction/payment-channel-claim' +import prepareCheckCreate from '../transaction/check-create' +import prepareCheckCancel from '../transaction/check-cancel' +import prepareCheckCash from '../transaction/check-cash' +import prepareSettings from '../transaction/settings' +import prepareTicketCreate from '../transaction/ticket' +import {sign} from '../transaction/sign' +import combine from '../transaction/combine' +import submit from '../transaction/submit' +import { generateAddress, generateXAddress } from '../offline/utils' +import {deriveKeypair, deriveAddress, deriveXAddress} from '../offline/derive' +import computeLedgerHash from '../offline/ledgerhash' +import signPaymentChannelClaim from '../offline/sign-payment-channel-claim' +import verifyPaymentChannelClaim from '../offline/verify-payment-channel-claim' +import getLedger from '../ledger/ledger' import { AccountObjectsRequest, AccountObjectsResponse, @@ -76,16 +72,16 @@ import { LedgerEntryResponse, ServerInfoRequest, ServerInfoResponse -} from './common/types/commands' +} from '../common/types/commands' -import RangeSet from './common/rangeset' -import * as ledgerUtils from './ledger/utils' -import * as transactionUtils from './transaction/utils' -import * as schemaValidator from './common/schema-validator' -import {getServerInfo, getFee} from './common/serverinfo' -import {clamp, renameCounterpartyToIssuer} from './ledger/utils' -import {TransactionJSON, Instructions, Prepare} from './transaction/types' -import {ConnectionUserOptions} from './common/connection' +import RangeSet from '../common/rangeset' +import * as ledgerUtils from '../ledger/utils' +import * as transactionUtils from '../transaction/utils' +import * as schemaValidator from '../common/schema-validator' +import {getServerInfo, getFee} from '../common/serverinfo' +import {clamp, renameCounterpartyToIssuer} from '../ledger/utils' +import {TransactionJSON, Instructions, Prepare} from '../transaction/types' +import {ConnectionUserOptions} from '../common/connection' import { classicAddressToXAddress, xAddressToClassicAddress, @@ -114,11 +110,11 @@ import { computeStateTreeHash, computeEscrowHash, computePaymentChannelHash -} from './common/hashes' +} from '../common/hashes' -import generateFaucetWallet from './wallet/wallet-generation' +import generateFaucetWallet from '../wallet/wallet-generation' -export interface APIOptions extends ConnectionUserOptions { +export interface ClientOptions extends ConnectionUserOptions { server?: string feeCushion?: number maxFeeXRP?: string @@ -143,7 +139,7 @@ function getCollectKeyFromCommand(command: string): string | undefined { } } -class RippleAPI extends EventEmitter { +class Client extends EventEmitter { _feeCushion: number _maxFeeXRP: string @@ -151,7 +147,7 @@ class RippleAPI extends EventEmitter { // non-validated ledger versions are allowed, and passed to rippled as-is. connection: Connection - // these are exposed only for use by unit tests; they are not part of the API. + // these are exposed only for use by unit tests; they are not part of the client. static _PRIVATE = { validate, RangeSet, @@ -162,7 +158,7 @@ class RippleAPI extends EventEmitter { static renameCounterpartyToIssuer = renameCounterpartyToIssuer static formatBidsAndAsks = formatBidsAndAsks - constructor(options: APIOptions = {}) { + constructor(options: ClientOptions = {}) { super() validate.apiOptions(options) this._feeCushion = options.feeCushion || 1.2 @@ -196,7 +192,7 @@ class RippleAPI extends EventEmitter { } /** - * Makes a request to the API with the given command and + * Makes a request to the client with the given command and * additional request body parameters. */ async request( @@ -300,7 +296,7 @@ class RippleAPI extends EventEmitter { } /** - * Makes multiple paged requests to the API to return a given number of + * Makes multiple paged requests to the client to return a given number of * resources. _requestAll() will make multiple requests until the `limit` * number of resources is reached (if no `limit` is provided, a single request * will be made). @@ -369,9 +365,20 @@ class RippleAPI extends EventEmitter { generateAddress = generateAddress generateXAddress = generateXAddress // @deprecated Invoke from top-level package instead - connect = connect - disconnect = disconnect - isConnected = isConnected + isConnected(): boolean { + return this.connection.isConnected() + } + + async connect(): Promise { + return this.connection.connect() + } + + 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() + } + getServerInfo = getServerInfo getFee = getFee getLedgerVersion = getLedgerVersion @@ -409,7 +416,7 @@ class RippleAPI extends EventEmitter { sign = sign combine = combine - submit = submit // @deprecated Use api.request('submit', { tx_blob: signedTransaction }) instead + submit = submit // @deprecated Use client.request('submit', { tx_blob: signedTransaction }) instead deriveKeypair = deriveKeypair // @deprecated Invoke from top-level package instead deriveAddress = deriveAddress // @deprecated Invoke from top-level package instead @@ -423,7 +430,7 @@ class RippleAPI extends EventEmitter { static deriveXAddress = deriveXAddress - // RippleAPI.deriveClassicAddress (static) is a new name for api.deriveAddress + // Client.deriveClassicAddress (static) is a new name for client.deriveAddress static deriveClassicAddress = deriveAddress /** @@ -495,7 +502,9 @@ class RippleAPI extends EventEmitter { isValidSecret = schemaValidator.isValidSecret } -export {RippleAPI} +export { + Client +} export type { AccountObjectsRequest, diff --git a/src/server/server.ts b/src/client/utils.ts similarity index 50% rename from src/server/server.ts rename to src/client/utils.ts index 2109c8d7..9a17ca16 100644 --- a/src/server/server.ts +++ b/src/client/utils.ts @@ -1,24 +1,10 @@ import * as common from '../common' -import {RippleAPI} from '..' +import {Client} from '..' -function isConnected(this: RippleAPI): boolean { - return this.connection.isConnected() -} - -function getLedgerVersion(this: RippleAPI): Promise { +function getLedgerVersion(this: Client): Promise { return this.connection.getLedgerVersion() } -async function connect(this: RippleAPI): Promise { - return this.connection.connect() -} - -async function disconnect(this: RippleAPI): 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() -} - function formatLedgerClose(ledgerClose: any): object { return { baseFeeXRP: common.dropsToXrp(ledgerClose.fee_base), @@ -32,4 +18,4 @@ function formatLedgerClose(ledgerClose: any): object { } } -export {connect, disconnect, isConnected, getLedgerVersion, formatLedgerClose} +export {getLedgerVersion, formatLedgerClose} diff --git a/src/common/connection.ts b/src/common/connection.ts index 05122cfd..afb277d9 100644 --- a/src/common/connection.ts +++ b/src/common/connection.ts @@ -489,7 +489,7 @@ 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 RippleAPI constructor.` + `You can also try setting the 'connectionTimeout' option in the Client constructor.` ) ) }, this._config.connectionTimeout) diff --git a/src/common/schemas/input/get-fee.json b/src/common/schemas/input/get-fee.json index 207537d9..4250b271 100644 --- a/src/common/schemas/input/get-fee.json +++ b/src/common/schemas/input/get-fee.json @@ -6,7 +6,7 @@ "properties": { "cushion": { "type": "number", - "description": "The fee is the product of the base fee, the `load_factor`, and this cushion. Default is provided by the `RippleAPI` constructor's `feeCushion`." + "description": "The fee is the product of the base fee, the `load_factor`, and this cushion. Default is provided by the `Client` constructor's `feeCushion`." } }, "additionalProperties": false diff --git a/src/common/schemas/objects/instructions.json b/src/common/schemas/objects/instructions.json index cd5989ac..ef7da3fe 100644 --- a/src/common/schemas/objects/instructions.json +++ b/src/common/schemas/objects/instructions.json @@ -18,7 +18,7 @@ "$ref": "value" }, "maxFee": { - "description": "Deprecated: Use `maxFeeXRP` in the RippleAPI constructor instead. The maximum fee to pay for this transaction. If this exceeds `maxFeeXRP`, use `maxFeeXRP` instead. See [Transaction Fees](#transaction-fees) for more information.", + "description": "Deprecated: Use `maxFeeXRP` in the Client constructor instead. The maximum fee to pay for this transaction. If this exceeds `maxFeeXRP`, use `maxFeeXRP` instead. See [Transaction Fees](#transaction-fees) for more information.", "$ref": "value" }, "maxLedgerVersion": { diff --git a/src/common/serverinfo.ts b/src/common/serverinfo.ts index ca59ff05..00dd7505 100644 --- a/src/common/serverinfo.ts +++ b/src/common/serverinfo.ts @@ -1,7 +1,7 @@ import * as _ from 'lodash' import {convertKeysFromSnakeCaseToCamelCase} from './utils' import BigNumber from 'bignumber.js' -import {RippleAPI} from '..' +import {Client} from '..' export type GetServerInfoResponse = { buildVersion: string @@ -41,7 +41,7 @@ function renameKeys(object: Record, mapping: Record) { }) } -function getServerInfo(this: RippleAPI): Promise { +function getServerInfo(this: Client): Promise { return this.request('server_info').then((response) => { const info = convertKeysFromSnakeCaseToCamelCase(response.info) renameKeys(info, {hostid: 'hostID'}) @@ -62,7 +62,7 @@ function getServerInfo(this: RippleAPI): Promise { // This is a public API that can be called directly. // This is not used by the `prepare*` methods. See `src/transaction/utils.ts` -async function getFee(this: RippleAPI, cushion?: number): Promise { +async function getFee(this: Client, cushion?: number): Promise { if (cushion == null) { cushion = this._feeCushion } diff --git a/src/index.ts b/src/index.ts index aedff091..fa93f512 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -export * from './api' +export * from './client' export * from './transaction/types' @@ -6,7 +6,7 @@ export * from './common/types/objects/ledger' export * from './offline/utils' -// Broadcast api is experimental -export {RippleAPIBroadcast} from './broadcast' +// Broadcast client is experimental +export {ClientBroadcast} from './broadcast' export * from './Wallet' diff --git a/src/ledger/accountinfo.ts b/src/ledger/accountinfo.ts index ca0ca686..c4186b3e 100644 --- a/src/ledger/accountinfo.ts +++ b/src/ledger/accountinfo.ts @@ -4,7 +4,7 @@ import { dropsToXrp, ensureClassicAddress } from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import {AccountInfoResponse} from '../common/types/commands/account_info' export type GetAccountInfoOptions = { @@ -35,7 +35,7 @@ function formatAccountInfo( } export default async function getAccountInfo( - this: RippleAPI, + this: Client, address: string, options: GetAccountInfoOptions = {} ): Promise { diff --git a/src/ledger/accountobjects.ts b/src/ledger/accountobjects.ts index 80fcc5fa..dfb61436 100644 --- a/src/ledger/accountobjects.ts +++ b/src/ledger/accountobjects.ts @@ -1,12 +1,12 @@ import {removeUndefined} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import { GetAccountObjectsOptions, AccountObjectsResponse } from '../common/types/commands/account_objects' export default async function getAccountObjects( - this: RippleAPI, + this: Client, address: string, options: GetAccountObjectsOptions = {} ): Promise { diff --git a/src/ledger/balance-sheet.ts b/src/ledger/balance-sheet.ts index 9d0f6efd..a9183dd9 100644 --- a/src/ledger/balance-sheet.ts +++ b/src/ledger/balance-sheet.ts @@ -2,7 +2,7 @@ import * as _ from 'lodash' import {validate} from '../common' import {Amount} from '../common/types/objects' import {ensureLedgerVersion} from './utils' -import {RippleAPI} from '..' +import {Client} from '..' export type BalanceSheetOptions = { excludeAddresses?: Array @@ -57,7 +57,7 @@ function formatBalanceSheet(balanceSheet: BalanceSheet): GetBalanceSheet { } async function getBalanceSheet( - this: RippleAPI, + this: Client, address: string, options: BalanceSheetOptions = {} ): Promise { diff --git a/src/ledger/balances.ts b/src/ledger/balances.ts index 319da126..679faa15 100644 --- a/src/ledger/balances.ts +++ b/src/ledger/balances.ts @@ -3,7 +3,7 @@ import {validate, ensureClassicAddress} from '../common' import {Connection} from '../common' import {GetTrustlinesOptions} from './trustlines' import {FormattedTrustline} from '../common/types/objects/trustlines' -import {RippleAPI} from '..' +import {Client} from '..' export type Balance = { value: string @@ -50,7 +50,7 @@ function getLedgerVersionHelper( } function getBalances( - this: RippleAPI, + this: Client, address: string, options: GetTrustlinesOptions = {} ): Promise { diff --git a/src/ledger/ledger.ts b/src/ledger/ledger.ts index 2ee25613..3652f779 100644 --- a/src/ledger/ledger.ts +++ b/src/ledger/ledger.ts @@ -1,6 +1,6 @@ import {validate} from '../common' import {FormattedLedger, parseLedger} from './parse/ledger' -import {RippleAPI} from '..' +import {Client} from '..' export type GetLedgerOptions = { ledgerHash?: string @@ -11,7 +11,7 @@ export type GetLedgerOptions = { } async function getLedger( - this: RippleAPI, + this: Client, options: GetLedgerOptions = {} ): Promise { // 1. Validate diff --git a/src/ledger/orderbook.ts b/src/ledger/orderbook.ts index d15d27d4..6b09a008 100644 --- a/src/ledger/orderbook.ts +++ b/src/ledger/orderbook.ts @@ -7,7 +7,7 @@ import { import {validate} from '../common' import {Issue} from '../common/types/objects' import {BookOffer} from '../common/types/commands' -import {RippleAPI} from '..' +import {Client} from '..' import BigNumber from 'bignumber.js' export type FormattedOrderbook = { @@ -71,7 +71,7 @@ export function formatBidsAndAsks( // account is to specify a "perspective", which affects which unfunded offers // are returned async function makeRequest( - api: RippleAPI, + client: Client, taker: string, options: GetOrderbookOptions, takerGets: Issue, @@ -81,7 +81,7 @@ async function makeRequest( taker_gets: takerGets, taker_pays: takerPays }) - return api._requestAll('book_offers', { + return client._requestAll('book_offers', { taker_gets: orderData.taker_gets, taker_pays: orderData.taker_pays, ledger_index: options.ledgerVersion || 'validated', @@ -101,7 +101,7 @@ export type OrderbookInfo = { } export async function getOrderbook( - this: RippleAPI, + this: Client, address: string, orderbook: OrderbookInfo, options: GetOrderbookOptions = {} diff --git a/src/ledger/orders.ts b/src/ledger/orders.ts index 717355a8..3571b4c7 100644 --- a/src/ledger/orders.ts +++ b/src/ledger/orders.ts @@ -1,7 +1,7 @@ import * as _ from 'lodash' import {validate} from '../common' import {FormattedAccountOrder, parseAccountOrder} from './parse/account-order' -import {RippleAPI} from '..' +import {Client} from '..' import {AccountOffersResponse} from '../common/types/commands' export type GetOrdersOptions = { @@ -24,7 +24,7 @@ function formatResponse( } export default async function getOrders( - this: RippleAPI, + this: Client, address: string, options: GetOrdersOptions = {} ): Promise { diff --git a/src/ledger/pathfind.ts b/src/ledger/pathfind.ts index 7df25917..e84443c8 100644 --- a/src/ledger/pathfind.ts +++ b/src/ledger/pathfind.ts @@ -17,7 +17,7 @@ import { RippledPathsResponse, PathFindRequest } from './pathfind-types' -import {RippleAPI} from '..' +import {Client} from '..' const NotFoundError = errors.NotFoundError const ValidationError = errors.ValidationError @@ -185,7 +185,7 @@ function formatResponse(pathfind: PathFind, paths: RippledPathsResponse) { } } -function getPaths(this: RippleAPI, pathfind: PathFind): Promise { +function getPaths(this: Client, pathfind: PathFind): Promise { validate.getPaths({pathfind}) const address = pathfind.source.address diff --git a/src/ledger/payment-channel.ts b/src/ledger/payment-channel.ts index 236328e4..ea88f606 100644 --- a/src/ledger/payment-channel.ts +++ b/src/ledger/payment-channel.ts @@ -3,7 +3,7 @@ import { FormattedPaymentChannel } from './parse/payment-channel' import {validate, errors} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import {LedgerEntryResponse} from '../common/types/commands' const NotFoundError = errors.NotFoundError @@ -20,7 +20,7 @@ function formatResponse( } async function getPaymentChannel( - this: RippleAPI, + this: Client, id: string ): Promise { // 1. Validate diff --git a/src/ledger/settings.ts b/src/ledger/settings.ts index 501358cc..bf141336 100644 --- a/src/ledger/settings.ts +++ b/src/ledger/settings.ts @@ -2,7 +2,7 @@ import parseFields from './parse/fields' import {validate, constants, ensureClassicAddress} from '../common' import {FormattedSettings} from '../common/types/objects' import {AccountInfoResponse} from '../common/types/commands' -import {RippleAPI} from '..' +import {Client} from '..' import {Settings} from '../common/constants' const AccountFlags = constants.AccountFlags @@ -36,7 +36,7 @@ function formatSettings(response: AccountInfoResponse) { } export async function getSettings( - this: RippleAPI, + this: Client, address: string, options: SettingsOptions = {} ): Promise { diff --git a/src/ledger/transaction.ts b/src/ledger/transaction.ts index 77fb69b3..17d7794d 100644 --- a/src/ledger/transaction.ts +++ b/src/ledger/transaction.ts @@ -4,7 +4,7 @@ import {validate, errors} from '../common' import {Connection} from '../common' import {FormattedTransactionType} from '../transaction/types' import {RippledError} from '../common/errors' -import {RippleAPI} from '..' +import {Client} from '..' export type TransactionOptions = { minLedgerVersion?: number @@ -121,7 +121,7 @@ function formatResponse( } async function getTransaction( - this: RippleAPI, + this: Client, id: string, options: TransactionOptions = {} ): Promise { diff --git a/src/ledger/transactions.ts b/src/ledger/transactions.ts index c0175809..4920999c 100644 --- a/src/ledger/transactions.ts +++ b/src/ledger/transactions.ts @@ -6,7 +6,7 @@ import parseTransaction from './parse/transaction' import getTransaction from './transaction' import {validate, errors, Connection, ensureClassicAddress} from '../common' import {FormattedTransactionType} from '../transaction/types' -import {RippleAPI} from '..' +import {Client} from '..' export type TransactionsOptions = { start?: string @@ -189,7 +189,7 @@ function getTransactionsInternal( } function getTransactions( - this: RippleAPI, + this: Client, address: string, options: TransactionsOptions = {} ): Promise { diff --git a/src/ledger/trustlines.ts b/src/ledger/trustlines.ts index a1387bd9..e6198f50 100644 --- a/src/ledger/trustlines.ts +++ b/src/ledger/trustlines.ts @@ -1,7 +1,7 @@ import * as _ from 'lodash' import {validate, ensureClassicAddress} from '../common' import parseAccountTrustline from './parse/account-trustline' -import {RippleAPI} from '..' +import {Client} from '..' import {FormattedTrustline} from '../common/types/objects/trustlines' export type GetTrustlinesOptions = { @@ -16,7 +16,7 @@ function currencyFilter(currency: string, trustline: FormattedTrustline) { } async function getTrustlines( - this: RippleAPI, + this: Client, address: string, options: GetTrustlinesOptions = {} ): Promise { diff --git a/src/ledger/utils.ts b/src/ledger/utils.ts index cdd131a8..684c8780 100644 --- a/src/ledger/utils.ts +++ b/src/ledger/utils.ts @@ -4,7 +4,7 @@ import * as common from '../common' import {Connection} from '../common' import {FormattedTransactionType} from '../transaction/types' import {Issue} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type RecursiveData = { marker: string @@ -121,7 +121,7 @@ function isPendingLedgerVersion( .then((ledgerVersion) => ledgerVersion < (maxLedgerVersion || 0)) } -function ensureLedgerVersion(this: RippleAPI, options: any): Promise { +function ensureLedgerVersion(this: Client, options: any): Promise { if ( Boolean(options) && options.ledgerVersion != null && diff --git a/src/transaction/check-cancel.ts b/src/transaction/check-cancel.ts index bde56a3d..02ac839b 100644 --- a/src/transaction/check-cancel.ts +++ b/src/transaction/check-cancel.ts @@ -1,7 +1,7 @@ import {prepareTransaction} from './utils' import {validate} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' -import {RippleAPI} from '..' +import {Client} from '..' export type CheckCancelParameters = { checkID: string @@ -21,7 +21,7 @@ function createCheckCancelTransaction( } function prepareCheckCancel( - this: RippleAPI, + this: Client, address: string, checkCancel: CheckCancelParameters, instructions: Instructions = {} diff --git a/src/transaction/check-cash.ts b/src/transaction/check-cash.ts index 9bcf338c..49b131e7 100644 --- a/src/transaction/check-cash.ts +++ b/src/transaction/check-cash.ts @@ -4,7 +4,7 @@ const toRippledAmount = utils.common.toRippledAmount import {validate} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' import {Amount} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type CheckCashParameters = { checkID: string @@ -41,7 +41,7 @@ function createCheckCashTransaction( } function prepareCheckCash( - this: RippleAPI, + this: Client, address: string, checkCash: CheckCashParameters, instructions: Instructions = {} diff --git a/src/transaction/check-create.ts b/src/transaction/check-create.ts index 1cc4cf61..1a53f843 100644 --- a/src/transaction/check-create.ts +++ b/src/transaction/check-create.ts @@ -3,7 +3,7 @@ const toRippledAmount = utils.common.toRippledAmount import {validate, iso8601ToRippleTime} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' import {Amount} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type CheckCreateParameters = { destination: string @@ -40,7 +40,7 @@ function createCheckCreateTransaction( } function prepareCheckCreate( - this: RippleAPI, + this: Client, address: string, checkCreate: CheckCreateParameters, instructions: Instructions = {} diff --git a/src/transaction/escrow-cancellation.ts b/src/transaction/escrow-cancellation.ts index 2cb0e670..4feb0537 100644 --- a/src/transaction/escrow-cancellation.ts +++ b/src/transaction/escrow-cancellation.ts @@ -2,7 +2,7 @@ import * as utils from './utils' const validate = utils.common.validate import {Instructions, Prepare, TransactionJSON} from './types' import {Memo} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type EscrowCancellation = { owner: string @@ -30,7 +30,7 @@ function createEscrowCancellationTransaction( } function prepareEscrowCancellation( - this: RippleAPI, + this: Client, address: string, escrowCancellation: EscrowCancellation, instructions: Instructions = {} diff --git a/src/transaction/escrow-creation.ts b/src/transaction/escrow-creation.ts index 50eaca4f..a214b981 100644 --- a/src/transaction/escrow-creation.ts +++ b/src/transaction/escrow-creation.ts @@ -3,7 +3,7 @@ import {validate, iso8601ToRippleTime, xrpToDrops} from '../common' const ValidationError = utils.common.errors.ValidationError import {Instructions, Prepare, TransactionJSON} from './types' import {Memo} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type EscrowCreation = { amount: string @@ -59,7 +59,7 @@ function createEscrowCreationTransaction( } function prepareEscrowCreation( - this: RippleAPI, + this: Client, address: string, escrowCreation: EscrowCreation, instructions: Instructions = {} diff --git a/src/transaction/escrow-execution.ts b/src/transaction/escrow-execution.ts index 011bba6e..f7065895 100644 --- a/src/transaction/escrow-execution.ts +++ b/src/transaction/escrow-execution.ts @@ -3,7 +3,7 @@ const validate = utils.common.validate const ValidationError = utils.common.errors.ValidationError import {Instructions, Prepare, TransactionJSON} from './types' import {Memo} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' export type EscrowExecution = { owner: string @@ -44,7 +44,7 @@ function createEscrowExecutionTransaction( } function prepareEscrowExecution( - this: RippleAPI, + this: Client, address: string, escrowExecution: EscrowExecution, instructions: Instructions = {} diff --git a/src/transaction/order.ts b/src/transaction/order.ts index 6dc125ca..e6967574 100644 --- a/src/transaction/order.ts +++ b/src/transaction/order.ts @@ -3,7 +3,7 @@ const offerFlags = utils.common.txFlags.OfferCreate import {validate, iso8601ToRippleTime, toRippledAmount} from '../common' import {Instructions, Prepare, OfferCreateTransaction} from './types' import {FormattedOrderSpecification} from '../common/types/objects/index' -import {RippleAPI} from '..' +import {Client} from '..' function createOrderTransaction( account: string, @@ -48,7 +48,7 @@ function createOrderTransaction( } function prepareOrder( - this: RippleAPI, + this: Client, address: string, order: FormattedOrderSpecification, instructions: Instructions = {} diff --git a/src/transaction/ordercancellation.ts b/src/transaction/ordercancellation.ts index 57f1e7d5..0aed83fc 100644 --- a/src/transaction/ordercancellation.ts +++ b/src/transaction/ordercancellation.ts @@ -1,7 +1,7 @@ import * as utils from './utils' const validate = utils.common.validate import {Instructions, Prepare, TransactionJSON} from './types' -import {RippleAPI} from '..' +import {Client} from '..' function createOrderCancellationTransaction( account: string, @@ -19,7 +19,7 @@ function createOrderCancellationTransaction( } function prepareOrderCancellation( - this: RippleAPI, + this: Client, address: string, orderCancellation: object, instructions: Instructions = {} diff --git a/src/transaction/payment-channel-claim.ts b/src/transaction/payment-channel-claim.ts index 2dd8c908..8afed802 100644 --- a/src/transaction/payment-channel-claim.ts +++ b/src/transaction/payment-channel-claim.ts @@ -3,7 +3,7 @@ const ValidationError = utils.common.errors.ValidationError const claimFlags = utils.common.txFlags.PaymentChannelClaim import {validate, xrpToDrops} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' -import {RippleAPI} from '..' +import {Client} from '..' export type PaymentChannelClaim = { channel: string @@ -65,7 +65,7 @@ function createPaymentChannelClaimTransaction( } function preparePaymentChannelClaim( - this: RippleAPI, + this: Client, address: string, paymentChannelClaim: PaymentChannelClaim, instructions: Instructions = {} diff --git a/src/transaction/payment-channel-create.ts b/src/transaction/payment-channel-create.ts index eaf627cf..7165e941 100644 --- a/src/transaction/payment-channel-create.ts +++ b/src/transaction/payment-channel-create.ts @@ -1,7 +1,7 @@ import * as utils from './utils' import {validate, iso8601ToRippleTime, xrpToDrops} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' -import {RippleAPI} from '..' +import {Client} from '..' export type PaymentChannelCreate = { amount: string @@ -40,7 +40,7 @@ function createPaymentChannelCreateTransaction( } function preparePaymentChannelCreate( - this: RippleAPI, + this: Client, address: string, paymentChannelCreate: PaymentChannelCreate, instructions: Instructions = {} diff --git a/src/transaction/payment-channel-fund.ts b/src/transaction/payment-channel-fund.ts index d22bf1bc..f6d941c4 100644 --- a/src/transaction/payment-channel-fund.ts +++ b/src/transaction/payment-channel-fund.ts @@ -1,7 +1,7 @@ import * as utils from './utils' import {validate, iso8601ToRippleTime, xrpToDrops} from '../common' import {Instructions, Prepare, TransactionJSON} from './types' -import {RippleAPI} from '..' +import {Client} from '..' export type PaymentChannelFund = { channel: string @@ -28,7 +28,7 @@ function createPaymentChannelFundTransaction( } function preparePaymentChannelFund( - this: RippleAPI, + this: Client, address: string, paymentChannelFund: PaymentChannelFund, instructions: Instructions = {} diff --git a/src/transaction/payment.ts b/src/transaction/payment.ts index b94cb192..c29e3972 100644 --- a/src/transaction/payment.ts +++ b/src/transaction/payment.ts @@ -12,7 +12,7 @@ import { Memo } from '../common/types/objects' import {toRippledAmount, xrpToDrops} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import {getClassicAccountAndTag, ClassicAccountAndTag} from './utils' export interface Payment { @@ -244,7 +244,7 @@ function createPaymentTransaction( } function preparePayment( - this: RippleAPI, + this: Client, address: string, payment: Payment, instructions: Instructions = {} diff --git a/src/transaction/settings.ts b/src/transaction/settings.ts index 104a1b85..0f8fe99f 100644 --- a/src/transaction/settings.ts +++ b/src/transaction/settings.ts @@ -11,7 +11,7 @@ import { TransactionJSON } from './types' import {FormattedSettings, WeightedSigner} from '../common/types/objects' -import {RippleAPI} from '..' +import {Client} from '..' function setTransactionFlags( txJSON: TransactionJSON, @@ -149,7 +149,7 @@ function createSettingsTransaction( } function prepareSettings( - this: RippleAPI, + this: Client, address: string, settings: FormattedSettings, instructions: Instructions = {} diff --git a/src/transaction/sign.ts b/src/transaction/sign.ts index 048c9b7c..a9b28230 100644 --- a/src/transaction/sign.ts +++ b/src/transaction/sign.ts @@ -6,7 +6,7 @@ import {computeBinaryTransactionHash} from '../common/hashes' import {SignOptions, KeyPair, TransactionJSON} from './types' import BigNumber from 'bignumber.js' import {xrpToDrops} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import Wallet from '../Wallet' import {SignedTransaction} from '../common/types/objects' const validate = utils.common.validate @@ -19,7 +19,7 @@ function computeSignature(tx: object, privateKey: string, signAs?: string) { } function signWithKeypair( - api: RippleAPI, + client: Client, txJSON: string, keypair: KeyPair, options: SignOptions = { @@ -27,7 +27,7 @@ function signWithKeypair( } ): SignedTransaction { validate.sign({txJSON, keypair}) - const isOnline = !!api; + const isOnline = !!client; const tx = JSON.parse(txJSON) if (tx.TxnSignature || tx.Signers) { @@ -37,7 +37,7 @@ function signWithKeypair( } if (isOnline) { - checkFee(api, tx.Fee) + checkFee(client, tx.Fee) } const txToSignAndEncode = Object.assign({}, tx) @@ -202,24 +202,24 @@ function checkTxSerialization(serialized: string, tx: TransactionJSON): void { * * See https://xrpl.org/rippleapi-reference.html#parameters * - * @param {RippleAPI} api A RippleAPI instance. + * @param {Client} client A Client instance. * @param {string} txFee The transaction fee in drops, encoded as a string. * * @returns {void} This method does not return a value, but throws an error if the check fails. */ -function checkFee(api: RippleAPI, txFee: string): void { +function checkFee(client: Client, txFee: string): void { const fee = new BigNumber(txFee) - const maxFeeDrops = xrpToDrops(api._maxFeeXRP) + 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 RippleAPI constructor.' + 'To use a higher fee, set `maxFeeXRP` in the Client constructor.' ) } } function sign( - this: RippleAPI, + this: Client, txJSON: string, secret?: any, options?: SignOptions, diff --git a/src/transaction/submit.ts b/src/transaction/submit.ts index f961ca1f..ea70efdd 100644 --- a/src/transaction/submit.ts +++ b/src/transaction/submit.ts @@ -1,12 +1,12 @@ -// Deprecated - use api.request instead: -// const response = await api.request('submit', { +// Deprecated - use client.request instead: +// const response = await client.request('submit', { // tx_blob: signedTransaction, // fail_hard: failHard // }); import * as utils from './utils' import {validate} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' export interface FormattedSubmitResponse { resultCode: string @@ -41,9 +41,9 @@ function formatSubmitResponse(response): FormattedSubmitResponse { return data } -// @deprecated Use api.request('submit', { tx_blob: signedTransaction }) instead +// @deprecated Use client.request('submit', { tx_blob: signedTransaction }) instead async function submit( - this: RippleAPI, + this: Client, signedTransaction: string, failHard?: boolean ): Promise { diff --git a/src/transaction/ticket.ts b/src/transaction/ticket.ts index 0406abfa..89e18baf 100644 --- a/src/transaction/ticket.ts +++ b/src/transaction/ticket.ts @@ -1,7 +1,7 @@ import * as _ from 'lodash' import * as utils from './utils' import {Prepare, TransactionJSON, Instructions} from './types' -import {RippleAPI} from '..' +import {Client} from '..' const validate = utils.common.validate const ValidationError = utils.common.errors.ValidationError @@ -28,7 +28,7 @@ function createTicketTransaction( } function prepareTicketCreate( - this: RippleAPI, + this: Client, address: string, ticketCount: number, instructions: Instructions = {} diff --git a/src/transaction/trustline.ts b/src/transaction/trustline.ts index 9ebf6a4e..3120303c 100644 --- a/src/transaction/trustline.ts +++ b/src/transaction/trustline.ts @@ -4,7 +4,7 @@ const validate = utils.common.validate const trustlineFlags = utils.common.txFlags.TrustSet import {Instructions, Prepare, TransactionJSON} from './types' import {FormattedTrustlineSpecification} from '../common/types/objects/trustlines' -import {RippleAPI} from '..' +import {Client} from '..' function convertQuality(quality) { return new BigNumber(quality) @@ -55,7 +55,7 @@ function createTrustlineTransaction( } function prepareTrustline( - this: RippleAPI, + this: Client, address: string, trustline: FormattedTrustlineSpecification, instructions: Instructions = {} diff --git a/src/transaction/utils.ts b/src/transaction/utils.ts index 9ce88e74..9360a788 100644 --- a/src/transaction/utils.ts +++ b/src/transaction/utils.ts @@ -3,7 +3,7 @@ import * as common from '../common' import {Memo} from '../common/types/objects' import {Instructions, Prepare, TransactionJSON} from './types' import {toRippledAmount} from '../common' -import {RippleAPI} from '..' +import {Client} from '..' import {ValidationError} from '../common/errors' import {xAddressToClassicAddress, isValidXAddress} from 'ripple-address-codec' @@ -110,7 +110,7 @@ function getClassicAccountAndTag( function prepareTransaction( txJSON: TransactionJSON, - api: RippleAPI, + client: Client, instructions: Instructions ): Promise { common.validate.instructions(instructions) @@ -269,7 +269,7 @@ function prepareTransaction( instructions.maxLedgerVersionOffset != null ? instructions.maxLedgerVersionOffset : 3 - return api.connection.getLedgerVersion().then((ledgerVersion) => { + return client.connection.getLedgerVersion().then((ledgerVersion) => { newTxJSON.LastLedgerSequence = ledgerVersion + offset return }) @@ -298,12 +298,12 @@ function prepareTransaction( : instructions.signersCount + 1 if (instructions.fee != null) { const fee = new BigNumber(instructions.fee) - if (fee.isGreaterThan(api._maxFeeXRP)) { + if (fee.isGreaterThan(client._maxFeeXRP)) { return Promise.reject( new ValidationError( `Fee of ${fee.toString(10)} XRP exceeds ` + - `max of ${api._maxFeeXRP} XRP. To use this fee, increase ` + - '`maxFeeXRP` in the RippleAPI constructor.' + `max of ${client._maxFeeXRP} XRP. To use this fee, increase ` + + '`maxFeeXRP` in the Client constructor.' ) ) } @@ -313,9 +313,9 @@ function prepareTransaction( ) return Promise.resolve() } - const cushion = api._feeCushion - return api.getFee(cushion).then((fee) => { - return api.connection.getFeeRef().then((feeRef) => { + const cushion = client._feeCushion + return client.getFee(cushion).then((fee) => { + return client.connection.getFeeRef().then((feeRef) => { // feeRef is the reference transaction cost in "fee units" const extraFee = newTxJSON.TransactionType !== 'EscrowFinish' || @@ -329,8 +329,8 @@ function prepareTransaction( )) const feeDrops = common.xrpToDrops(fee) const maxFeeXRP = instructions.maxFee - ? BigNumber.min(api._maxFeeXRP, instructions.maxFee) - : api._maxFeeXRP + ? BigNumber.min(client._maxFeeXRP, instructions.maxFee) + : client._maxFeeXRP const maxFeeDrops = common.xrpToDrops(maxFeeXRP) const normalFee = scaleValue(feeDrops, multiplier, extraFee) newTxJSON.Fee = BigNumber.min(normalFee, maxFeeDrops).toString(10) @@ -370,7 +370,7 @@ function prepareTransaction( } try { - const response = await api.request('account_info', { + const response = await client.request('account_info', { account: classicAccount, ledger_index: 'current' // Fix #999 }) diff --git a/src/wallet/wallet-generation.ts b/src/wallet/wallet-generation.ts index 68253cf0..f436f1f7 100644 --- a/src/wallet/wallet-generation.ts +++ b/src/wallet/wallet-generation.ts @@ -1,6 +1,6 @@ import https = require('https') -import {RippleAPI} from '..' +import {Client} from '..' import {errors} from '../common' import {GeneratedAddress} from '../offline/generate-address' import {isValidAddress} from '../common/schema-validator' @@ -27,11 +27,11 @@ const MAX_ATTEMPTS = 20 // Maximum attempts to retrieve a balance * @returns - A Wallet on the Testnet or Devnet that contains some amount of XRP. */ async function generateFaucetWallet( - this: RippleAPI, + this: Client, address?: string ): Promise { if(!this.isConnected()) - throw new RippledError("RippleAPI not connected, cannot call faucet") + throw new RippledError("Client not connected, cannot call faucet") // Initialize some variables let body: Uint8Array @@ -136,17 +136,17 @@ async function generateFaucetWallet( /** * Retrieves an XRPL address XRP balance * - * @param api - RippleAPI + * @param client - Client * @param address - XRPL address. * @returns */ async function getAddressXrpBalance( - api: RippleAPI, + client: Client, address: string ): Promise { // Get all the account balances try { - const balances = await api.getBalances(address) + const balances = await client.getBalances(address) // Retrieve the XRP balance const xrpBalance = balances.filter( @@ -161,13 +161,13 @@ async function getAddressXrpBalance( /** * Check at regular interval if the address is enabled on the XRPL and funded * - * @param api - RippleAPI + * @param client - Client * @param address - the account address to check * @param originalBalance - the initial balance before the funding * @returns A Promise boolean */ async function hasAddressBalanceIncreased( - api: RippleAPI, + client: Client, address: string, originalBalance: number ): Promise { @@ -182,7 +182,7 @@ async function hasAddressBalanceIncreased( } try { - const newBalance = +(await getAddressXrpBalance(api, address)) + const newBalance = +(await getAddressXrpBalance(client, address)) if (newBalance > originalBalance) { clearInterval(interval) resolve(true) @@ -200,12 +200,12 @@ async function hasAddressBalanceIncreased( } /** - * Get the faucet URL based on the RippleAPI connection - * @param api - RippleAPI + * Get the faucet URL based on the Client connection + * @param client - Client * @returns A {@link FaucetNetwork} */ -export function getFaucetUrl(api: RippleAPI) { - const connectionUrl = api.connection.getUrl() +export function getFaucetUrl(client: Client) { + const connectionUrl = client.connection.getUrl() // 'altnet' for Ripple Testnet server and 'testnet' for XRPL Labs Testnet server if (connectionUrl.includes('altnet') || connectionUrl.includes('testnet')) { diff --git a/test/api/constructor/index.ts b/test/api/constructor/index.ts deleted file mode 100644 index e88649fb..00000000 --- a/test/api/constructor/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import assert from 'assert-diff' -import {TestSuite} from '../../utils' -import {RippleAPI} from 'ripple-api' - -/** - * Every test suite exports their tests in the default object. - * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. - */ -export default { - 'RippleAPI - implicit server port': () => { - new RippleAPI({server: 'wss://s1.ripple.com'}) - }, - - 'RippleAPI invalid options': () => { - // @ts-ignore - This is intentionally invalid - assert.throws(() => new RippleAPI({invalid: true})) - }, - - 'RippleAPI valid options': () => { - const api = new RippleAPI({server: 'wss://s:1'}) - const privateConnectionUrl = (api.connection as any)._url - assert.deepEqual(privateConnectionUrl, 'wss://s:1') - }, - - 'RippleAPI invalid server uri': () => { - assert.throws(() => new RippleAPI({server: 'wss//s:1'})) - } -} diff --git a/test/api/getBalanceSheet/index.ts b/test/api/getBalanceSheet/index.ts deleted file mode 100644 index ecc93d4f..00000000 --- a/test/api/getBalanceSheet/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {assertRejects, assertResultMatch, TestSuite} from '../../utils' - -/** - * Every test suite exports their tests in the default object. - * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. - */ -export default { - 'getBalanceSheet': async (api, address) => { - await api.getBalanceSheet(address) - }, - - 'getBalanceSheet - invalid options': async (api, address) => { - await assertRejects( - // @ts-ignore - This is intentionally invalid - api.getBalanceSheet(address, {invalid: 'options'}), - api.errors.ValidationError - ) - }, - - 'getBalanceSheet - empty': async (api, address) => { - const options = {ledgerVersion: 123456} - const result = await api.getBalanceSheet(address, options) - assertResultMatch(result, {}, 'getBalanceSheet') - } -} diff --git a/test/api/hasNextPage/index.ts b/test/api/hasNextPage/index.ts deleted file mode 100644 index d2a6a5e0..00000000 --- a/test/api/hasNextPage/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from 'assert-diff' -import {TestSuite} from '../../utils' - -/** - * Every test suite exports their tests in the default object. - * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. - */ -export default { - 'returns true when there is another page': async (api, address) => { - const response = await api.request('ledger_data') - assert(api.hasNextPage(response)) - }, - - 'returns false when there are no more pages': async (api, address) => { - const response = await api.request('ledger_data') - const responseNextPage = await api.requestNextPage( - 'ledger_data', - {}, - response - ) - assert(!api.hasNextPage(responseNextPage)) - } -} diff --git a/test/api/isConnected/index.ts b/test/api/isConnected/index.ts deleted file mode 100644 index c5660409..00000000 --- a/test/api/isConnected/index.ts +++ /dev/null @@ -1,15 +0,0 @@ -import assert from 'assert-diff' -import {TestSuite} from '../../utils' - -/** - * Every test suite exports their tests in the default object. - * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. - */ -export default { - 'disconnect & isConnected': async (api, address) => { - assert.strictEqual(api.isConnected(), true) - await api.disconnect() - assert.strictEqual(api.isConnected(), false) - } -} diff --git a/test/api/isValidAddress/index.ts b/test/api/isValidAddress/index.ts deleted file mode 100644 index 8ab82f1d..00000000 --- a/test/api/isValidAddress/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import assert from 'assert-diff' -import {TestSuite} from '../../utils' -import addresses from '../../fixtures/addresses.json' - -export default { - 'returns true for valid address': async (api, address) => { - assert(api.isValidAddress('rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K')) - assert(api.isValidAddress(addresses.ACCOUNT_X)) - assert(api.isValidAddress(addresses.ACCOUNT_T)) - }, - - 'returns false for invalid address': async (api, address) => { - assert(!api.isValidAddress('foobar')) - assert(!api.isValidAddress(addresses.ACCOUNT_X.slice(0, -1))) - assert(!api.isValidAddress(addresses.ACCOUNT_T.slice(1))) - } -} diff --git a/test/api/isValidSecret/index.ts b/test/api/isValidSecret/index.ts deleted file mode 100644 index e8f6abf8..00000000 --- a/test/api/isValidSecret/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import assert from 'assert-diff' -import {TestSuite} from '../../utils' - -export default { - 'returns true for valid secret': async (api, address) => { - assert(api.isValidSecret('snsakdSrZSLkYpCXxfRkS4Sh96PMK')) - }, - - 'returns false for invalid secret': async (api, address) => { - assert(!api.isValidSecret('foobar')) - } -} diff --git a/test/api/requestNextPage/index.ts b/test/api/requestNextPage/index.ts deleted file mode 100644 index 933fca85..00000000 --- a/test/api/requestNextPage/index.ts +++ /dev/null @@ -1,38 +0,0 @@ -import assert from 'assert-diff' -import {LedgerData} from 'ripple-api/common/types/objects' -import {assertRejects, TestSuite} from '../../utils' - -/** - * Every test suite exports their tests in the default object. - * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. - */ -export default { - 'requests the next page': async (api, address) => { - const response = await api.request('ledger_data') - const responseNextPage = await api.requestNextPage( - 'ledger_data', - {}, - response - ) - assert.equal( - responseNextPage.state[0].index, - '000B714B790C3C79FEE00D17C4DEB436B375466F29679447BA64F265FD63D731' - ) - }, - - 'rejects when there are no more pages': async (api, address) => { - const response = await api.request('ledger_data') - const responseNextPage = await api.requestNextPage( - 'ledger_data', - {}, - response - ) - assert(!api.hasNextPage(responseNextPage)) - await assertRejects( - api.requestNextPage('ledger_data', {}, responseNextPage), - Error, - 'response does not have a next page' - ) - } -} diff --git a/test/broadcast-api-test.ts b/test/broadcast-client-test.ts similarity index 75% rename from test/broadcast-api-test.ts rename to test/broadcast-client-test.ts index 33b9faa1..0de3fd95 100644 --- a/test/broadcast-api-test.ts +++ b/test/broadcast-client-test.ts @@ -1,11 +1,11 @@ import _ from 'lodash' import assert from 'assert-diff' -import setupAPI from './setup-api' +import setupClient from './setup-client' import responses from './fixtures/responses' import ledgerClosed from './fixtures/rippled/ledger-close.json' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import {ignoreWebSocketDisconnect} from './utils' -const schemaValidator = RippleAPI._PRIVATE.schemaValidator +const schemaValidator = Client._PRIVATE.schemaValidator const TIMEOUT = 20000 @@ -21,30 +21,30 @@ function checkResult(expected, schemaName, response) { return response } -describe('RippleAPIBroadcast', function () { +describe('ClientBroadcast', function () { this.timeout(TIMEOUT) - beforeEach(setupAPI.setupBroadcast) - afterEach(setupAPI.teardown) + beforeEach(setupClient.setupBroadcast) + afterEach(setupClient.teardown) it('base', function () { const expected = {request_server_info: 1} this.mocks.forEach((mock) => mock.expect(Object.assign({}, expected))) - assert(this.api.isConnected()) - return this.api + assert(this.client.isConnected()) + return this.client .getServerInfo() .then(_.partial(checkResult, responses.getServerInfo, 'getServerInfo')) }) it('ledger', function (done) { let gotLedger = 0 - this.api.on('ledger', () => { + this.client.on('ledger', () => { gotLedger++ }) const ledgerNext = Object.assign({}, ledgerClosed) ledgerNext.ledger_index++ - this.api._apis.forEach((api) => - api.connection + this.client._clients.forEach((client) => + client.connection .request({ command: 'echo', data: ledgerNext @@ -59,12 +59,12 @@ describe('RippleAPIBroadcast', function () { }) it('error propagation', function (done) { - this.api.once('error', (type, info) => { + this.client.once('error', (type, info) => { assert.strictEqual(type, 'type') assert.strictEqual(info, 'info') done() }) - this.api._apis[1].connection + this.client._clients[1].connection .request({ command: 'echo', data: {error: 'type', error_message: 'info'} diff --git a/test/api/combine/index.ts b/test/client/combine/index.ts similarity index 74% rename from test/api/combine/index.ts rename to test/client/combine/index.ts index 75984df4..4c93a46e 100644 --- a/test/api/combine/index.ts +++ b/test/client/combine/index.ts @@ -9,21 +9,21 @@ const {combine: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'combine': async (api, address) => { - const combined = api.combine(REQUEST_FIXTURES.setDomain) + 'combine': async (client, address) => { + const combined = client.combine(REQUEST_FIXTURES.setDomain) assertResultMatch(combined, RESPONSE_FIXTURES.single, 'sign') }, - 'combine - different transactions': async (api, address) => { + 'combine - different transactions': async (client, address) => { const request = [REQUEST_FIXTURES.setDomain[0]] const tx = binary.decode(REQUEST_FIXTURES.setDomain[0]) tx.Flags = 0 request.push(binary.encode(tx)) assert.throws(() => { - api.combine(request) + client.combine(request) }, /txJSON is not the same for all signedTransactions/) } } diff --git a/test/api/computeLedgerHash/index.ts b/test/client/computeLedgerHash/index.ts similarity index 88% rename from test/api/computeLedgerHash/index.ts rename to test/client/computeLedgerHash/index.ts index 2fb0626d..73548b5f 100644 --- a/test/api/computeLedgerHash/index.ts +++ b/test/client/computeLedgerHash/index.ts @@ -7,17 +7,17 @@ const {computeLedgerHash: REQUEST_FIXTURES} = requests /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'given corrupt data - should fail': async (api, address) => { + 'given corrupt data - should fail': async (client, address) => { const request = { includeTransactions: true, includeState: true, includeAllData: true, ledgerVersion: 38129 } - const ledger = await api.getLedger(request) + const ledger = await client.getLedger(request) assert.strictEqual( // @ts-ignore ledger.transactions[0].rawTransaction, @@ -29,9 +29,9 @@ export default { ledger.parentCloseTime = ledger.closeTime let hash try { - hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) + hash = client.computeLedgerHash(ledger, {computeTreeHashes: true}) } catch (error) { - assert(error instanceof api.errors.ValidationError) + assert(error instanceof client.errors.ValidationError) assert.strictEqual( error.message, 'transactionHash in header does not match computed hash of transactions' @@ -51,7 +51,7 @@ export default { }, 'given ledger without raw transactions - should throw': async ( - api, + client, address ) => { const request = { @@ -60,7 +60,7 @@ export default { includeAllData: true, ledgerVersion: 38129 } - const ledger = await api.getLedger(request) + const ledger = await client.getLedger(request) assert.strictEqual( // @ts-ignore ledger.transactions[0].rawTransaction, @@ -72,9 +72,9 @@ export default { ledger.parentCloseTime = ledger.closeTime let hash try { - hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) + hash = client.computeLedgerHash(ledger, {computeTreeHashes: true}) } catch (error) { - assert(error instanceof api.errors.ValidationError) + assert(error instanceof client.errors.ValidationError) assert.strictEqual( error.message, 'ledger' + ' is missing raw transactions' @@ -88,7 +88,7 @@ export default { }, 'given ledger without state or transactions - only compute ledger hash': async ( - api, + client, address ) => { const request = { @@ -97,15 +97,15 @@ export default { includeAllData: true, ledgerVersion: 38129 } - const ledger = await api.getLedger(request) + const ledger = await client.getLedger(request) assert.strictEqual( // @ts-ignore 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 = api.computeLedgerHash - const ValidationError = api.errors.ValidationError + const computeLedgerHash = client.computeLedgerHash + const ValidationError = client.errors.ValidationError function testCompute(ledger, expectedError) { let hash = computeLedgerHash(ledger) assert.strictEqual( @@ -135,14 +135,14 @@ export default { testCompute(ledger, 'rawState property is missing from the ledger') }, - 'wrong hash': async (api, address) => { + 'wrong hash': async (client, address) => { const request = { includeTransactions: true, includeState: true, includeAllData: true, ledgerVersion: 38129 } - const ledger = await api.getLedger(request) + const ledger = await client.getLedger(request) assertResultMatch(ledger, responses.getLedger.full, 'getLedger') const newLedger = { ...ledger, @@ -151,41 +151,41 @@ export default { 'D9ABF622DA26EEEE48203085D4BC23B0F77DC6F8724AC33D975DA3CA492D2E44' } assert.throws(() => { - api.computeLedgerHash(newLedger) + client.computeLedgerHash(newLedger) }, /does not match computed hash of state/) }, - 'computeLedgerHash': async (api, address) => { - // const api = new RippleAPI() + 'computeLedgerHash': async (client, address) => { + // const client = new Client() const header = REQUEST_FIXTURES.header - const ledgerHash = api.computeLedgerHash(header) + const ledgerHash = client.computeLedgerHash(header) assert.strictEqual( ledgerHash, 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349' ) }, - 'computeLedgerHash - with transactions': async (api, address) => { - // const api = new RippleAPI() + 'computeLedgerHash - with transactions': async (client, address) => { + // const client = new Client() const header = { ...REQUEST_FIXTURES.header, transactionHash: undefined, rawTransactions: JSON.stringify(REQUEST_FIXTURES.transactions) } - const ledgerHash = api.computeLedgerHash(header) + const ledgerHash = client.computeLedgerHash(header) assert.strictEqual( ledgerHash, 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349' ) }, - 'computeLedgerHash - incorrent transaction_hash': async (api, address) => { - // const api = new RippleAPI() + 'computeLedgerHash - incorrent transaction_hash': async (client, address) => { + // const client = new Client() const header = Object.assign({}, REQUEST_FIXTURES.header, { transactionHash: '325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9' }) header.rawTransactions = JSON.stringify(REQUEST_FIXTURES.transactions) - assert.throws(() => api.computeLedgerHash(header)) + assert.throws(() => client.computeLedgerHash(header)) } } diff --git a/test/client/constructor/index.ts b/test/client/constructor/index.ts new file mode 100644 index 00000000..72cf4c15 --- /dev/null +++ b/test/client/constructor/index.ts @@ -0,0 +1,29 @@ +import assert from 'assert-diff' +import {TestSuite} from '../../utils' +import {Client} from 'xrpl-local' + +/** + * 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. + */ +export default { + 'Client - implicit server port': () => { + new Client({server: 'wss://s1.ripple.com'}) + }, + + 'Client invalid options': () => { + // @ts-ignore - This is intentionally invalid + assert.throws(() => new Client({invalid: true})) + }, + + 'Client valid options': () => { + const client = new Client({server: 'wss://s:1'}) + const privateConnectionUrl = (client.connection as any)._url + assert.deepEqual(privateConnectionUrl, 'wss://s:1') + }, + + 'Client invalid server uri': () => { + assert.throws(() => new Client({server: 'wss//s:1'})) + } +} diff --git a/test/api/deriveAddress/index.ts b/test/client/deriveAddress/index.ts similarity index 67% rename from test/api/deriveAddress/index.ts rename to test/client/deriveAddress/index.ts index e7ab3e03..64225527 100644 --- a/test/api/deriveAddress/index.ts +++ b/test/client/deriveAddress/index.ts @@ -4,11 +4,11 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'returns address for public key': async (api, address) => { - var address = api.deriveAddress( + 'returns address for public key': async (client, address) => { + var address = client.deriveAddress( '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06' ) assert.equal(address, 'rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K') diff --git a/test/api/deriveKeypair/index.ts b/test/client/deriveKeypair/index.ts similarity index 64% rename from test/api/deriveKeypair/index.ts rename to test/client/deriveKeypair/index.ts index d217f09d..c5aa8e64 100644 --- a/test/api/deriveKeypair/index.ts +++ b/test/client/deriveKeypair/index.ts @@ -4,11 +4,11 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'returns keypair for secret': async (api, address) => { - var keypair = api.deriveKeypair('snsakdSrZSLkYpCXxfRkS4Sh96PMK') + 'returns keypair for secret': async (client, address) => { + var keypair = client.deriveKeypair('snsakdSrZSLkYpCXxfRkS4Sh96PMK') assert.equal( keypair.privateKey, '008850736302221AFD59FF9CA1A29D4975F491D726249302EE48A3078A8934D335' @@ -19,8 +19,8 @@ export default { ) }, - 'returns keypair for ed25519 secret': async (api, address) => { - var keypair = api.deriveKeypair('sEdV9eHWbibBnTj7b1H5kHfPfv7gudx') + 'returns keypair for ed25519 secret': async (client, address) => { + var keypair = client.deriveKeypair('sEdV9eHWbibBnTj7b1H5kHfPfv7gudx') assert.equal( keypair.privateKey, 'ED5C2EF6C2E3200DFA6B72F47935C7F64D35453646EA34919192538F458C7BC30F' @@ -31,9 +31,9 @@ export default { ) }, - 'throws with an invalid secret': async (api, address) => { + 'throws with an invalid secret': async (client, address) => { assert.throws(() => { - api.deriveKeypair('...') + client.deriveKeypair('...') }, /^Error: Non-base58 character$/) } } diff --git a/test/api/deriveXAddress/index.ts b/test/client/deriveXAddress/index.ts similarity index 74% rename from test/api/deriveXAddress/index.ts rename to test/client/deriveXAddress/index.ts index c31baa00..4f28e7f6 100644 --- a/test/api/deriveXAddress/index.ts +++ b/test/client/deriveXAddress/index.ts @@ -1,16 +1,16 @@ import assert from 'assert-diff' import {TestSuite} from '../../utils' -import {RippleAPI} from '../../../src' +import {Client} from '../../../src' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'returns address for public key': async (api, address) => { + 'returns address for public key': async (client, address) => { assert.equal( - RippleAPI.deriveXAddress({ + Client.deriveXAddress({ publicKey: '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06', tag: false, @@ -19,7 +19,7 @@ export default { 'XVZVpQj8YSVpNyiwXYSqvQoQqgBttTxAZwMcuJd4xteQHyt' ) assert.equal( - RippleAPI.deriveXAddress({ + Client.deriveXAddress({ publicKey: '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06', tag: false, diff --git a/test/api/dropsToXrp/index.ts b/test/client/dropsToXrp/index.ts similarity index 58% rename from test/api/dropsToXrp/index.ts rename to test/client/dropsToXrp/index.ts index aec39db6..62027cea 100644 --- a/test/api/dropsToXrp/index.ts +++ b/test/client/dropsToXrp/index.ts @@ -5,115 +5,115 @@ import BigNumber from 'bignumber.js' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'works with a typical amount': async (api) => { - const xrp = api.dropsToXrp('2000000') + 'works with a typical amount': async (client) => { + const xrp = client.dropsToXrp('2000000') assert.strictEqual(xrp, '2', '2 million drops equals 2 XRP') }, - 'works with fractions': async (api) => { - let xrp = api.dropsToXrp('3456789') + 'works with fractions': async (client) => { + let xrp = client.dropsToXrp('3456789') assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP') - xrp = api.dropsToXrp('3400000') + xrp = client.dropsToXrp('3400000') assert.strictEqual(xrp, '3.4', '3,400,000 drops equals 3.4 XRP') - xrp = api.dropsToXrp('1') + xrp = client.dropsToXrp('1') assert.strictEqual(xrp, '0.000001', '1 drop equals 0.000001 XRP') - xrp = api.dropsToXrp('1.0') + xrp = client.dropsToXrp('1.0') assert.strictEqual(xrp, '0.000001', '1.0 drops equals 0.000001 XRP') - xrp = api.dropsToXrp('1.00') + xrp = client.dropsToXrp('1.00') assert.strictEqual(xrp, '0.000001', '1.00 drops equals 0.000001 XRP') }, - 'works with zero': async (api) => { - let xrp = api.dropsToXrp('0') + 'works with zero': async (client) => { + let xrp = client.dropsToXrp('0') assert.strictEqual(xrp, '0', '0 drops equals 0 XRP') // negative zero is equivalent to zero - xrp = api.dropsToXrp('-0') + xrp = client.dropsToXrp('-0') assert.strictEqual(xrp, '0', '-0 drops equals 0 XRP') - xrp = api.dropsToXrp('0.00') + xrp = client.dropsToXrp('0.00') assert.strictEqual(xrp, '0', '0.00 drops equals 0 XRP') - xrp = api.dropsToXrp('000000000') + xrp = client.dropsToXrp('000000000') assert.strictEqual(xrp, '0', '000000000 drops equals 0 XRP') }, - 'works with a negative value': async (api) => { - const xrp = api.dropsToXrp('-2000000') + 'works with a negative value': async (client) => { + const xrp = client.dropsToXrp('-2000000') assert.strictEqual(xrp, '-2', '-2 million drops equals -2 XRP') }, - 'works with a value ending with a decimal point': async (api) => { - let xrp = api.dropsToXrp('2000000.') + 'works with a value ending with a decimal point': async (client) => { + let xrp = client.dropsToXrp('2000000.') assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP') - xrp = api.dropsToXrp('-2000000.') + xrp = client.dropsToXrp('-2000000.') assert.strictEqual(xrp, '-2', '-2000000. drops equals -2 XRP') }, - 'works with BigNumber objects': async (api) => { - let xrp = api.dropsToXrp(new BigNumber(2000000)) + 'works with BigNumber objects': async (client) => { + let xrp = client.dropsToXrp(new BigNumber(2000000)) assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP') - xrp = api.dropsToXrp(new BigNumber(-2000000)) + xrp = client.dropsToXrp(new BigNumber(-2000000)) assert.strictEqual(xrp, '-2', '(BigNumber) -2 million drops equals -2 XRP') - xrp = api.dropsToXrp(new BigNumber(2345678)) + xrp = client.dropsToXrp(new BigNumber(2345678)) assert.strictEqual( xrp, '2.345678', '(BigNumber) 2,345,678 drops equals 2.345678 XRP' ) - xrp = api.dropsToXrp(new BigNumber(-2345678)) + xrp = client.dropsToXrp(new BigNumber(-2345678)) assert.strictEqual( xrp, '-2.345678', '(BigNumber) -2,345,678 drops equals -2.345678 XRP' ) }, - 'works with a number': async (api) => { + 'works with a number': async (client) => { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. - let xrp = api.dropsToXrp(2000000) + let xrp = client.dropsToXrp(2000000) assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP') - xrp = api.dropsToXrp(-2000000) + xrp = client.dropsToXrp(-2000000) assert.strictEqual(xrp, '-2', '(number) -2 million drops equals -2 XRP') }, - 'throws with an amount with too many decimal places': async (api) => { + 'throws with an amount with too many decimal places': async (client) => { assert.throws(() => { - api.dropsToXrp('1.2') + client.dropsToXrp('1.2') }, /has too many decimal places/) assert.throws(() => { - api.dropsToXrp('0.10') + client.dropsToXrp('0.10') }, /has too many decimal places/) }, - 'throws with an invalid value': async (api) => { + 'throws with an invalid value': async (client) => { assert.throws(() => { - api.dropsToXrp('FOO') + client.dropsToXrp('FOO') }, /invalid value/) assert.throws(() => { - api.dropsToXrp('1e-7') + client.dropsToXrp('1e-7') }, /invalid value/) assert.throws(() => { - api.dropsToXrp('2,0') + client.dropsToXrp('2,0') }, /invalid value/) assert.throws(() => { - api.dropsToXrp('.') + client.dropsToXrp('.') }, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./) }, - 'throws with an amount more than one decimal point': async (api) => { + 'throws with an amount more than one decimal point': async (client) => { assert.throws(() => { - api.dropsToXrp('1.0.0') + client.dropsToXrp('1.0.0') }, /dropsToXrp: invalid value '1\.0\.0'/) assert.throws(() => { - api.dropsToXrp('...') + client.dropsToXrp('...') }, /dropsToXrp: invalid value '\.\.\.'/) } } diff --git a/test/api/errors/index.ts b/test/client/errors/index.ts similarity index 55% rename from test/api/errors/index.ts rename to test/client/errors/index.ts index d042cc24..18774cd3 100644 --- a/test/api/errors/index.ts +++ b/test/client/errors/index.ts @@ -4,16 +4,16 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'RippleError with data': async (api, address) => { - const error = new api.errors.RippleError('_message_', '_data_') + 'RippleError with data': async (client, address) => { + const error = new client.errors.RippleError('_message_', '_data_') assert.strictEqual(error.toString(), "[RippleError(_message_, '_data_')]") }, - 'NotFoundError default message': async (api, address) => { - const error = new api.errors.NotFoundError() + 'NotFoundError default message': async (client, address) => { + const error = new client.errors.NotFoundError() assert.strictEqual(error.toString(), '[NotFoundError(Not found)]') } } diff --git a/test/api/formatBidsAndAsks/index.ts b/test/client/formatBidsAndAsks/index.ts similarity index 71% rename from test/api/formatBidsAndAsks/index.ts rename to test/client/formatBidsAndAsks/index.ts index 60109cc3..2290df82 100644 --- a/test/api/formatBidsAndAsks/index.ts +++ b/test/client/formatBidsAndAsks/index.ts @@ -1,6 +1,6 @@ import BigNumber from 'bignumber.js' import assert from 'assert-diff' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' import {TestSuite} from '../../utils' @@ -42,10 +42,10 @@ function checkSortingOfOrders(orders) { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'normal': async (api, address) => { + 'normal': async (client, address) => { const orderbookInfo = { base: { currency: 'USD', @@ -58,16 +58,16 @@ export default { } await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 20, taker: address }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 20, taker: address @@ -81,7 +81,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -89,7 +89,7 @@ export default { }) }, - 'with XRP': async (api, address) => { + 'with XRP': async (client, address) => { const orderbookInfo = { base: { currency: 'USD', @@ -101,16 +101,16 @@ export default { } await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 20, taker: address }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 20, taker: address @@ -124,7 +124,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -132,7 +132,7 @@ export default { }) }, - 'sample XRP/JPY book has orders sorted correctly': async (api, address) => { + 'sample XRP/JPY book has orders sorted correctly': async (client, address) => { const orderbookInfo = { base: { // the first currency in pair @@ -147,16 +147,16 @@ export default { const myAddress = 'rE9qNjzJXpiUbVomdv7R4xhrXVeH2oVmGR' await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 400, // must match `test/fixtures/rippled/requests/1-taker_gets-XRP-taker_pays-JPY.json` taker: myAddress }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 400, // must match `test/fixtures/rippled/requests/2-taker_gets-JPY-taker_pays-XRP.json` taker: myAddress @@ -170,7 +170,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -179,7 +179,7 @@ export default { }) }, - 'sample USD/XRP book has orders sorted correctly': async (api, address) => { + 'sample USD/XRP book has orders sorted correctly': async (client, address) => { const orderbookInfo = { counter: {currency: 'XRP'}, base: { @@ -191,16 +191,16 @@ export default { const myAddress = 'rE9qNjzJXpiUbVomdv7R4xhrXVeH2oVmGR' await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 400, // must match `test/fixtures/rippled/requests/1-taker_gets-XRP-taker_pays-JPY.json` taker: myAddress }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 400, // must match `test/fixtures/rippled/requests/2-taker_gets-JPY-taker_pays-XRP.json` taker: myAddress @@ -214,7 +214,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -225,7 +225,7 @@ export default { }) }, - 'sorted so that best deals come first': async (api, address) => { + 'sorted so that best deals come first': async (client, address) => { const orderbookInfo = { base: { currency: 'USD', @@ -238,16 +238,16 @@ export default { } await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 20, taker: address }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 20, taker: address @@ -261,7 +261,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -280,7 +280,7 @@ export default { }) }, - 'currency & counterparty are correct': async (api, address) => { + 'currency & counterparty are correct': async (client, address) => { const orderbookInfo = { base: { currency: 'USD', @@ -293,16 +293,16 @@ export default { } await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 20, taker: address }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 20, taker: address @@ -316,7 +316,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) @@ -334,7 +334,7 @@ export default { }) }, - 'direction is correct for bids and asks': async (api, address) => { + 'direction is correct for bids and asks': async (client, address) => { const orderbookInfo = { base: { currency: 'USD', @@ -347,16 +347,16 @@ export default { } await Promise.all([ - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.base), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.counter), ledger_index: 'validated', limit: 20, taker: address }), - api.request('book_offers', { - taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter), - taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base), + client.request('book_offers', { + taker_gets: Client.renameCounterpartyToIssuer(orderbookInfo.counter), + taker_pays: Client.renameCounterpartyToIssuer(orderbookInfo.base), ledger_index: 'validated', limit: 20, taker: address @@ -370,7 +370,7 @@ export default { ? reverseOfferResults.offers : [] ).reduce((acc, res) => acc.concat(res), []) - const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [ + const orderbook = Client.formatBidsAndAsks(orderbookInfo, [ ...directOffers, ...reverseOffers ]) diff --git a/test/api/generateAddress/index.ts b/test/client/generateAddress/index.ts similarity index 84% rename from test/api/generateAddress/index.ts rename to test/client/generateAddress/index.ts index 78aef15c..d2ef2b91 100644 --- a/test/api/generateAddress/index.ts +++ b/test/client/generateAddress/index.ts @@ -8,10 +8,10 @@ const {generateAddress: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'generateAddress': async (api) => { + 'generateAddress': async (client) => { // GIVEN entropy of all zeros function random() { return new Array(16).fill(0) @@ -19,14 +19,14 @@ export default { assert.deepEqual( // WHEN generating an address - api.generateAddress({entropy: random()}), + client.generateAddress({entropy: random()}), // THEN we get the expected return value RESPONSE_FIXTURES ) }, - 'generateAddress invalid entropy': async (api) => { + 'generateAddress invalid entropy': async (client) => { assert.throws(() => { // GIVEN entropy of 1 byte function random() { @@ -34,42 +34,42 @@ export default { } // WHEN generating an address - api.generateAddress({entropy: random()}) + client.generateAddress({entropy: random()}) // THEN an UnexpectedError is thrown // because 16 bytes of entropy are required - }, api.errors.UnexpectedError) + }, client.errors.UnexpectedError) }, - 'generateAddress with no options object': async (api) => { + 'generateAddress with no options object': async (client) => { // GIVEN no options // WHEN generating an address - const account = api.generateAddress() + const account = client.generateAddress() // THEN we get an object with an address starting with 'r' and a secret starting with 's' assert(account.address.startsWith('r'), 'Address must start with `r`') assert(account.secret.startsWith('s'), 'Secret must start with `s`') }, - 'generateAddress with empty options object': async (api) => { + 'generateAddress with empty options object': async (client) => { // GIVEN an empty options object const options = {} // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get an object with an address starting with 'r' and a secret starting with 's' assert(account.address.startsWith('r'), 'Address must start with `r`') assert(account.secret.startsWith('s'), 'Secret must start with `s`') }, - 'generateAddress with algorithm `ecdsa-secp256k1`': async (api) => { + 'generateAddress with algorithm `ecdsa-secp256k1`': async (client) => { // GIVEN we want to use 'ecdsa-secp256k1' const options: GenerateAddressOptions = {algorithm: ECDSA.secp256k1} // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get an object with an address starting with 'r' and a secret starting with 's' (not 'sEd') assert(account.address.startsWith('r'), 'Address must start with `r`') @@ -85,12 +85,12 @@ export default { ) }, - 'generateAddress with algorithm `ed25519`': async (api) => { + 'generateAddress with algorithm `ed25519`': async (client) => { // GIVEN we want to use 'ed25519' const options: GenerateAddressOptions = {algorithm: ECDSA.ed25519} // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get an object with an address starting with 'r' and a secret starting with 'sEd' assert(account.address.startsWith('r'), 'Address must start with `r`') @@ -102,7 +102,7 @@ export default { }, 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -111,13 +111,13 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value assert.deepEqual(account, responses.generateAddress) }, - 'generateAddress with algorithm `ed25519` and given entropy': async (api) => { + 'generateAddress with algorithm `ed25519` and given entropy': async (client) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { algorithm: ECDSA.ed25519, @@ -125,7 +125,7 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -139,7 +139,7 @@ export default { }, 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -149,14 +149,14 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value assert.deepEqual(account, responses.generateAddress) }, 'generateAddress with algorithm `ed25519` and given entropy; include classic address': async ( - api + client ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { @@ -166,7 +166,7 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -180,7 +180,7 @@ export default { }, 'generateAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -191,7 +191,7 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value const response = Object.assign({}, responses.generateAddress, { @@ -202,7 +202,7 @@ export default { }, 'generateAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async ( - api + client ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { @@ -213,7 +213,7 @@ export default { } // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -226,12 +226,12 @@ export default { }) }, - 'generateAddress for test network use': async (api) => { + 'generateAddress for test network use': async (client) => { // GIVEN we want an address for test network use const options: GenerateAddressOptions = {test: true} // WHEN generating an address - const account = api.generateAddress(options) + const account = client.generateAddress(options) // THEN we get an object with xAddress starting with 'T' and a secret starting with 's' diff --git a/test/api/generateXAddress/index.ts b/test/client/generateXAddress/index.ts similarity index 83% rename from test/api/generateXAddress/index.ts rename to test/client/generateXAddress/index.ts index 098aeb41..ca952782 100644 --- a/test/api/generateXAddress/index.ts +++ b/test/client/generateXAddress/index.ts @@ -7,10 +7,10 @@ import {GenerateAddressOptions} from '../../../src/offline/generate-address' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'generateXAddress': async (api) => { + 'generateXAddress': async (client) => { // GIVEN entropy of all zeros function random() { return new Array(16).fill(0) @@ -18,14 +18,14 @@ export default { assert.deepEqual( // WHEN generating an X-address - api.generateXAddress({entropy: random()}), + client.generateXAddress({entropy: random()}), // THEN we get the expected return value responses.generateXAddress ) }, - 'generateXAddress invalid entropy': async (api) => { + 'generateXAddress invalid entropy': async (client) => { assert.throws(() => { // GIVEN entropy of 1 byte function random() { @@ -33,18 +33,18 @@ export default { } // WHEN generating an X-address - api.generateXAddress({entropy: random()}) + client.generateXAddress({entropy: random()}) // THEN an UnexpectedError is thrown // because 16 bytes of entropy are required - }, api.errors.UnexpectedError) + }, client.errors.UnexpectedError) }, - 'generateXAddress with no options object': async (api) => { + 'generateXAddress with no options object': async (client) => { // GIVEN no options // WHEN generating an X-address - const account = api.generateXAddress() + const account = client.generateXAddress() // THEN we get an object with an xAddress starting with 'X' and a secret starting with 's' assert( @@ -54,12 +54,12 @@ export default { assert(account.secret.startsWith('s'), 'Secrets start with s') }, - 'generateXAddress with empty options object': async (api) => { + 'generateXAddress with empty options object': async (client) => { // GIVEN an empty options object const options = {} // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get an object with an xAddress starting with 'X' and a secret starting with 's' assert( @@ -69,12 +69,12 @@ export default { assert(account.secret.startsWith('s'), 'Secrets start with s') }, - 'generateXAddress with algorithm `ecdsa-secp256k1`': async (api) => { + 'generateXAddress with algorithm `ecdsa-secp256k1`': async (client) => { // GIVEN we want to use 'ecdsa-secp256k1' const options: GenerateAddressOptions = {algorithm: ECDSA.secp256k1} // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get an object with an xAddress starting with 'X' and a secret starting with 's' assert( @@ -93,12 +93,12 @@ export default { ) }, - 'generateXAddress with algorithm `ed25519`': async (api) => { + 'generateXAddress with algorithm `ed25519`': async (client) => { // GIVEN we want to use 'ed25519' const options: GenerateAddressOptions = {algorithm: ECDSA.ed25519} // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get an object with an xAddress starting with 'X' and a secret starting with 'sEd' assert( @@ -113,7 +113,7 @@ export default { }, 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -122,14 +122,14 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, responses.generateXAddress) }, 'generateXAddress with algorithm `ed25519` and given entropy': async ( - api + client ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { @@ -138,7 +138,7 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -148,7 +148,7 @@ export default { }, 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -158,14 +158,14 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, responses.generateAddress) }, 'generateXAddress with algorithm `ed25519` and given entropy; include classic address': async ( - api + client ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { @@ -175,7 +175,7 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -187,7 +187,7 @@ export default { }, 'generateXAddress with algorithm `ecdsa-secp256k1` and given entropy; include classic address; for test network use': async ( - api + client ) => { // GIVEN we want to use 'ecdsa-secp256k1' with entropy of zero const options: GenerateAddressOptions = { @@ -198,7 +198,7 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value const response = Object.assign({}, responses.generateAddress, { @@ -208,7 +208,7 @@ export default { }, 'generateXAddress with algorithm `ed25519` and given entropy; include classic address; for test network use': async ( - api + client ) => { // GIVEN we want to use 'ed25519' with entropy of zero const options: GenerateAddressOptions = { @@ -219,7 +219,7 @@ export default { } // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get the expected return value assert.deepEqual(account, { @@ -230,12 +230,12 @@ export default { }) }, - 'generateXAddress for test network use': async (api) => { + 'generateXAddress for test network use': async (client) => { // GIVEN we want an X-address for test network use const options: GenerateAddressOptions = {test: true} // WHEN generating an X-address - const account = api.generateXAddress(options) + const account = client.generateXAddress(options) // THEN we get an object with xAddress starting with 'T' and a secret starting with 's' assert.deepEqual( diff --git a/test/api/getAccountInfo/index.ts b/test/client/getAccountInfo/index.ts similarity index 52% rename from test/api/getAccountInfo/index.ts rename to test/client/getAccountInfo/index.ts index b7fa42d8..f297340a 100644 --- a/test/api/getAccountInfo/index.ts +++ b/test/client/getAccountInfo/index.ts @@ -4,24 +4,24 @@ import {assertRejects, assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getAccountInfo': async (api, address) => { - const result = await api.getAccountInfo(address) + 'getAccountInfo': async (client, address) => { + const result = await client.getAccountInfo(address) assertResultMatch(result, responses.getAccountInfo, 'getAccountInfo') }, - 'getAccountInfo - options undefined': async (api, address) => { - const result = await api.getAccountInfo(address, undefined) + 'getAccountInfo - options undefined': async (client, address) => { + const result = await client.getAccountInfo(address, undefined) assertResultMatch(result, responses.getAccountInfo, 'getAccountInfo') }, - 'getAccountInfo - invalid options': async (api, address) => { + 'getAccountInfo - invalid options': async (client, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getAccountInfo(address, {invalid: 'options'}), - api.errors.ValidationError + client.getAccountInfo(address, {invalid: 'options'}), + client.errors.ValidationError ) } } diff --git a/test/api/getAccountObjects/index.ts b/test/client/getAccountObjects/index.ts similarity index 61% rename from test/api/getAccountObjects/index.ts rename to test/client/getAccountObjects/index.ts index 0092150a..096f8012 100644 --- a/test/api/getAccountObjects/index.ts +++ b/test/client/getAccountObjects/index.ts @@ -5,17 +5,17 @@ const {getAccountObjects: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getAccountObjects': async (api, address) => { - const result = await api.getAccountObjects(address) + 'getAccountObjects': async (client, address) => { + const result = await client.getAccountObjects(address) assertResultMatch(result, RESPONSE_FIXTURES, 'AccountObjectsResponse') }, - 'getAccountObjects - invalid options': async (api, address) => { + 'getAccountObjects - invalid options': async (client, address) => { // @ts-ignore - This is intentionally invalid - const result = await api.getAccountObjects(address, {invalid: 'options'}) + const result = await client.getAccountObjects(address, {invalid: 'options'}) assertResultMatch(result, RESPONSE_FIXTURES, 'AccountObjectsResponse') } } diff --git a/test/client/getBalanceSheet/index.ts b/test/client/getBalanceSheet/index.ts new file mode 100644 index 00000000..829709ab --- /dev/null +++ b/test/client/getBalanceSheet/index.ts @@ -0,0 +1,26 @@ +import {assertRejects, assertResultMatch, TestSuite} from '../../utils' + +/** + * 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. + */ +export default { + 'getBalanceSheet': async (client, address) => { + await client.getBalanceSheet(address) + }, + + 'getBalanceSheet - invalid options': async (client, address) => { + await assertRejects( + // @ts-ignore - This is intentionally invalid + client.getBalanceSheet(address, {invalid: 'options'}), + client.errors.ValidationError + ) + }, + + 'getBalanceSheet - empty': async (client, address) => { + const options = {ledgerVersion: 123456} + const result = await client.getBalanceSheet(address, options) + assertResultMatch(result, {}, 'getBalanceSheet') + } +} diff --git a/test/api/getBalances/index.ts b/test/client/getBalances/index.ts similarity index 67% rename from test/api/getBalances/index.ts rename to test/client/getBalances/index.ts index c0a352b7..e56d9575 100644 --- a/test/api/getBalances/index.ts +++ b/test/client/getBalances/index.ts @@ -4,31 +4,31 @@ import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getBalances': async (api, address) => { - const result = await api.getBalances(address) + 'getBalances': async (client, address) => { + const result = await client.getBalances(address) assertResultMatch(result, responses.getBalances, 'getBalances') }, - 'getBalances - limit': async (api, address) => { + 'getBalances - limit': async (client, address) => { const options = {limit: 3, ledgerVersion: 123456} const expectedResponse = responses.getBalances.slice(0, 3) - const result = await api.getBalances(address, options) + const result = await client.getBalances(address, options) assertResultMatch(result, expectedResponse, 'getBalances') }, - 'getBalances - limit & currency': async (api, address) => { + 'getBalances - limit & currency': async (client, address) => { const options = {currency: 'USD', limit: 3} const expectedResponse = responses.getBalances .filter((item) => item.currency === 'USD') .slice(0, 3) - const result = await api.getBalances(address, options) + const result = await client.getBalances(address, options) assertResultMatch(result, expectedResponse, 'getBalances') }, - 'getBalances - limit & currency & issuer': async (api, address) => { + 'getBalances - limit & currency & issuer': async (client, address) => { const options = { currency: 'USD', counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', @@ -41,7 +41,7 @@ export default { item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' ) .slice(0, 3) - const result = await api.getBalances(address, options) + const result = await client.getBalances(address, options) assertResultMatch(result, expectedResponse, 'getBalances') } } diff --git a/test/api/getFee/index.ts b/test/client/getFee/index.ts similarity index 51% rename from test/api/getFee/index.ts rename to test/client/getFee/index.ts index 73be175a..6603e9e7 100644 --- a/test/api/getFee/index.ts +++ b/test/client/getFee/index.ts @@ -4,61 +4,61 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getFee': async (api, address) => { - const fee = await api.getFee() + 'getFee': async (client, address) => { + const fee = await client.getFee() assert.strictEqual(fee, '0.000012') }, - 'getFee default': async (api, address) => { - api._feeCushion = undefined - const fee = await api.getFee() + 'getFee default': async (client, address) => { + client._feeCushion = undefined + const fee = await client.getFee() assert.strictEqual(fee, '0.000012') }, - 'getFee - high load_factor': async (api, address) => { - api.connection.request({ + 'getFee - high load_factor': async (client, address) => { + client.connection.request({ command: 'config', data: {highLoadFactor: true} }) - const fee = await api.getFee() + const fee = await client.getFee() assert.strictEqual(fee, '2') }, - 'getFee - high load_factor with custom maxFeeXRP': async (api, address) => { + 'getFee - high load_factor with custom maxFeeXRP': async (client, address) => { // Ensure that overriding with high maxFeeXRP of '51540' causes no errors. // (fee will actually be 51539.607552) - api._maxFeeXRP = '51540' - api.connection.request({ + client._maxFeeXRP = '51540' + client.connection.request({ command: 'config', data: {highLoadFactor: true} }) - const fee = await api.getFee() + const fee = await client.getFee() assert.strictEqual(fee, '51539.607552') }, - 'getFee custom cushion': async (api, address) => { - api._feeCushion = 1.4 - const fee = await api.getFee() + 'getFee custom cushion': async (client, address) => { + client._feeCushion = 1.4 + const fee = await 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. - 'getFee cushion less than 1.0': async (api, address) => { - api._feeCushion = 0.9 - const fee = await api.getFee() + 'getFee cushion less than 1.0': async (client, address) => { + client._feeCushion = 0.9 + const fee = await client.getFee() assert.strictEqual(fee, '0.000009') }, - 'getFee reporting': async (api, address) => { - api.connection.request({ + 'getFee reporting': async (client, address) => { + client.connection.request({ command: 'config', data: {reporting: true} }) - const fee = await api.getFee() + const fee = await client.getFee() assert.strictEqual(fee, '0.000012') } } diff --git a/test/api/getFeeBase/index.ts b/test/client/getFeeBase/index.ts similarity index 60% rename from test/api/getFeeBase/index.ts rename to test/client/getFeeBase/index.ts index 23681ca4..07a4949a 100644 --- a/test/api/getFeeBase/index.ts +++ b/test/client/getFeeBase/index.ts @@ -4,11 +4,11 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default test': async (api, address) => { - const fee = await api.connection.getFeeBase() + 'default test': async (client, address) => { + const fee = await client.connection.getFeeBase() assert.strictEqual(fee, 10) } } diff --git a/test/api/getFeeRef/index.ts b/test/client/getFeeRef/index.ts similarity index 60% rename from test/api/getFeeRef/index.ts rename to test/client/getFeeRef/index.ts index d625ce25..273a3a55 100644 --- a/test/api/getFeeRef/index.ts +++ b/test/client/getFeeRef/index.ts @@ -4,11 +4,11 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default test': async (api, address) => { - const fee = await api.connection.getFeeRef() + 'default test': async (client, address) => { + const fee = await client.connection.getFeeRef() assert.strictEqual(fee, 10) } } diff --git a/test/api/getLedger/index.ts b/test/client/getLedger/index.ts similarity index 67% rename from test/api/getLedger/index.ts rename to test/client/getLedger/index.ts index bdd75ed3..35170b97 100644 --- a/test/api/getLedger/index.ts +++ b/test/client/getLedger/index.ts @@ -6,83 +6,83 @@ const {getLedger: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'simple test': async (api) => { - const response = await api.getLedger() + 'simple test': async (client) => { + const response = await client.getLedger() assertResultMatch(response, RESPONSE_FIXTURES.header, 'getLedger') }, - 'by hash': async (api) => { - const response = await api.getLedger({ + 'by hash': async (client) => { + const response = await client.getLedger({ ledgerHash: '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D' }) assertResultMatch(response, RESPONSE_FIXTURES.headerByHash, 'getLedger') }, - 'future ledger version': async (api) => { - const response = await api.getLedger({ledgerVersion: 14661789}) + 'future ledger version': async (client) => { + const response = await client.getLedger({ledgerVersion: 14661789}) assert(!!response) }, - 'with state as hashes': async (api) => { + 'with state as hashes': async (client) => { const request = { includeTransactions: true, includeAllData: false, includeState: true, ledgerVersion: 6 } - const response = await api.getLedger(request) + const response = await client.getLedger(request) assertResultMatch( response, RESPONSE_FIXTURES.withStateAsHashes, 'getLedger' ) }, - 'with settings transaction': async (api) => { + 'with settings transaction': async (client) => { const request = { includeTransactions: true, includeAllData: true, ledgerVersion: 4181996 } - const response = await api.getLedger(request) + const response = await client.getLedger(request) assertResultMatch(response, RESPONSE_FIXTURES.withSettingsTx, 'getLedger') }, - 'with partial payment': async (api) => { + 'with partial payment': async (client) => { const request = { includeTransactions: true, includeAllData: true, ledgerVersion: 22420574 } - const response = await api.getLedger(request) + const response = await client.getLedger(request) assertResultMatch(response, RESPONSE_FIXTURES.withPartial, 'getLedger') }, - 'pre 2014 with partial payment': async (api) => { + 'pre 2014 with partial payment': async (client) => { const request = { includeTransactions: true, includeAllData: true, ledgerVersion: 100001 } - const response = await api.getLedger(request) + const response = await client.getLedger(request) assertResultMatch( response, RESPONSE_FIXTURES.pre2014withPartial, 'getLedger' ) }, - 'full, then computeLedgerHash': async (api) => { + 'full, then computeLedgerHash': async (client) => { const request = { includeTransactions: true, includeState: true, includeAllData: true, ledgerVersion: 38129 } - const response = await api.getLedger(request) + const response = await client.getLedger(request) assertResultMatch(response, RESPONSE_FIXTURES.full, 'getLedger') const ledger = { ...response, parentCloseTime: response.closeTime } - const hash = api.computeLedgerHash(ledger, {computeTreeHashes: true}) + const hash = client.computeLedgerHash(ledger, {computeTreeHashes: true}) assert.strictEqual( hash, 'E6DB7365949BF9814D76BCC730B01818EB9136A89DB224F3F9F5AAE4569D758E' diff --git a/test/api/getLedgerVersion/index.ts b/test/client/getLedgerVersion/index.ts similarity index 61% rename from test/api/getLedgerVersion/index.ts rename to test/client/getLedgerVersion/index.ts index a2edb5d3..23adf044 100644 --- a/test/api/getLedgerVersion/index.ts +++ b/test/client/getLedgerVersion/index.ts @@ -4,11 +4,11 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default test': async (api, address) => { - const ver = await api.getLedgerVersion() + 'default test': async (client, address) => { + const ver = await client.getLedgerVersion() assert.strictEqual(ver, 8819951) } } diff --git a/test/api/getOrderbook/index.ts b/test/client/getOrderbook/index.ts similarity index 79% rename from test/api/getOrderbook/index.ts rename to test/client/getOrderbook/index.ts index 1b43a2fa..c7b2771b 100644 --- a/test/api/getOrderbook/index.ts +++ b/test/client/getOrderbook/index.ts @@ -41,11 +41,11 @@ function checkSortingOfOrders(orders) { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'normal': async (api, address) => { - const response = await api.getOrderbook( + 'normal': async (client, address) => { + const response = await client.getOrderbook( address, requests.getOrderbook.normal, {limit: 20} @@ -53,25 +53,25 @@ export default { assertResultMatch(response, responses.getOrderbook.normal, 'getOrderbook') }, - 'invalid options': async (api, address) => { + 'invalid options': async (client, address) => { assertRejects( - api.getOrderbook(address, requests.getOrderbook.normal, { + client.getOrderbook(address, requests.getOrderbook.normal, { // @ts-ignore invalid: 'options' }), - api.errors.ValidationError + client.errors.ValidationError ) }, - 'with XRP': async (api, address) => { - const response = await api.getOrderbook( + 'with XRP': async (client, address) => { + const response = await client.getOrderbook( address, requests.getOrderbook.withXRP ) assertResultMatch(response, responses.getOrderbook.withXRP, 'getOrderbook') }, - 'sample XRP/JPY book has orders sorted correctly': async (api, address) => { + 'sample XRP/JPY book has orders sorted correctly': async (client, address) => { const orderbookInfo = { base: { // the first currency in pair @@ -83,12 +83,12 @@ export default { } } const myAddress = 'rE9qNjzJXpiUbVomdv7R4xhrXVeH2oVmGR' - const response = await api.getOrderbook(myAddress, orderbookInfo) + const response = await client.getOrderbook(myAddress, orderbookInfo) assert.deepStrictEqual([], response.bids) checkSortingOfOrders(response.asks) }, - 'sample USD/XRP book has orders sorted correctly': async (api, address) => { + 'sample USD/XRP book has orders sorted correctly': async (client, address) => { const orderbookInfo = { counter: {currency: 'XRP'}, base: { @@ -97,14 +97,14 @@ export default { } } const myAddress = 'rE9qNjzJXpiUbVomdv7R4xhrXVeH2oVmGR' - const response = await api.getOrderbook(myAddress, orderbookInfo) + const response = await client.getOrderbook(myAddress, orderbookInfo) checkSortingOfOrders(response.bids) checkSortingOfOrders(response.asks) }, // WARNING: This test fails to catch the sorting bug, issue #766 - 'sorted so that best deals come first [bad test]': async (api, address) => { - const response = await api.getOrderbook( + 'sorted so that best deals come first [bad test]': async (client, address) => { + const response = await client.getOrderbook( address, requests.getOrderbook.normal ) @@ -127,8 +127,8 @@ export default { ) }, - 'currency & counterparty are correct': async (api, address) => { - const response = await api.getOrderbook( + 'currency & counterparty are correct': async (client, address) => { + const response = await client.getOrderbook( address, requests.getOrderbook.normal ) @@ -143,8 +143,8 @@ export default { }) }, - 'direction is correct for bids and asks': async (api, address) => { - const response = await api.getOrderbook( + 'direction is correct for bids and asks': async (client, address) => { + const response = await client.getOrderbook( address, requests.getOrderbook.normal ) diff --git a/test/api/getOrders/index.ts b/test/client/getOrders/index.ts similarity index 63% rename from test/api/getOrders/index.ts rename to test/client/getOrders/index.ts index afa9dace..a50e66b5 100644 --- a/test/api/getOrders/index.ts +++ b/test/client/getOrders/index.ts @@ -11,24 +11,24 @@ export const config = { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getOrders': async (api, address) => { - const result = await api.getOrders(address) + 'getOrders': async (client, address) => { + const result = await client.getOrders(address) assertResultMatch(result, responses.getOrders, 'getOrders') }, - 'getOrders - limit': async (api, address) => { - const result = await api.getOrders(address, {limit: 20}) + 'getOrders - limit': async (client, address) => { + const result = await client.getOrders(address, {limit: 20}) assertResultMatch(result, responses.getOrders, 'getOrders') }, - 'getOrders - invalid options': async (api, address) => { + 'getOrders - invalid options': async (client, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getOrders(address, {invalid: 'options'}), - api.errors.ValidationError + client.getOrders(address, {invalid: 'options'}), + client.errors.ValidationError ) } } diff --git a/test/api/getPaths/index.ts b/test/client/getPaths/index.ts similarity index 50% rename from test/api/getPaths/index.ts rename to test/client/getPaths/index.ts index 19e9eeb1..caea507b 100644 --- a/test/api/getPaths/index.ts +++ b/test/client/getPaths/index.ts @@ -9,18 +9,18 @@ const {getPaths: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'simple test': async (api) => { - const response = await api.getPaths(REQUEST_FIXTURES.normal) + 'simple test': async (client) => { + const response = await client.getPaths(REQUEST_FIXTURES.normal) assertResultMatch(response, RESPONSE_FIXTURES.XrpToUsd, 'getPaths') }, - 'queuing': async (api) => { + 'queuing': async (client) => { const [normalResult, usdOnlyResult, xrpOnlyResult] = await Promise.all([ - api.getPaths(REQUEST_FIXTURES.normal), - api.getPaths(REQUEST_FIXTURES.UsdToUsd), - api.getPaths(REQUEST_FIXTURES.XrpToXrp) + client.getPaths(REQUEST_FIXTURES.normal), + client.getPaths(REQUEST_FIXTURES.UsdToUsd), + client.getPaths(REQUEST_FIXTURES.XrpToXrp) ]) assertResultMatch(normalResult, RESPONSE_FIXTURES.XrpToUsd, 'getPaths') assertResultMatch(usdOnlyResult, RESPONSE_FIXTURES.UsdToUsd, 'getPaths') @@ -30,66 +30,66 @@ export default { // need decide what to do with currencies/XRP: // if add 'XRP' in currencies, then there will be exception in // xrpToDrops function (called from toRippledAmount) - 'getPaths USD 2 USD': async (api) => { - const response = await api.getPaths(REQUEST_FIXTURES.UsdToUsd) + 'getPaths USD 2 USD': async (client) => { + const response = await client.getPaths(REQUEST_FIXTURES.UsdToUsd) assertResultMatch(response, RESPONSE_FIXTURES.UsdToUsd, 'getPaths') }, - 'getPaths XRP 2 XRP': async (api) => { - const response = await api.getPaths(REQUEST_FIXTURES.XrpToXrp) + 'getPaths XRP 2 XRP': async (client) => { + const response = await client.getPaths(REQUEST_FIXTURES.XrpToXrp) assertResultMatch(response, RESPONSE_FIXTURES.XrpToXrp, 'getPaths') }, - 'source with issuer': async (api) => { + 'source with issuer': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.issuer), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.issuer), + client.errors.NotFoundError ) }, - 'XRP 2 XRP - not enough': async (api) => { + 'XRP 2 XRP - not enough': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.XrpToXrpNotEnough), + client.errors.NotFoundError ) }, - 'invalid PathFind': async (api) => { + 'invalid PathFind': async (client) => { assert.throws(() => { - api.getPaths(REQUEST_FIXTURES.invalid) + client.getPaths(REQUEST_FIXTURES.invalid) }, /Cannot specify both source.amount/) }, - 'does not accept currency': async (api) => { + 'does not accept currency': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.NotAcceptCurrency), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.NotAcceptCurrency), + client.errors.NotFoundError ) }, - 'no paths': async (api) => { + 'no paths': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.NoPaths), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.NoPaths), + client.errors.NotFoundError ) }, - 'no paths source amount': async (api) => { + 'no paths source amount': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.NoPathsSource), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.NoPathsSource), + client.errors.NotFoundError ) }, - 'no paths with source currencies': async (api) => { + 'no paths with source currencies': async (client) => { return assertRejects( - api.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies), - api.errors.NotFoundError + client.getPaths(REQUEST_FIXTURES.NoPathsWithCurrencies), + client.errors.NotFoundError ) }, - 'error: srcActNotFound': async (api) => { + 'error: srcActNotFound': async (client) => { return assertRejects( - api.getPaths({ + client.getPaths({ ...REQUEST_FIXTURES.normal, source: {address: addresses.NOTFOUND} }), - api.errors.RippleError + client.errors.RippleError ) }, - 'send all': async (api) => { - const response = await api.getPaths(REQUEST_FIXTURES.sendAll) + 'send all': async (client) => { + const response = await client.getPaths(REQUEST_FIXTURES.sendAll) assertResultMatch(response, RESPONSE_FIXTURES.sendAll, 'getPaths') } } diff --git a/test/api/getPaymentChannel/index.ts b/test/client/getPaymentChannel/index.ts similarity index 63% rename from test/api/getPaymentChannel/index.ts rename to test/client/getPaymentChannel/index.ts index 34227718..55632b3b 100644 --- a/test/api/getPaymentChannel/index.ts +++ b/test/client/getPaymentChannel/index.ts @@ -5,39 +5,39 @@ const {getPaymentChannel: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getPaymentChannel': async (api, address) => { + 'getPaymentChannel': async (client, address) => { const channelId = 'E30E709CF009A1F26E0E5C48F7AA1BFB79393764F15FB108BDC6E06D3CBD8415' - const result = await api.getPaymentChannel(channelId) + const result = await client.getPaymentChannel(channelId) assertResultMatch(result, RESPONSE_FIXTURES.normal, 'getPaymentChannel') }, - 'getPaymentChannel - full': async (api, address) => { + 'getPaymentChannel - full': async (client, address) => { const channelId = 'D77CD4713AA08195E6B6D0E5BC023DA11B052EBFF0B5B22EDA8AE85345BCF661' - const result = await api.getPaymentChannel(channelId) + const result = await client.getPaymentChannel(channelId) assertResultMatch(result, RESPONSE_FIXTURES.full, 'getPaymentChannel') }, - 'getPaymentChannel - not found': async (api, address) => { + 'getPaymentChannel - not found': async (client, address) => { const channelId = 'DFA557EA3497585BFE83F0F97CC8E4530BBB99967736BB95225C7F0C13ACE708' await assertRejects( - api.getPaymentChannel(channelId), - api.errors.RippledError, + client.getPaymentChannel(channelId), + client.errors.RippledError, 'entryNotFound' ) }, - 'getPaymentChannel - wrong type': async (api, address) => { + 'getPaymentChannel - wrong type': async (client, address) => { const channelId = '8EF9CCB9D85458C8D020B3452848BBB42EAFDDDB69A93DD9D1223741A4CA562B' await assertRejects( - api.getPaymentChannel(channelId), - api.errors.NotFoundError, + client.getPaymentChannel(channelId), + client.errors.NotFoundError, 'Payment channel ledger entry not found' ) } diff --git a/test/api/getServerInfo/index.ts b/test/client/getServerInfo/index.ts similarity index 56% rename from test/api/getServerInfo/index.ts rename to test/client/getServerInfo/index.ts index 886aae13..914167f3 100644 --- a/test/api/getServerInfo/index.ts +++ b/test/client/getServerInfo/index.ts @@ -5,40 +5,40 @@ import {assertResultMatch, TestSuite, assertRejects} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default': async (api, address) => { - const serverInfo = await api.getServerInfo() + 'default': async (client, address) => { + const serverInfo = await client.getServerInfo() assertResultMatch(serverInfo, responses.getServerInfo, 'getServerInfo') }, - 'error': async (api, address) => { - api.connection.request({ + 'error': async (client, address) => { + client.connection.request({ command: 'config', data: {returnErrorOnServerInfo: true} }) try { - await api.getServerInfo() + await client.getServerInfo() throw new Error('Should throw NetworkError') } catch (err) { - assert(err instanceof api.errors.RippledError) + assert(err instanceof client.errors.RippledError) assert.equal(err.message, 'You are placing too much load on the server.') assert.equal(err.data.error, 'slowDown') } }, - 'no validated ledger': async (api, address) => { - api.connection.request({ + 'no validated ledger': async (client, address) => { + client.connection.request({ command: 'config', data: {serverInfoWithoutValidated: true} }) - const serverInfo = await api.getServerInfo() + const serverInfo = await client.getServerInfo() assert.strictEqual(serverInfo.networkLedger, 'waiting') }, - 'getServerInfo - offline': async (api, address) => { - await api.disconnect() - return assertRejects(api.getServerInfo(), api.errors.NotConnectedError) + 'getServerInfo - offline': async (client, address) => { + await client.disconnect() + return assertRejects(client.getServerInfo(), client.errors.NotConnectedError) } } diff --git a/test/api/getSettings/index.ts b/test/client/getSettings/index.ts similarity index 55% rename from test/api/getSettings/index.ts rename to test/client/getSettings/index.ts index c090ba07..36978963 100644 --- a/test/api/getSettings/index.ts +++ b/test/client/getSettings/index.ts @@ -5,24 +5,24 @@ const {getSettings: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getSettings': async (api, address) => { - const result = await api.getSettings(address) + 'getSettings': async (client, address) => { + const result = await client.getSettings(address) assertResultMatch(result, RESPONSE_FIXTURES, 'getSettings') }, - 'getSettings - options undefined': async (api, address) => { - const result = await api.getSettings(address, undefined) + 'getSettings - options undefined': async (client, address) => { + const result = await client.getSettings(address, undefined) assertResultMatch(result, RESPONSE_FIXTURES, 'getSettings') }, - 'getSettings - invalid options': async (api, address) => { + 'getSettings - invalid options': async (client, address) => { await assertRejects( // @ts-ignore - This is intentionally invalid - api.getSettings(address, {invalid: 'options'}), - api.errors.ValidationError + client.getSettings(address, {invalid: 'options'}), + client.errors.ValidationError ) } } diff --git a/test/api/getTransaction/index.ts b/test/client/getTransaction/index.ts similarity index 65% rename from test/api/getTransaction/index.ts rename to test/client/getTransaction/index.ts index 1805358b..ce0bb92c 100644 --- a/test/api/getTransaction/index.ts +++ b/test/client/getTransaction/index.ts @@ -3,7 +3,7 @@ import { MissingLedgerHistoryError, NotFoundError, UnexpectedError -} from 'ripple-api/common/errors' +} from 'xrpl-local/common/errors' import {PendingLedgerVersionError} from '../../../src/common/errors' import hashes from '../../fixtures/hashes.json' import responses from '../../fixtures/responses' @@ -18,19 +18,19 @@ function closeLedger(connection) { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'payment': async (api, address) => { - const response = await api.getTransaction(hashes.VALID_TRANSACTION_HASH) + 'payment': async (client, address) => { + const response = await client.getTransaction(hashes.VALID_TRANSACTION_HASH) assertResultMatch(response, RESPONSE_FIXTURES.payment, 'getTransaction') }, - 'payment - include raw transaction': async (api, address) => { + 'payment - include raw transaction': async (client, address) => { const options = { includeRawTransaction: true } - const response = await api.getTransaction( + const response = await client.getTransaction( hashes.VALID_TRANSACTION_HASH, options ) @@ -41,14 +41,14 @@ export default { ) }, - 'settings': async (api, address) => { + 'settings': async (client, address) => { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.settings, 'getTransaction') }, - 'settings - include raw transaction': async (api, address) => { + 'settings - include raw transaction': async (client, address) => { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B' const options = { @@ -57,38 +57,38 @@ export default { const expected = Object.assign({}, RESPONSE_FIXTURES.settings) // Avoid mutating test fixture expected.rawTransaction = '{"Account":"rLVKsA4F9iJBbA6rX2x4wCmkj6drgtqpQe","Fee":"10","Flags":2147483648,"Sequence":1,"SetFlag":2,"SigningPubKey":"03EA3ADCA632F125EC2CC4F7F6A82DE0DCE2B65290CAC1F22242C5163F0DA9652D","TransactionType":"AccountSet","TxnSignature":"3045022100DE8B666B1A31EA65011B0F32130AB91A5747E32FA49B3054CEE8E8362DBAB98A022040CF0CF254677A8E5CD04C59CA2ED7F6F15F7E184641BAE169C561650967B226","date":460832270,"hash":"4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B","inLedger":8206418,"ledger_index":8206418,"meta":{"AffectedNodes":[{"ModifiedNode":{"FinalFields":{"Account":"rLVKsA4F9iJBbA6rX2x4wCmkj6drgtqpQe","Balance":"29999990","Flags":786432,"OwnerCount":0,"Sequence":2},"LedgerEntryType":"AccountRoot","LedgerIndex":"3F5072C4875F32ED770DAF3610A716600ED7C7BB0348FADC7A98E011BB2CD36F","PreviousFields":{"Balance":"30000000","Flags":4194304,"Sequence":1},"PreviousTxnID":"3FB0350A3742BBCC0D8AA3C5247D1AEC01177D0A24D9C34762BAA2FEA8AD88B3","PreviousTxnLgrSeq":8206397}}],"TransactionIndex":5,"TransactionResult":"tesSUCCESS"},"validated":true}' - const response = await api.getTransaction(hash, options) + const response = await client.getTransaction(hash, options) assertResultMatch(response, expected, 'getTransaction') }, - 'order': async (api, address) => { + 'order': async (client, address) => { const hash = '10A6FB4A66EE80BED46AAE4815D7DC43B97E944984CCD5B93BCF3F8538CABC51' - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.order, 'getTransaction') }, - 'order with memo': async (api, address) => { + 'order with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_OFFER_CREATE_TRANSACTION_HASH - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.orderWithMemo, 'getTransaction') }, - 'sell order': async (api, address) => { + 'sell order': async (client, address) => { const hash = '458101D51051230B1D56E9ACAFAA34451BF65FA000F95DF6F0FF5B3A62D83FC2' - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.orderSell, 'getTransaction') }, - 'order cancellation': async (api, address) => { + 'order cancellation': async (client, address) => { const hash = '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E' - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.orderCancellation, @@ -96,10 +96,10 @@ export default { ) }, - 'order with expiration cancellation': async (api, address) => { + 'order with expiration cancellation': async (client, address) => { const hash = '097B9491CC76B64831F1FEA82EAA93BCD728106D90B65A072C933888E946C40B' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.orderWithExpirationCancellation, @@ -107,10 +107,10 @@ export default { ) }, - 'order cancellation with memo': async (api, address) => { + 'order cancellation with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_ORDER_CANCELLATION_TRANSACTION_HASH - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.orderCancellationWithMemo, @@ -118,17 +118,17 @@ export default { ) }, - 'trustline set': async (api, address) => { + 'trustline set': async (client, address) => { const hash = '635A0769BD94710A1F6A76CDE65A3BC661B20B798807D1BBBDADCEA26420538D' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.trustline, 'getTransaction') }, - 'trustline frozen off': async (api, address) => { + 'trustline frozen off': async (client, address) => { const hash = 'FE72FAD0FA7CA904FB6C633A1666EDF0B9C73B2F5A4555D37EEF2739A78A531B' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.trustlineFrozenOff, @@ -136,10 +136,10 @@ export default { ) }, - 'trustline no quality': async (api, address) => { + 'trustline no quality': async (client, address) => { const hash = 'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.trustlineNoQuality, @@ -147,10 +147,10 @@ export default { ) }, - 'trustline add memo': async (api, address) => { + 'trustline add memo': async (client, address) => { const hash = '9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.trustlineAddMemo, @@ -158,34 +158,34 @@ export default { ) }, - 'not validated': async (api, address) => { + 'not validated': async (client, address) => { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10' await assertRejects( - api.getTransaction(hash), + client.getTransaction(hash), NotFoundError, 'Transaction not found' ) }, - 'tracking on': async (api, address) => { + 'tracking on': async (client, address) => { const hash = '8925FC8844A1E930E2CC76AD0A15E7665AFCC5425376D548BB1413F484C31B8C' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.trackingOn, 'getTransaction') }, - 'tracking off': async (api, address) => { + 'tracking off': async (client, address) => { const hash = 'C8C5E20DFB1BF533D0D81A2ED23F0A3CBD1EF2EE8A902A1D760500473CC9C582' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.trackingOff, 'getTransaction') }, - 'set regular key': async (api, address) => { + 'set regular key': async (client, address) => { const hash = '278E6687C1C60C6873996210A6523564B63F2844FB1019576C157353B1813E60' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.setRegularKey, @@ -193,126 +193,126 @@ export default { ) }, - 'not found in range': async (api, address) => { + 'not found in range': async (client, address) => { const hash = '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E' const options = { minLedgerVersion: 32570, maxLedgerVersion: 32571 } - await assertRejects(api.getTransaction(hash, options), NotFoundError) + await assertRejects(client.getTransaction(hash, options), NotFoundError) }, - 'not found by hash': async (api, address) => { + 'not found by hash': async (client, address) => { const hash = hashes.NOTFOUND_TRANSACTION_HASH - await assertRejects(api.getTransaction(hash), NotFoundError) + await assertRejects(client.getTransaction(hash), NotFoundError) }, - 'missing ledger history': async (api, address) => { + 'missing ledger history': async (client, address) => { const hash = hashes.NOTFOUND_TRANSACTION_HASH // make gaps in history - closeLedger(api.connection) + closeLedger(client.connection) - await assertRejects(api.getTransaction(hash), MissingLedgerHistoryError) + await assertRejects(client.getTransaction(hash), MissingLedgerHistoryError) }, - 'missing ledger history with ledger range': async (api, address) => { + 'missing ledger history with ledger range': async (client, address) => { const hash = hashes.NOTFOUND_TRANSACTION_HASH const options = { minLedgerVersion: 32569, maxLedgerVersion: 32571 } await assertRejects( - api.getTransaction(hash, options), + client.getTransaction(hash, options), MissingLedgerHistoryError ) }, - 'not found - future maxLedgerVersion': async (api, address) => { + 'not found - future maxLedgerVersion': async (client, address) => { const hash = hashes.NOTFOUND_TRANSACTION_HASH const options = { maxLedgerVersion: 99999999999 } await assertRejects( - api.getTransaction(hash, options), + client.getTransaction(hash, options), PendingLedgerVersionError, "maxLedgerVersion is greater than server's most recent validated ledger" ) }, - 'transaction not validated': async (api, address) => { + 'transaction not validated': async (client, address) => { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11' await assertRejects( - api.getTransaction(hash), + client.getTransaction(hash), NotFoundError, /Transaction has not been validated yet/ ) }, - 'transaction ledger not found': async (api, address) => { + 'transaction ledger not found': async (client, address) => { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA12' await assertRejects( - api.getTransaction(hash), + client.getTransaction(hash), NotFoundError, /ledger not found/ ) }, - 'ledger missing close time': async (api, address) => { + 'ledger missing close time': async (client, address) => { const hash = '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A04' - closeLedger(api.connection) - await assertRejects(api.getTransaction(hash), UnexpectedError) + closeLedger(client.connection) + await assertRejects(client.getTransaction(hash), UnexpectedError) }, // Checks - 'CheckCreate': async (api, address) => { + 'CheckCreate': async (client, address) => { const hash = '605A2E2C8E48AECAF5C56085D1AEAA0348DC838CE122C9188F94EB19DA05C2FE' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCreate, 'getTransaction') }, - 'CheckCreate with memo': async (api, address) => { + 'CheckCreate with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_CHECK_CREATE_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCreateWithMemo, 'getTransaction') }, - 'CheckCancel': async (api, address) => { + 'CheckCancel': async (client, address) => { const hash = 'B4105D1B2D83819647E4692B7C5843D674283F669524BD50C9614182E3A12CD4' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCancel, 'getTransaction') }, - 'CheckCancel with memo': async (api, address) => { + 'CheckCancel with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_CHECK_CANCEL_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCancelWithMemo, 'getTransaction') }, - 'CheckCash': async (api, address) => { + 'CheckCash': async (client, address) => { const hash = '8321208465F70BA52C28BCC4F646BAF3B012BA13B57576C0336F42D77E3E0749' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCash, 'getTransaction') }, - 'CheckCash with memo': async (api, address) => { + 'CheckCash with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_CHECK_CASH_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.checkCashWithMemo, 'getTransaction') }, // Escrows - 'EscrowCreation': async (api, address) => { + 'EscrowCreation': async (client, address) => { const hash = '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE1' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.escrowCreation, @@ -320,10 +320,10 @@ export default { ) }, - 'EscrowCancellation': async (api, address) => { + 'EscrowCancellation': async (client, address) => { const hash = 'F346E542FFB7A8398C30A87B952668DAB48B7D421094F8B71776DA19775A3B22' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.escrowCancellation, @@ -331,14 +331,14 @@ export default { ) }, - 'EscrowExecution': async (api, address) => { + 'EscrowExecution': async (client, address) => { const options = { minLedgerVersion: 10, maxLedgerVersion: 15 } const hash = 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD136993B' - const response = await api.getTransaction(hash, options) + const response = await client.getTransaction(hash, options) assertResultMatch( response, RESPONSE_FIXTURES.escrowExecution, @@ -346,10 +346,10 @@ export default { ) }, - 'EscrowExecution simple': async (api, address) => { + 'EscrowExecution simple': async (client, address) => { const hash = 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD1369931' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.escrowExecutionSimple, @@ -357,10 +357,10 @@ export default { ) }, - 'PaymentChannelCreate': async (api, address) => { + 'PaymentChannelCreate': async (client, address) => { const hash = '0E9CA3AB1053FC0C1CBAA75F636FE1EC92F118C7056BBEF5D63E4C116458A16D' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelCreate, @@ -368,9 +368,9 @@ export default { ) }, - 'PaymentChannelCreate with memo': async (api, address) => { + 'PaymentChannelCreate with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_PAYMENT_CHANNEL_CREATE_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelCreateWithMemo, @@ -378,10 +378,10 @@ export default { ) }, - 'PaymentChannelFund': async (api, address) => { + 'PaymentChannelFund': async (client, address) => { const hash = 'CD053D8867007A6A4ACB7A432605FE476D088DCB515AFFC886CF2B4EB6D2AE8B' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelFund, @@ -389,9 +389,9 @@ export default { ) }, - 'PaymentChannelFund with memo': async (api, address) => { + 'PaymentChannelFund with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_PAYMENT_CHANNEL_FUND_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelFundWithMemo, @@ -399,10 +399,10 @@ export default { ) }, - 'PaymentChannelClaim': async (api, address) => { + 'PaymentChannelClaim': async (client, address) => { const hash = '81B9ECAE7195EB6E8034AEDF44D8415A7A803E14513FDBB34FA984AB37D59563' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelClaim, @@ -410,9 +410,9 @@ export default { ) }, - 'PaymentChannelClaim with memo': async (api, address) => { + 'PaymentChannelClaim with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_PAYMENT_CHANNEL_CLAIM_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.paymentChannelClaimWithMemo, @@ -420,10 +420,10 @@ export default { ) }, - 'AccountDelete': async (api, address) => { + 'AccountDelete': async (client, address) => { const hash = 'EC2AB14028DC84DE525470AB4DAAA46358B50A8662C63804BFF38244731C0CB9' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.accountDelete, @@ -431,9 +431,9 @@ export default { ) }, - 'AccountDelete with memo': async (api, address) => { + 'AccountDelete with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_ACCOUNT_DELETE_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch( response, RESPONSE_FIXTURES.accountDeleteWithMemo, @@ -441,18 +441,18 @@ export default { ) }, - 'no Meta': async (api, address) => { + 'no Meta': async (client, address) => { const hash = 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assert.deepEqual(response, RESPONSE_FIXTURES.noMeta) }, - 'Unrecognized transaction type': async (api, address) => { + 'Unrecognized transaction type': async (client, address) => { const hash = 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11' - closeLedger(api.connection) - const response = await api.getTransaction(hash) + closeLedger(client.connection) + const response = await client.getTransaction(hash) assert.strictEqual( // @ts-ignore response.specification.UNAVAILABLE, @@ -460,49 +460,49 @@ export default { ) }, - 'amendment': async (api, address) => { + 'amendment': async (client, address) => { const hash = 'A971B83ABED51D83749B73F3C1AAA627CD965AFF74BE8CD98299512D6FB0658F' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.amendment) }, - 'feeUpdate': async (api, address) => { + 'feeUpdate': async (client, address) => { const hash = 'C6A40F56127436DCD830B1B35FF939FD05B5747D30D6542572B7A835239817AF' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.feeUpdate) }, - 'feeUpdate with memo': async (api, address) => { + 'feeUpdate with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_FEE_UPDATE_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.feeUpdateWithMemo) }, - 'order with one memo': async (api, address) => { + 'order with one memo': async (client, address) => { const hash = '995570FE1E40F42DF56BFC80503BA9E3C1229619C61A1C279A76BC0805036D74' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.withMemo) }, - 'order with more than one memo': async (api, address) => { + 'order with more than one memo': async (client, address) => { const hash = '995570FE1E40F42DF56BFC80503BA9E3C1229619C61A1C279A76BC0805036D73' - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.withMemos) }, - 'ticketCreate with memo': async (api, address) => { + 'ticketCreate with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_TICKET_CREATE_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.ticketCreateWithMemo) }, - 'depositPreauth with memo': async (api, address) => { + 'depositPreauth with memo': async (client, address) => { const hash = hashes.WITH_MEMOS_DEPOSIT_PREAUTH_TRANSACTION_HASH - const response = await api.getTransaction(hash) + const response = await client.getTransaction(hash) assertResultMatch(response, RESPONSE_FIXTURES.depositPreauthWithMemo) } } diff --git a/test/api/getTransactions/index.ts b/test/client/getTransactions/index.ts similarity index 69% rename from test/api/getTransactions/index.ts rename to test/client/getTransactions/index.ts index 0156c2a6..e9f18233 100644 --- a/test/api/getTransactions/index.ts +++ b/test/client/getTransactions/index.ts @@ -1,33 +1,33 @@ -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import assert from 'assert-diff' import {assertResultMatch, TestSuite, assertRejects} from '../../utils' import responses from '../../fixtures/responses' import hashes from '../../fixtures/hashes.json' import addresses from '../../fixtures/addresses.json' -const utils = RippleAPI._PRIVATE.ledgerUtils +const utils = Client._PRIVATE.ledgerUtils const {getTransactions: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default': async (api, address) => { + 'default': async (client, address) => { const options = {types: ['payment', 'order'], initiated: true, limit: 2} - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assertResultMatch(response, RESPONSE_FIXTURES.normal, 'getTransactions') }, - 'include raw transactions': async (api, address) => { + 'include raw transactions': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, limit: 2, includeRawTransactions: true } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) assertResultMatch( response, RESPONSE_FIXTURES.includeRawTransactions, @@ -35,7 +35,7 @@ export default { ) }, - 'earliest first': async (api, address) => { + 'earliest first': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, @@ -45,12 +45,12 @@ export default { const expected = Array.from(RESPONSE_FIXTURES.normal as any[]).sort( utils.compareTransactions ) - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assertResultMatch(response, expected, 'getTransactions') }, - 'earliest first with start option': async (api, address) => { + 'earliest first with start option': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, @@ -58,11 +58,11 @@ export default { start: hashes.VALID_TRANSACTION_HASH, earliestFirst: true } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) assert.strictEqual(response.length, 0) }, - 'gap': async (api, address) => { + 'gap': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, @@ -70,12 +70,12 @@ export default { maxLedgerVersion: 348858000 } return assertRejects( - api.getTransactions(address, options), - api.errors.MissingLedgerHistoryError + client.getTransactions(address, options), + client.errors.MissingLedgerHistoryError ) }, - 'tx not found': async (api, address) => { + 'tx not found': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, @@ -84,12 +84,12 @@ export default { counterparty: address } return assertRejects( - api.getTransactions(address, options), - api.errors.NotFoundError + client.getTransactions(address, options), + client.errors.NotFoundError ) }, - 'filters': async (api, address) => { + 'filters': async (client, address) => { const options = { types: ['payment', 'order'], initiated: true, @@ -97,14 +97,14 @@ export default { excludeFailures: true, counterparty: addresses.ISSUER } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assert.strictEqual(response.length, 10) response.forEach((t) => assert(t.type === 'payment' || t.type === 'order')) response.forEach((t) => assert(t.outcome.result === 'tesSUCCESS')) }, - 'filters for incoming': async (api, address) => { + 'filters for incoming': async (client, address) => { const options = { types: ['payment', 'order'], initiated: false, @@ -112,7 +112,7 @@ export default { excludeFailures: true, counterparty: addresses.ISSUER } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assert.strictEqual(response.length, 10) response.forEach((t) => assert(t.type === 'payment' || t.type === 'order')) @@ -120,39 +120,39 @@ export default { }, // this is the case where core.RippleError just falls - // through the api to the user - 'error': async (api, address) => { + // through the client to the user + 'error': async (client, address) => { const options = {types: ['payment', 'order'], initiated: true, limit: 13} return assertRejects( - api.getTransactions(address, options), - api.errors.RippleError + client.getTransactions(address, options), + client.errors.RippleError ) }, // TODO: this doesn't test much, just that it doesn't crash - 'getTransactions with start option': async (api, address) => { + 'getTransactions with start option': async (client, address) => { const options = { start: hashes.VALID_TRANSACTION_HASH, earliestFirst: false, limit: 2 } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assertResultMatch(response, RESPONSE_FIXTURES.normal, 'getTransactions') }, - 'start transaction with zero ledger version': async (api, address) => { + 'start transaction with zero ledger version': async (client, address) => { const options = { start: '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA13', limit: 1 } - const response = await api.getTransactions(address, options) + const response = await client.getTransactions(address, options) hack(response) assertResultMatch(response, [], 'getTransactions') }, - 'no options': async (api, address) => { - const response = await api.getTransactions(addresses.OTHER_ACCOUNT) + 'no options': async (client, address) => { + const response = await client.getTransactions(addresses.OTHER_ACCOUNT) assertResultMatch(response, RESPONSE_FIXTURES.one, 'getTransactions') } diff --git a/test/api/getTrustlines/index.ts b/test/client/getTrustlines/index.ts similarity index 53% rename from test/api/getTrustlines/index.ts rename to test/client/getTrustlines/index.ts index 405bf27f..84a4c207 100644 --- a/test/api/getTrustlines/index.ts +++ b/test/client/getTrustlines/index.ts @@ -6,18 +6,18 @@ const {getTrustlines: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'getTrustlines - filtered': async (api, address) => { + 'getTrustlines - filtered': async (client, address) => { const options = {currency: 'USD'} - const result = await api.getTrustlines(address, options) + const result = await client.getTrustlines(address, options) assertResultMatch(result, RESPONSE_FIXTURES.filtered, 'getTrustlines') }, - 'getTrustlines - more than 400 items': async (api, address) => { + 'getTrustlines - more than 400 items': async (client, address) => { const options = {limit: 401} - const result = await api.getTrustlines(addresses.THIRD_ACCOUNT, options) + const result = await client.getTrustlines(addresses.THIRD_ACCOUNT, options) assertResultMatch( result, RESPONSE_FIXTURES.moreThan400Items, @@ -25,12 +25,12 @@ export default { ) }, - 'getTrustlines - no options': async (api, address) => { - await api.getTrustlines(address) + 'getTrustlines - no options': async (client, address) => { + await client.getTrustlines(address) }, - 'getTrustlines - ripplingDisabled works properly': async (api, address) => { - const result = await api.getTrustlines(addresses.FOURTH_ACCOUNT) + 'getTrustlines - ripplingDisabled works properly': async (client, address) => { + const result = await client.getTrustlines(addresses.FOURTH_ACCOUNT) assertResultMatch( result, RESPONSE_FIXTURES.ripplingDisabled, @@ -38,8 +38,8 @@ export default { ) }, - 'getTrustlines - ledger version option': async (api, address) => { - const result = await api.getTrustlines(addresses.FOURTH_ACCOUNT, {ledgerVersion: 5}) + 'getTrustlines - ledger version option': async (client, address) => { + const result = await client.getTrustlines(addresses.FOURTH_ACCOUNT, {ledgerVersion: 5}) assertResultMatch( result, RESPONSE_FIXTURES.moreThan400Items, diff --git a/test/client/hasNextPage/index.ts b/test/client/hasNextPage/index.ts new file mode 100644 index 00000000..87c288fb --- /dev/null +++ b/test/client/hasNextPage/index.ts @@ -0,0 +1,24 @@ +import assert from 'assert-diff' +import {TestSuite} from '../../utils' + +/** + * 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. + */ +export default { + 'returns true when there is another page': async (client, address) => { + const response = await client.request('ledger_data') + assert(client.hasNextPage(response)) + }, + + 'returns false when there are no more pages': async (client, address) => { + const response = await client.request('ledger_data') + const responseNextPage = await client.requestNextPage( + 'ledger_data', + {}, + response + ) + assert(!client.hasNextPage(responseNextPage)) + } +} diff --git a/test/client/isConnected/index.ts b/test/client/isConnected/index.ts new file mode 100644 index 00000000..5bdf91d5 --- /dev/null +++ b/test/client/isConnected/index.ts @@ -0,0 +1,15 @@ +import assert from 'assert-diff' +import {TestSuite} from '../../utils' + +/** + * 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. + */ +export default { + 'disconnect & isConnected': async (client, address) => { + assert.strictEqual(client.isConnected(), true) + await client.disconnect() + assert.strictEqual(client.isConnected(), false) + } +} diff --git a/test/client/isValidAddress/index.ts b/test/client/isValidAddress/index.ts new file mode 100644 index 00000000..f3e6ccd8 --- /dev/null +++ b/test/client/isValidAddress/index.ts @@ -0,0 +1,17 @@ +import assert from 'assert-diff' +import {TestSuite} from '../../utils' +import addresses from '../../fixtures/addresses.json' + +export default { + 'returns true for valid address': async (client, address) => { + assert(client.isValidAddress('rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K')) + assert(client.isValidAddress(addresses.ACCOUNT_X)) + assert(client.isValidAddress(addresses.ACCOUNT_T)) + }, + + 'returns false for invalid address': async (client, address) => { + assert(!client.isValidAddress('foobar')) + assert(!client.isValidAddress(addresses.ACCOUNT_X.slice(0, -1))) + assert(!client.isValidAddress(addresses.ACCOUNT_T.slice(1))) + } +} diff --git a/test/client/isValidSecret/index.ts b/test/client/isValidSecret/index.ts new file mode 100644 index 00000000..b5d393d1 --- /dev/null +++ b/test/client/isValidSecret/index.ts @@ -0,0 +1,12 @@ +import assert from 'assert-diff' +import {TestSuite} from '../../utils' + +export default { + 'returns true for valid secret': async (client, address) => { + assert(client.isValidSecret('snsakdSrZSLkYpCXxfRkS4Sh96PMK')) + }, + + 'returns false for invalid secret': async (client, address) => { + assert(!client.isValidSecret('foobar')) + } +} diff --git a/test/api/prepareCheckCancel/index.ts b/test/client/prepareCheckCancel/index.ts similarity index 75% rename from test/api/prepareCheckCancel/index.ts rename to test/client/prepareCheckCancel/index.ts index 849b647e..ed9ce815 100644 --- a/test/api/prepareCheckCancel/index.ts +++ b/test/client/prepareCheckCancel/index.ts @@ -6,24 +6,24 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareCheckCancel': async (api, address) => { - const result = await api.prepareCheckCancel( + 'prepareCheckCancel': async (client, address) => { + const result = await client.prepareCheckCancel( address, requests.prepareCheckCancel.normal ) assertResultMatch(result, responses.prepareCheckCancel.normal, 'prepare') }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareCheckCancel( + const result = await client.prepareCheckCancel( address, requests.prepareCheckCancel.normal, localInstructions diff --git a/test/api/prepareCheckCash/index.ts b/test/client/prepareCheckCash/index.ts similarity index 71% rename from test/api/prepareCheckCash/index.ts rename to test/client/prepareCheckCash/index.ts index 77be87af..cfe941b8 100644 --- a/test/api/prepareCheckCash/index.ts +++ b/test/client/prepareCheckCash/index.ts @@ -6,32 +6,32 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareCheckCash amount': async (api, address) => { - const result = await api.prepareCheckCash( + 'prepareCheckCash amount': async (client, address) => { + const result = await client.prepareCheckCash( address, requests.prepareCheckCash.amount ) assertResultMatch(result, responses.prepareCheckCash.amount, 'prepare') }, - 'prepareCheckCash deliverMin': async (api, address) => { - const result = await api.prepareCheckCash( + 'prepareCheckCash deliverMin': async (client, address) => { + const result = await client.prepareCheckCash( address, requests.prepareCheckCash.deliverMin ) assertResultMatch(result, responses.prepareCheckCash.deliverMin, 'prepare') }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareCheckCash( + const result = await client.prepareCheckCash( address, requests.prepareCheckCash.amount, localInstructions diff --git a/test/api/prepareCheckCreate/index.ts b/test/client/prepareCheckCreate/index.ts similarity index 73% rename from test/api/prepareCheckCreate/index.ts rename to test/client/prepareCheckCreate/index.ts index 96707c66..54fd4591 100644 --- a/test/api/prepareCheckCreate/index.ts +++ b/test/client/prepareCheckCreate/index.ts @@ -6,15 +6,15 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareCheckCreate': async (api, address) => { + 'prepareCheckCreate': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const result = await api.prepareCheckCreate( + const result = await client.prepareCheckCreate( address, requests.prepareCheckCreate.normal, localInstructions @@ -22,21 +22,21 @@ export default { assertResultMatch(result, responses.prepareCheckCreate.normal, 'prepare') }, - 'prepareCheckCreate full': async (api, address) => { - const result = await api.prepareCheckCreate( + 'prepareCheckCreate full': async (client, address) => { + const result = await client.prepareCheckCreate( address, requests.prepareCheckCreate.full ) assertResultMatch(result, responses.prepareCheckCreate.full, 'prepare') }, - 'prepareCheckCreate with ticket': async (api, address) => { + 'prepareCheckCreate with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareCheckCreate( + const result = await client.prepareCheckCreate( address, requests.prepareCheckCreate.normal, localInstructions diff --git a/test/api/prepareEscrowCancellation/index.ts b/test/client/prepareEscrowCancellation/index.ts similarity index 72% rename from test/api/prepareEscrowCancellation/index.ts rename to test/client/prepareEscrowCancellation/index.ts index fb698d52..0e91cb4e 100644 --- a/test/api/prepareEscrowCancellation/index.ts +++ b/test/client/prepareEscrowCancellation/index.ts @@ -6,11 +6,11 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareEscrowCancellation': async (api, address) => { - const result = await api.prepareEscrowCancellation( + 'prepareEscrowCancellation': async (client, address) => { + const result = await client.prepareEscrowCancellation( address, requests.prepareEscrowCancellation.normal, instructionsWithMaxLedgerVersionOffset @@ -22,8 +22,8 @@ export default { ) }, - 'prepareEscrowCancellation with memos': async (api, address) => { - const result = await api.prepareEscrowCancellation( + 'prepareEscrowCancellation with memos': async (client, address) => { + const result = await client.prepareEscrowCancellation( address, requests.prepareEscrowCancellation.memos ) @@ -34,13 +34,13 @@ export default { ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareEscrowCancellation( + const result = await client.prepareEscrowCancellation( address, requests.prepareEscrowCancellation.normal, localInstructions diff --git a/test/api/prepareEscrowCreation/index.ts b/test/client/prepareEscrowCreation/index.ts similarity index 74% rename from test/api/prepareEscrowCreation/index.ts rename to test/client/prepareEscrowCreation/index.ts index a21f398b..190ab3a7 100644 --- a/test/api/prepareEscrowCreation/index.ts +++ b/test/client/prepareEscrowCreation/index.ts @@ -13,15 +13,15 @@ export const config = { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareEscrowCreation': async (api, address) => { + 'prepareEscrowCreation': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const result = await api.prepareEscrowCreation( + const result = await client.prepareEscrowCreation( address, requests.prepareEscrowCreation.normal, localInstructions @@ -29,31 +29,31 @@ export default { assertResultMatch(result, responses.prepareEscrowCreation.normal, 'prepare') }, - 'prepareEscrowCreation full': async (api, address) => { - const result = await api.prepareEscrowCreation( + 'prepareEscrowCreation full': async (client, address) => { + const result = await client.prepareEscrowCreation( address, requests.prepareEscrowCreation.full ) assertResultMatch(result, responses.prepareEscrowCreation.full, 'prepare') }, - 'prepareEscrowCreation - invalid': async (api, address) => { + 'prepareEscrowCreation - invalid': async (client, address) => { const escrow = Object.assign({}, requests.prepareEscrowCreation.full) delete escrow.amount // Make invalid await assertRejects( - api.prepareEscrowCreation(address, escrow), - api.errors.ValidationError, + client.prepareEscrowCreation(address, escrow), + client.errors.ValidationError, 'instance.escrowCreation requires property "amount"' ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000396', ticketSequence: 23 } - const result = await api.prepareEscrowCreation( + const result = await client.prepareEscrowCreation( address, requests.prepareEscrowCreation.normal, localInstructions diff --git a/test/api/prepareEscrowExecution/index.ts b/test/client/prepareEscrowExecution/index.ts similarity index 70% rename from test/api/prepareEscrowExecution/index.ts rename to test/client/prepareEscrowExecution/index.ts index 2cdbafd6..30ffb025 100644 --- a/test/api/prepareEscrowExecution/index.ts +++ b/test/client/prepareEscrowExecution/index.ts @@ -6,11 +6,11 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareEscrowExecution': async (api, address) => { - const result = await api.prepareEscrowExecution( + 'prepareEscrowExecution': async (client, address) => { + const result = await client.prepareEscrowExecution( address, requests.prepareEscrowExecution.normal, instructionsWithMaxLedgerVersionOffset @@ -22,8 +22,8 @@ export default { ) }, - 'prepareEscrowExecution - simple': async (api, address) => { - const result = await api.prepareEscrowExecution( + 'prepareEscrowExecution - simple': async (client, address) => { + const result = await client.prepareEscrowExecution( address, requests.prepareEscrowExecution.simple ) @@ -34,37 +34,37 @@ export default { ) }, - 'prepareEscrowExecution - no condition': async (api, address) => { + 'prepareEscrowExecution - no condition': async (client, address) => { await assertRejects( - api.prepareEscrowExecution( + client.prepareEscrowExecution( address, requests.prepareEscrowExecution.noCondition, instructionsWithMaxLedgerVersionOffset ), - api.errors.ValidationError, + client.errors.ValidationError, '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.' ) }, - 'prepareEscrowExecution - no fulfillment': async (api, address) => { + 'prepareEscrowExecution - no fulfillment': async (client, address) => { await assertRejects( - api.prepareEscrowExecution( + client.prepareEscrowExecution( address, requests.prepareEscrowExecution.noFulfillment, instructionsWithMaxLedgerVersionOffset ), - api.errors.ValidationError, + client.errors.ValidationError, '"condition" and "fulfillment" fields on EscrowFinish must only be specified together.' ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000396', ticketSequence: 23 } - const result = await api.prepareEscrowExecution( + const result = await client.prepareEscrowExecution( address, requests.prepareEscrowExecution.normal, localInstructions diff --git a/test/api/prepareOrder/index.ts b/test/client/prepareOrder/index.ts similarity index 71% rename from test/api/prepareOrder/index.ts rename to test/client/prepareOrder/index.ts index 917e36e5..c50a99e3 100644 --- a/test/api/prepareOrder/index.ts +++ b/test/client/prepareOrder/index.ts @@ -6,19 +6,19 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'buy order': async (api, address) => { + 'buy order': async (client, address) => { const request = requests.prepareOrder.buy - const result = await api.prepareOrder(address, request) + const result = await client.prepareOrder(address, request) assertResultMatch(result, responses.prepareOrder.buy, 'prepare') }, - 'buy order with expiration': async (api, address) => { + 'buy order with expiration': async (client, address) => { const request = requests.prepareOrder.expiration const response = responses.prepareOrder.expiration - const result = await api.prepareOrder( + const result = await client.prepareOrder( address, request, instructionsWithMaxLedgerVersionOffset @@ -26,9 +26,9 @@ export default { assertResultMatch(result, response, 'prepare') }, - 'sell order': async (api, address) => { + 'sell order': async (client, address) => { const request = requests.prepareOrder.sell - const result = await api.prepareOrder( + const result = await client.prepareOrder( address, request, instructionsWithMaxLedgerVersionOffset @@ -36,28 +36,28 @@ export default { assertResultMatch(result, responses.prepareOrder.sell, 'prepare') }, - 'invalid': async (api, address) => { + 'invalid': async (client, address) => { const request = Object.assign({}, requests.prepareOrder.sell) delete request.direction // Make invalid await assertRejects( - api.prepareOrder( + client.prepareOrder( address, request, instructionsWithMaxLedgerVersionOffset ), - api.errors.ValidationError, + client.errors.ValidationError, 'instance.order requires property "direction"' ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const request = requests.prepareOrder.sell const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareOrder(address, request, localInstructions) + const result = await client.prepareOrder(address, request, localInstructions) assertResultMatch(result, responses.prepareOrder.ticket, 'prepare') } } diff --git a/test/api/prepareOrderCancellation/index.ts b/test/client/prepareOrderCancellation/index.ts similarity index 70% rename from test/api/prepareOrderCancellation/index.ts rename to test/client/prepareOrderCancellation/index.ts index ee507781..742e2b21 100644 --- a/test/api/prepareOrderCancellation/index.ts +++ b/test/client/prepareOrderCancellation/index.ts @@ -6,12 +6,12 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'prepareOrderCancellation': async (api, address) => { + 'prepareOrderCancellation': async (client, address) => { const request = requests.prepareOrderCancellation.simple - const result = await api.prepareOrderCancellation( + const result = await client.prepareOrderCancellation( address, request, instructionsWithMaxLedgerVersionOffset @@ -23,9 +23,9 @@ export default { ) }, - 'no instructions': async (api, address) => { + 'no instructions': async (client, address) => { const request = requests.prepareOrderCancellation.simple - const result = await api.prepareOrderCancellation(address, request) + const result = await client.prepareOrderCancellation(address, request) assertResultMatch( result, responses.prepareOrderCancellation.noInstructions, @@ -33,9 +33,9 @@ export default { ) }, - 'with memos': async (api, address) => { + 'with memos': async (client, address) => { const request = requests.prepareOrderCancellation.withMemos - const result = await api.prepareOrderCancellation(address, request) + const result = await client.prepareOrderCancellation(address, request) assertResultMatch( result, responses.prepareOrderCancellation.withMemos, @@ -43,7 +43,7 @@ export default { ) }, - 'invalid': async (api, address) => { + 'invalid': async (client, address) => { const request = Object.assign( {}, requests.prepareOrderCancellation.withMemos @@ -51,20 +51,20 @@ export default { delete request.orderSequence // Make invalid await assertRejects( - api.prepareOrderCancellation(address, request), - api.errors.ValidationError, + client.prepareOrderCancellation(address, request), + client.errors.ValidationError, 'instance.orderCancellation requires property "orderSequence"' ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const request = requests.prepareOrderCancellation.simple const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareOrderCancellation( + const result = await client.prepareOrderCancellation( address, request, localInstructions diff --git a/test/api/preparePayment/index.ts b/test/client/preparePayment/index.ts similarity index 82% rename from test/api/preparePayment/index.ts rename to test/client/preparePayment/index.ts index 5300a875..3d2a18c1 100644 --- a/test/api/preparePayment/index.ts +++ b/test/client/preparePayment/index.ts @@ -1,12 +1,12 @@ import {assertResultMatch, TestSuite, assertRejects} from '../../utils' import responses from '../../fixtures/responses' import requests from '../../fixtures/requests' -import {ValidationError} from 'ripple-api/common/errors' +import {ValidationError} from 'xrpl-local/common/errors' import binary from 'ripple-binary-codec' import assert from 'assert-diff' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' -const {schemaValidator} = RippleAPI._PRIVATE +const {schemaValidator} = Client._PRIVATE const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} const {preparePayment: REQUEST_FIXTURES} = requests const {preparePayment: RESPONSE_FIXTURES} = responses @@ -15,15 +15,15 @@ const RECIPIENT_ADDRESS = 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'normal': async (api, address) => { + 'normal': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.normal, localInstructions @@ -31,12 +31,12 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.normal, 'prepare') }, - 'min amount xrp': async (api, address) => { + 'min amount xrp': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.minAmountXRP, localInstructions @@ -44,8 +44,8 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.minAmountXRP, 'prepare') }, - 'min amount xrp2xrp': async (api, address) => { - const response = await api.preparePayment( + 'min amount xrp2xrp': async (client, address) => { + const response = await client.preparePayment( address, REQUEST_FIXTURES.minAmount, instructionsWithMaxLedgerVersionOffset @@ -53,7 +53,7 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.minAmountXRPXRP, 'prepare') }, - 'XRP to XRP': async (api, address) => { + 'XRP to XRP': async (client, address) => { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', @@ -73,7 +73,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, payment, instructionsWithMaxLedgerVersionOffset @@ -81,7 +81,7 @@ export default { assertResultMatch(response, expected, 'prepare') }, - 'XRP drops to XRP drops': async (api, address) => { + 'XRP drops to XRP drops': async (client, address) => { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', @@ -101,7 +101,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, payment, instructionsWithMaxLedgerVersionOffset @@ -109,7 +109,7 @@ export default { assertResultMatch(response, expected, 'prepare') }, - 'XRP drops to XRP': async (api, address) => { + 'XRP drops to XRP': async (client, address) => { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', @@ -129,7 +129,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, payment, instructionsWithMaxLedgerVersionOffset @@ -137,7 +137,7 @@ export default { assertResultMatch(response, expected, 'prepare') }, - 'XRP to XRP drops': async (api, address) => { + 'XRP to XRP drops': async (client, address) => { const payment = { source: { address: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', @@ -157,7 +157,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, payment, instructionsWithMaxLedgerVersionOffset @@ -167,7 +167,7 @@ export default { // Errors 'rejects promise and does not throw when payment object is invalid': async ( - api, + client, address ) => { const payment = { @@ -183,14 +183,14 @@ export default { } return assertRejects( - api.preparePayment(address, payment), + client.preparePayment(address, payment), ValidationError, 'payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)' ) }, 'rejects promise and does not throw when field is missing': async ( - api, + client, address ) => { // Marking as "any" to get around the fact that TS won't allow this. @@ -203,14 +203,14 @@ export default { } return assertRejects( - api.preparePayment(address, payment), + client.preparePayment(address, payment), ValidationError, 'instance.payment.source is not exactly one from ,' ) }, 'rejects promise and does not throw when fee exceeds maxFeeXRP': async ( - api, + client, address ) => { const payment = { @@ -224,55 +224,55 @@ export default { } } return assertRejects( - api.preparePayment(address, payment, {fee: '3'}), + client.preparePayment(address, payment, {fee: '3'}), ValidationError, - 'Fee of 3 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the RippleAPI constructor.' + 'Fee of 3 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the Client constructor.' ) }, - 'XRP to XRP no partial': async (api, address) => { + 'XRP to XRP no partial': async (client, address) => { return assertRejects( - api.preparePayment(address, REQUEST_FIXTURES.wrongPartial), + client.preparePayment(address, REQUEST_FIXTURES.wrongPartial), ValidationError, 'XRP to XRP payments cannot be partial payments' ) }, - 'address must match payment.source.address': async (api, address) => { + 'address must match payment.source.address': async (client, address) => { return assertRejects( - api.preparePayment(address, REQUEST_FIXTURES.wrongAddress), + client.preparePayment(address, REQUEST_FIXTURES.wrongAddress), ValidationError, 'address must match payment.source.address' ) }, - 'wrong amount': async (api, address) => { + 'wrong amount': async (client, address) => { return assertRejects( - api.preparePayment(address, REQUEST_FIXTURES.wrongAmount), + client.preparePayment(address, REQUEST_FIXTURES.wrongAmount), ValidationError, 'payment must specify either (source.maxAmount and destination.amount) or (source.amount and destination.minAmount)' ) }, - 'throws when fee exceeds 2 XRP': async (api, address) => { + 'throws when fee exceeds 2 XRP': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, fee: '2.1' } return assertRejects( - api.preparePayment(address, REQUEST_FIXTURES.normal, localInstructions), + client.preparePayment(address, REQUEST_FIXTURES.normal, localInstructions), ValidationError, - 'Fee of 2.1 XRP exceeds max of 2 XRP. To use this fee, increase `maxFeeXRP` in the RippleAPI 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 (api, address) => { - const version = await api.getLedgerVersion() + 'preparePayment with all options specified': async (client, address) => { + const version = await client.getLedgerVersion() const localInstructions = { maxLedgerVersion: version + 100, fee: '0.000012' } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.allOptions, localInstructions @@ -280,12 +280,12 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.allOptions, 'prepare') }, - 'preparePayment without counterparty set': async (api, address) => { + 'preparePayment without counterparty set': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, sequence: 23 } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.noCounterparty, localInstructions @@ -294,7 +294,7 @@ export default { }, 'preparePayment with source.amount/destination.minAmount can be signed': async ( - api, + client, address ) => { // See also: 'sign succeeds with source.amount/destination.minAmount' @@ -303,7 +303,7 @@ export default { ...instructionsWithMaxLedgerVersionOffset, sequence: 23 } - const response = await api.preparePayment( + const response = await client.preparePayment( address, { source: { @@ -330,7 +330,7 @@ export default { // https://github.com/ripple/ripple-lib/issues/1237#issuecomment-631670946 const secret = 'shotKgaEotpcYsshSE39vmSnBDRim' - const result = api.sign(response.txJSON, secret) + const result = client.sign(response.txJSON, secret) const expectedResult = { signedTransaction: '12000022800200002400000017201B0086955361EC6386F26FC0FFFF0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A68400000000000000C69D4438D7EA4C6800000000000000000000000000047425000000000000C155FFE99C8C91F67083CEFFDB69EBFE76348CA6AD4446F8C5D8A5E0B0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100D9634523D8E232D4A7807A71856023D82AC928FA29848571B820867898413B5F022041AC00EC1F81A26A6504EBF844A38CC3204694EF2CC1A97A87632721631F93DA81145E7B112523F68D2F5E879DB4EAC51C6698A6930483149F500E50C2F016CA01945E5A1E5846B61EF2D376', @@ -345,8 +345,8 @@ export default { schemaValidator.schemaValidate('sign', result) }, - 'destination.minAmount': async (api, address) => { - const response = await api.preparePayment( + 'destination.minAmount': async (client, address) => { + const response = await client.preparePayment( address, responses.getPaths.sendAll[0], instructionsWithMaxLedgerVersionOffset @@ -354,8 +354,8 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.minAmount, 'prepare') }, - 'caps fee at 2 XRP by default': async (api, address) => { - api._feeCushion = 1000000 + 'caps fee at 2 XRP by default': async (client, address) => { + 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}', @@ -365,7 +365,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.normal, instructionsWithMaxLedgerVersionOffset @@ -374,10 +374,10 @@ export default { }, 'allows fee exceeding 2 XRP when maxFeeXRP is higher': async ( - api, + client, address ) => { - api._maxFeeXRP = '2.2' + client._maxFeeXRP = '2.2' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, fee: '2.1' @@ -391,7 +391,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.normal, localInstructions @@ -399,8 +399,8 @@ export default { assertResultMatch(response, expectedResponse, 'prepare') }, - 'fee - default maxFee of 2 XRP': async (api, address) => { - api._feeCushion = 1000000 + 'fee - default maxFee of 2 XRP': async (client, address) => { + 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}', @@ -410,7 +410,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, requests.preparePayment.normal, instructionsWithMaxLedgerVersionOffset @@ -419,11 +419,11 @@ export default { }, 'fee - capped to maxFeeXRP when maxFee exceeds maxFeeXRP': async ( - api, + client, address ) => { - api._feeCushion = 1000000 - api._maxFeeXRP = '3' + client._feeCushion = 1000000 + client._maxFeeXRP = '3' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '4' @@ -437,7 +437,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, requests.preparePayment.normal, localInstructions @@ -445,9 +445,9 @@ export default { assertResultMatch(response, expectedResponse, 'prepare') }, - 'fee - capped to maxFee': async (api, address) => { - api._feeCushion = 1000000 - api._maxFeeXRP = '5' + 'fee - capped to maxFee': async (client, address) => { + client._feeCushion = 1000000 + client._maxFeeXRP = '5' const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '4' @@ -461,7 +461,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, requests.preparePayment.normal, localInstructions @@ -470,10 +470,10 @@ export default { }, 'fee - calculated fee does not use more than 6 decimal places': async ( - api, + client, address ) => { - api.connection.request({ + client.connection.request({ command: 'config', data: {loadFactor: 5407.96875} }) @@ -486,7 +486,7 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, requests.preparePayment.normal, instructionsWithMaxLedgerVersionOffset @@ -495,14 +495,14 @@ export default { }, // Tickets - 'preparePayment with ticketSequence': async (api, address) => { - const version = await api.getLedgerVersion() + 'preparePayment with ticketSequence': async (client, address) => { + const version = await client.getLedgerVersion() const localInstructions = { maxLedgerVersion: version + 100, fee: '0.000012', ticketSequence: 23 } - const response = await api.preparePayment( + const response = await client.preparePayment( address, REQUEST_FIXTURES.allOptions, localInstructions @@ -511,10 +511,10 @@ export default { }, 'throws when both sequence and ticketSequence are set': async ( - api, + client, address ) => { - const version = await api.getLedgerVersion() + const version = await client.getLedgerVersion() const localInstructions = { maxLedgerVersion: version + 100, fee: '0.000012', @@ -522,7 +522,7 @@ export default { sequence: 12 } return assertRejects( - api.preparePayment( + client.preparePayment( address, REQUEST_FIXTURES.allOptions, localInstructions diff --git a/test/api/preparePaymentChannelClaim/index.ts b/test/client/preparePaymentChannelClaim/index.ts similarity index 80% rename from test/api/preparePaymentChannelClaim/index.ts rename to test/client/preparePaymentChannelClaim/index.ts index 86e55d84..0026e7d1 100644 --- a/test/api/preparePaymentChannelClaim/index.ts +++ b/test/client/preparePaymentChannelClaim/index.ts @@ -9,15 +9,15 @@ const {preparePaymentChannelClaim: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'default': async (api, address) => { + 'default': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.preparePaymentChannelClaim( + const response = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.normal, localInstructions @@ -25,12 +25,12 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.normal, 'prepare') }, - 'with renew': async (api, address) => { + 'with renew': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.preparePaymentChannelClaim( + const response = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.renew, localInstructions @@ -38,12 +38,12 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.renew, 'prepare') }, - 'with close': async (api, address) => { + 'with close': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.preparePaymentChannelClaim( + const response = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.close, localInstructions @@ -51,13 +51,13 @@ export default { assertResultMatch(response, RESPONSE_FIXTURES.close, 'prepare') }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const response = await api.preparePaymentChannelClaim( + const response = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.normal, localInstructions @@ -66,11 +66,11 @@ export default { }, 'rejects Promise on preparePaymentChannelClaim with renew and close': async ( - api, + client, address ) => { try { - const prepared = await api.preparePaymentChannelClaim( + const prepared = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.full ) @@ -88,11 +88,11 @@ export default { }, 'rejects Promise on preparePaymentChannelClaim with no signature': async ( - api, + client, address ) => { try { - const prepared = await api.preparePaymentChannelClaim( + const prepared = await client.preparePaymentChannelClaim( address, REQUEST_FIXTURES.noSignature ) diff --git a/test/api/preparePaymentChannelCreate/index.ts b/test/client/preparePaymentChannelCreate/index.ts similarity index 76% rename from test/api/preparePaymentChannelCreate/index.ts rename to test/client/preparePaymentChannelCreate/index.ts index bfea3b05..9ecdd095 100644 --- a/test/api/preparePaymentChannelCreate/index.ts +++ b/test/client/preparePaymentChannelCreate/index.ts @@ -13,15 +13,15 @@ export const config = { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'preparePaymentChannelCreate': async (api, address) => { + 'preparePaymentChannelCreate': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const result = await api.preparePaymentChannelCreate( + const result = await client.preparePaymentChannelCreate( address, requests.preparePaymentChannelCreate.normal, localInstructions @@ -33,8 +33,8 @@ export default { ) }, - 'preparePaymentChannelCreate full': async (api, address) => { - const result = await api.preparePaymentChannelCreate( + 'preparePaymentChannelCreate full': async (client, address) => { + const result = await client.preparePaymentChannelCreate( address, requests.preparePaymentChannelCreate.full ) @@ -45,13 +45,13 @@ export default { ) }, - 'preparePaymentChannelCreate with ticket': async (api, address) => { + 'preparePaymentChannelCreate with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.preparePaymentChannelCreate( + const result = await client.preparePaymentChannelCreate( address, requests.preparePaymentChannelCreate.normal, localInstructions diff --git a/test/api/preparePaymentChannelFund/index.ts b/test/client/preparePaymentChannelFund/index.ts similarity index 74% rename from test/api/preparePaymentChannelFund/index.ts rename to test/client/preparePaymentChannelFund/index.ts index bc678173..5b66155c 100644 --- a/test/api/preparePaymentChannelFund/index.ts +++ b/test/client/preparePaymentChannelFund/index.ts @@ -6,15 +6,15 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'preparePaymentChannelFund': async (api, address) => { + 'preparePaymentChannelFund': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const result = await api.preparePaymentChannelFund( + const result = await client.preparePaymentChannelFund( address, requests.preparePaymentChannelFund.normal, localInstructions @@ -26,8 +26,8 @@ export default { ) }, - 'preparePaymentChannelFund full': async (api, address) => { - const result = await api.preparePaymentChannelFund( + 'preparePaymentChannelFund full': async (client, address) => { + const result = await client.preparePaymentChannelFund( address, requests.preparePaymentChannelFund.full ) @@ -38,13 +38,13 @@ export default { ) }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.preparePaymentChannelFund( + const result = await client.preparePaymentChannelFund( address, requests.preparePaymentChannelFund.normal, localInstructions diff --git a/test/api/prepareSettings/index.ts b/test/client/prepareSettings/index.ts similarity index 73% rename from test/api/prepareSettings/index.ts rename to test/client/prepareSettings/index.ts index 14884303..6299a555 100644 --- a/test/api/prepareSettings/index.ts +++ b/test/client/prepareSettings/index.ts @@ -7,19 +7,19 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'simple test': async (api, address) => { - const response = await api.prepareSettings( + 'simple test': async (client, address) => { + const response = await client.prepareSettings( address, requests.prepareSettings.domain, instructionsWithMaxLedgerVersionOffset ) assertResultMatch(response, responses.prepareSettings.flags, 'prepare') }, - 'no maxLedgerVersion': async (api, address) => { - const response = await api.prepareSettings( + 'no maxLedgerVersion': async (client, address) => { + const response = await client.prepareSettings( address, requests.prepareSettings.domain, { @@ -32,8 +32,8 @@ export default { 'prepare' ) }, - 'no instructions': async (api, address) => { - const response = await api.prepareSettings( + 'no instructions': async (client, address) => { + const response = await client.prepareSettings( address, requests.prepareSettings.domain ) @@ -43,18 +43,18 @@ export default { 'prepare' ) }, - 'regularKey': async (api, address) => { + 'regularKey': async (client, address) => { const regularKey = {regularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD'} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, regularKey, instructionsWithMaxLedgerVersionOffset ) assertResultMatch(response, responses.prepareSettings.regularKey, 'prepare') }, - 'remove regularKey': async (api, address) => { + 'remove regularKey': async (client, address) => { const regularKey = {regularKey: null} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, regularKey, instructionsWithMaxLedgerVersionOffset @@ -65,27 +65,27 @@ export default { 'prepare' ) }, - 'flag set': async (api, address) => { + 'flag set': async (client, address) => { const settings = {requireDestinationTag: true} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset ) assertResultMatch(response, responses.prepareSettings.flagSet, 'prepare') }, - 'flag clear': async (api, address) => { + 'flag clear': async (client, address) => { const settings = {requireDestinationTag: false} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset ) assertResultMatch(response, responses.prepareSettings.flagClear, 'prepare') }, - 'set depositAuth flag': async (api, address) => { + 'set depositAuth flag': async (client, address) => { const settings = {depositAuth: true} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset @@ -96,9 +96,9 @@ export default { 'prepare' ) }, - 'clear depositAuth flag': async (api, address) => { + 'clear depositAuth flag': async (client, address) => { const settings = {depositAuth: false} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset @@ -109,9 +109,9 @@ export default { 'prepare' ) }, - 'integer field clear': async (api, address) => { + 'integer field clear': async (client, address) => { const settings = {transferRate: null} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset @@ -119,9 +119,9 @@ export default { assert(response) assert.strictEqual(JSON.parse(response.txJSON).TransferRate, 0) }, - 'set transferRate': async (api, address) => { + 'set transferRate': async (client, address) => { const settings = {transferRate: 1} - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset @@ -132,19 +132,19 @@ export default { 'prepare' ) }, - 'set signers': async (api, address) => { + 'set signers': async (client, address) => { const settings = requests.prepareSettings.signers.normal - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset ) assertResultMatch(response, responses.prepareSettings.signers, 'prepare') }, - 'signers no threshold': async (api, address) => { + 'signers no threshold': async (client, address) => { const settings = requests.prepareSettings.signers.noThreshold try { - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, instructionsWithMaxLedgerVersionOffset @@ -161,25 +161,25 @@ export default { assert.strictEqual(err.name, 'ValidationError') } }, - 'signers no weights': async (api, address) => { + 'signers no weights': async (client, address) => { const settings = requests.prepareSettings.signers.noWeights const localInstructions = { signersCount: 1, ...instructionsWithMaxLedgerVersionOffset } - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, localInstructions ) assertResultMatch(response, responses.prepareSettings.noWeights, 'prepare') }, - 'fee for multisign': async (api, address) => { + 'fee for multisign': async (client, address) => { const localInstructions = { signersCount: 4, ...instructionsWithMaxLedgerVersionOffset } - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, requests.prepareSettings.domain, localInstructions @@ -190,13 +190,13 @@ export default { 'prepare' ) }, - 'no signer list': async (api, address) => { + 'no signer list': async (client, address) => { const settings = requests.prepareSettings.noSignerEntries const localInstructions = { signersCount: 1, ...instructionsWithMaxLedgerVersionOffset } - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, localInstructions @@ -207,7 +207,7 @@ export default { 'prepare' ) }, - 'invalid': async (api, address) => { + 'invalid': async (client, address) => { // domain must be a string const settings = Object.assign({}, requests.prepareSettings.domain, { domain: 123 @@ -218,7 +218,7 @@ export default { } try { - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, settings, localInstructions @@ -235,8 +235,8 @@ export default { assert.strictEqual(err.name, 'ValidationError') } }, - 'offline': async (api, address) => { - // const api = new RippleAPI() + 'offline': async (client, address) => { + // const client = new Client() const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const settings = requests.prepareSettings.domain @@ -245,20 +245,20 @@ export default { maxLedgerVersion: 8820051, fee: '0.000012' } - const result = await api.prepareSettings(address, settings, instructions) + const result = await client.prepareSettings(address, settings, instructions) assertResultMatch(result, responses.prepareSettings.flags, 'prepare') assert.deepEqual( - api.sign(result.txJSON, secret), + client.sign(result.txJSON, secret), responses.prepareSettings.signed ) }, - 'prepare settings with ticket': async (api, address) => { + 'prepare settings with ticket': async (client, address) => { const instructions = { ticketSequence: 23, maxLedgerVersion: 8820051, fee: '0.000012' } - const response = await api.prepareSettings( + const response = await client.prepareSettings( address, requests.prepareSettings.domain, instructions diff --git a/test/api/prepareTicket/index.ts b/test/client/prepareTicket/index.ts similarity index 78% rename from test/api/prepareTicket/index.ts rename to test/client/prepareTicket/index.ts index cc431bfe..08be638d 100644 --- a/test/api/prepareTicket/index.ts +++ b/test/client/prepareTicket/index.ts @@ -1,12 +1,12 @@ import {assertResultMatch, TestSuite} from '../../utils' // import responses from '../../fixtures/responses' // import requests from '../../fixtures/requests' -// import {ValidationError} from 'ripple-api/common/errors' +// import {ValidationError} from 'xrpl-local/common/errors' // import binary from 'ripple-binary-codec' // import assert from 'assert-diff' -// import {RippleAPI} from 'ripple-api' +// import {Client} from 'xrpl-local' -// const {schemaValidator} = RippleAPI._PRIVATE +// const {schemaValidator} = Client._PRIVATE // const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} // const {preparePayment: REQUEST_FIXTURES} = requests // const {preparePayment: RESPONSE_FIXTURES} = responses @@ -15,11 +15,11 @@ import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { 'creates a ticket successfully with a sequence number': async ( - api, + client, address ) => { const expected = { @@ -31,11 +31,11 @@ export default { fee: '0.000012' } } - const response = await api.prepareTicketCreate(address, 2) + const response = await client.prepareTicketCreate(address, 2) assertResultMatch(response, expected, 'prepare') }, - 'creates a ticket successfully with another ticket': async (api, address) => { + 'creates a ticket successfully with another ticket': async (client, address) => { const expected = { txJSON: '{"TransactionType":"TicketCreate", "TicketCount": 1, "Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Flags":2147483648,"LastLedgerSequence":8819954,"Sequence": 0,"TicketSequence":23,"Fee":"12"}', @@ -50,7 +50,7 @@ export default { ticketSequence: 23, fee: '0.000012' } - const response = await api.prepareTicketCreate(address, 1, instructions) + const response = await client.prepareTicketCreate(address, 1, instructions) assertResultMatch(response, expected, 'prepare') } } diff --git a/test/api/prepareTransaction/index.ts b/test/client/prepareTransaction/index.ts similarity index 83% rename from test/api/prepareTransaction/index.ts rename to test/client/prepareTransaction/index.ts index 146a76a6..56368a66 100644 --- a/test/api/prepareTransaction/index.ts +++ b/test/client/prepareTransaction/index.ts @@ -1,4 +1,4 @@ -import {RippledError, ValidationError} from 'ripple-api/common/errors' +import {RippledError, ValidationError} from 'xrpl-local/common/errors' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' import {assertRejects, assertResultMatch, TestSuite} from '../../utils' @@ -14,11 +14,11 @@ export const config = { /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { 'auto-fillable fields - does not overwrite Fee in txJSON': async ( - api, + client, address ) => { const localInstructions = instructionsWithMaxLedgerVersionOffset @@ -28,7 +28,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Fee: '10' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"10","Sequence":23}`, instructions: { @@ -40,7 +40,7 @@ export default { return assertResultMatch(response, expected, 'prepare') }, - 'does not overwrite Fee in Instructions': async (api, address) => { + 'does not overwrite Fee in Instructions': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, fee: '0.000014' // CAUTION: This `fee` is specified in XRP, not drops. @@ -50,7 +50,7 @@ export default { Account: address, Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"14","Sequence":23}`, instructions: { @@ -63,7 +63,7 @@ export default { }, 'rejects Promise if both are set, even when txJSON.Fee matches instructions.fee': async ( - api, + client, address ) => { const localInstructions = { @@ -77,14 +77,14 @@ export default { Fee: '16' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`Fee` in txJSON and `fee` in `instructions` cannot both be set' ) }, 'rejects Promise if both are set, when txJSON.Fee does not match instructions.fee': async ( - api, + client, address ) => { const localInstructions = { @@ -98,14 +98,14 @@ export default { Fee: '20' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`Fee` in txJSON and `fee` in `instructions` cannot both be set' ) }, 'rejects Promise when the Fee is capitalized in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -118,14 +118,14 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance additionalProperty "Fee" exists in instance when not allowed' ) }, 'rejects Promise when the fee is specified in txJSON': async ( - api, + client, address ) => { const localInstructions = instructionsWithMaxLedgerVersionOffset @@ -136,13 +136,13 @@ export default { fee: '10' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'txJSON additionalProperty "fee" exists in instance when not allowed' ) }, - 'does not overwrite Sequence in txJSON': async (api, address) => { + 'does not overwrite Sequence in txJSON': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -153,7 +153,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Sequence: 100 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":100}`, instructions: { @@ -165,7 +165,7 @@ export default { return assertResultMatch(response, expected, 'prepare') }, - 'does not overwrite Sequence in Instructions': async (api, address) => { + 'does not overwrite Sequence in Instructions': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', @@ -176,7 +176,7 @@ export default { Account: address, Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":100}`, instructions: { @@ -189,7 +189,7 @@ export default { }, 'does not overwrite Sequence when same sequence is provided in both txJSON and Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -203,7 +203,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo', Sequence: 100 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":100}`, instructions: { @@ -216,7 +216,7 @@ export default { }, 'rejects Promise when Sequence in txJSON does not match sequence in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -231,14 +231,14 @@ export default { Sequence: 101 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`Sequence` in txJSON must match `sequence` in `instructions`' ) }, 'rejects Promise when the Sequence is capitalized in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -252,7 +252,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance additionalProperty "Sequence" exists in instance when not allowed' ) @@ -260,7 +260,7 @@ export default { // LastLedgerSequence aka maxLedgerVersion/maxLedgerVersionOffset: - 'does not overwrite LastLedgerSequence in txJSON': async (api, address) => { + 'does not overwrite LastLedgerSequence in txJSON': async (client, address) => { const localInstructions = {} const txJSON = { TransactionType: 'DepositPreauth', @@ -269,7 +269,7 @@ export default { Fee: '10', LastLedgerSequence: 8880000 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8880000,"Fee":"10","Sequence":23}`, instructions: { @@ -282,7 +282,7 @@ export default { }, 'does not overwrite maxLedgerVersion in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -293,7 +293,7 @@ export default { Account: address, Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8890000,"Fee":"12","Sequence":23}`, instructions: { @@ -306,7 +306,7 @@ export default { }, 'does not overwrite maxLedgerVersionOffset in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -318,7 +318,7 @@ export default { Account: address, Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820075,"Fee":"12","Sequence":23}`, instructions: { @@ -331,7 +331,7 @@ export default { }, 'rejects Promise if txJSON.LastLedgerSequence and instructions.maxLedgerVersion both are set': async ( - api, + client, address ) => { const localInstructions = { @@ -345,14 +345,14 @@ export default { LastLedgerSequence: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`LastLedgerSequence` in txJSON and `maxLedgerVersion` in `instructions` cannot both be set' ) }, 'rejects Promise if txJSON.LastLedgerSequence and instructions.maxLedgerVersionOffset both are set': async ( - api, + client, address ) => { const localInstructions = { @@ -367,14 +367,14 @@ export default { LastLedgerSequence: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`LastLedgerSequence` in txJSON and `maxLedgerVersionOffset` in `instructions` cannot both be set' ) }, 'rejects Promise if instructions.maxLedgerVersion and instructions.maxLedgerVersionOffset both are set': async ( - api, + client, address ) => { const localInstructions = { @@ -389,14 +389,14 @@ export default { Fee: '16' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance is of prohibited type [object Object]' ) }, 'rejects Promise if txJSON.LastLedgerSequence and instructions.maxLedgerVersion and instructions.maxLedgerVersionOffset all are set': async ( - api, + client, address ) => { const localInstructions = { @@ -412,14 +412,14 @@ export default { LastLedgerSequence: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance is of prohibited type [object Object]' ) }, 'rejects Promise when the maxLedgerVersion is capitalized in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -432,14 +432,14 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance additionalProperty "MaxLedgerVersion" exists in instance when not allowed' ) }, 'rejects Promise when the maxLedgerVersion is specified in txJSON': async ( - api, + client, address ) => { const localInstructions = instructionsWithMaxLedgerVersionOffset @@ -450,14 +450,14 @@ export default { maxLedgerVersion: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'txJSON additionalProperty "maxLedgerVersion" exists in instance when not allowed' ) }, 'rejects Promise when the maxLedgerVersionOffset is specified in txJSON': async ( - api, + client, address ) => { const localInstructions = instructionsWithMaxLedgerVersionOffset @@ -468,14 +468,14 @@ export default { maxLedgerVersionOffset: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'txJSON additionalProperty "maxLedgerVersionOffset" exists in instance when not allowed' ) }, 'rejects Promise when the sequence is specified in txJSON': async ( - api, + client, address ) => { const localInstructions = instructionsWithMaxLedgerVersionOffset @@ -486,7 +486,7 @@ export default { sequence: 8900000 } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'txJSON additionalProperty "sequence" exists in instance when not allowed' ) @@ -497,7 +497,7 @@ export default { // Other errors: 'rejects Promise when an unrecognized field is in Instructions': async ( - api, + client, address ) => { const localInstructions = { @@ -511,13 +511,13 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance additionalProperty "foo" exists in instance when not allowed' ) }, - 'rejects Promise when Account is missing': async (api, address) => { + 'rejects Promise when Account is missing': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -528,13 +528,13 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance requires property "Account"' ) }, - 'rejects Promise when Account is not a string': async (api, address) => { + 'rejects Promise when Account is not a string': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -546,13 +546,13 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance.Account is not of a type(s) string,instance.Account is not exactly one from ,' ) }, - 'rejects Promise when Account is invalid': async (api, address) => { + 'rejects Promise when Account is invalid': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -563,14 +563,14 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance.Account is not exactly one from ,' ) }, 'rejects Promise when Account is valid but non-existent on the ledger': async ( - api + client ) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, @@ -582,13 +582,13 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), RippledError, 'Account not found.' ) }, - 'rejects Promise when TransactionType is missing': async (api, address) => { + 'rejects Promise when TransactionType is missing': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -599,7 +599,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance requires property "TransactionType"' ) @@ -610,7 +610,7 @@ export default { // Error: DepositPreXXXX is not a valid name or ordinal for TransactionType // // at Function.from (ripple-binary-codec/distrib/npm/enums/index.js:43:15) - 'prepares tx when TransactionType is invalid': async (api, address) => { + 'prepares tx when TransactionType is invalid': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -620,7 +620,7 @@ export default { TransactionType: 'DepositPreXXXX', Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreXXXX","Account":"${address}","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { @@ -633,7 +633,7 @@ export default { }, 'rejects Promise when TransactionType is not a string': async ( - api, + client, address ) => { const localInstructions = { @@ -647,7 +647,7 @@ export default { Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance.TransactionType is not of a type(s) string' ) @@ -673,7 +673,7 @@ export default { // '304402201F0EF6A2DE7F96966F7082294D14F3EC1EF59C21E29443E5858A0120079357A302203CDB7FEBDEAAD93FF39CB589B55778CB80DC3979F96F27E828D5E659BEB26B7A', // hash: // 'C181D470684311658852713DA81F8201062535C8DE2FF853F7DD9981BB85312F' } })] - 'prepares tx when a required field is missing': async (api, address) => { + 'prepares tx when a required field is missing': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -683,7 +683,7 @@ export default { TransactionType: 'DepositPreauth' // Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' // Normally required, intentionally removed } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: `{"TransactionType":"DepositPreauth","Account":"${address}","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}`, instructions: { @@ -695,7 +695,7 @@ export default { return assertResultMatch(response, expected, 'prepare') }, - 'DepositPreauth - Authorize': async (api, address) => { + 'DepositPreauth - Authorize': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -716,11 +716,11 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) return assertResultMatch(response, expected, 'prepare') }, - 'DepositPreauth - Unauthorize': async (api, address) => { + 'DepositPreauth - Unauthorize': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -732,7 +732,7 @@ export default { Unauthorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: '{"TransactionType":"DepositPreauth","Account":"' + @@ -747,7 +747,7 @@ export default { return assertResultMatch(response, expected, 'prepare') }, - 'AccountDelete': async (api, address) => { + 'AccountDelete': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '5.0' // 5 XRP fee for AccountDelete @@ -759,7 +759,7 @@ export default { Destination: 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) const expected = { txJSON: '{"TransactionType":"AccountDelete","Account":"' + @@ -775,7 +775,7 @@ export default { }, // prepareTransaction - Payment - 'Payment - normal': async (api, address) => { + 'Payment - normal': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -798,11 +798,11 @@ export default { Flags: 0 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, responses.preparePayment.normal, 'prepare') }, - 'min amount xrp': async (api, address) => { + 'min amount xrp': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -823,10 +823,10 @@ export default { value: '0.01' }, DeliverMin: '10000', - Flags: api.txFlags.Payment.PartialPayment + Flags: client.txFlags.Payment.PartialPayment } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch( response, responses.preparePayment.minAmountXRP, @@ -834,7 +834,7 @@ export default { ) }, - 'min amount xrp2xrp': async (api, address) => { + 'min amount xrp2xrp': async (client, address) => { const txJSON = { TransactionType: 'Payment', Account: address, @@ -842,7 +842,7 @@ export default { Amount: '10000', Flags: 0 } - const response = await api.prepareTransaction( + const response = await client.prepareTransaction( txJSON, instructionsWithMaxLedgerVersionOffset ) @@ -854,8 +854,8 @@ export default { ) }, - 'with all options specified': async (api, address) => { - const ver = await api.getLedgerVersion() + 'with all options specified': async (client, address) => { + const ver = await client.getLedgerVersion() const localInstructions = { maxLedgerVersion: ver + 100, fee: '0.000012' @@ -872,26 +872,26 @@ export default { Memos: [ { Memo: { - MemoType: api.convertStringToHex('test'), - MemoFormat: api.convertStringToHex('text/plain'), - MemoData: api.convertStringToHex('texted data') + MemoType: client.convertStringToHex('test'), + MemoFormat: client.convertStringToHex('text/plain'), + MemoData: client.convertStringToHex('texted data') } } ], Flags: 0 | - api.txFlags.Payment.NoRippleDirect | - api.txFlags.Payment.LimitQuality + client.txFlags.Payment.NoRippleDirect | + client.txFlags.Payment.LimitQuality } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, responses.preparePayment.allOptions, 'prepare') }, 'fee is capped at default maxFee of 2 XRP (using txJSON.LastLedgerSequence)': async ( - api, + client, address ) => { - api._feeCushion = 1000000 + client._feeCushion = 1000000 const txJSON = { Flags: 2147483648, @@ -920,15 +920,15 @@ export default { maxLedgerVersion: 8820051 } } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, expectedResponse, 'prepare') }, 'fee is capped at default maxFee of 2 XRP (using instructions.maxLedgerVersion)': async ( - api, + client, address ) => { - api._feeCushion = 1000000 + client._feeCushion = 1000000 const txJSON = { Flags: 2147483648, @@ -961,17 +961,17 @@ export default { } } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, expectedResponse, 'prepare') }, // prepareTransaction - Payment 'fee is capped to custom maxFeeXRP when maxFee exceeds maxFeeXRP': async ( - api, + client, address ) => { - api._feeCushion = 1000000 - api._maxFeeXRP = '3' + client._feeCushion = 1000000 + client._maxFeeXRP = '3' const localInstructions = { maxFee: '4' // We are testing that this does not matter; fee is still capped to maxFeeXRP } @@ -1004,14 +1004,14 @@ export default { } } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, expectedResponse, 'prepare') }, // prepareTransaction - Payment - 'fee is capped to maxFee': async (api, address) => { - api._feeCushion = 1000000 - api._maxFeeXRP = '5' + 'fee is capped to maxFee': async (client, address) => { + client._feeCushion = 1000000 + client._maxFeeXRP = '5' const localInstructions = { maxFee: '4' // maxFeeXRP does not matter if maxFee is lower than maxFeeXRP } @@ -1044,15 +1044,15 @@ export default { } } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, expectedResponse, 'prepare') }, 'fee - calculated fee does not use more than 6 decimal places': async ( - api, + client, address ) => { - api.connection.request({ + client.connection.request({ command: 'config', data: {loadFactor: 5407.96875} }) @@ -1067,7 +1067,7 @@ export default { } } - const response = await api.preparePayment( + const response = await client.preparePayment( address, requests.preparePayment.normal, instructionsWithMaxLedgerVersionOffset @@ -1076,7 +1076,7 @@ export default { }, - 'xaddress-issuer': async (api, address) => { + 'xaddress-issuer': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -1099,16 +1099,16 @@ export default { Flags: 0 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, responses.preparePayment.normal, 'prepare') }, - 'PaymentChannelCreate': async (api, address) => { + 'PaymentChannelCreate': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' } - const response = await api.prepareTransaction( + const response = await client.prepareTransaction( { Account: address, TransactionType: 'PaymentChannelCreate', @@ -1132,21 +1132,21 @@ export default { ) }, - 'PaymentChannelCreate full': async (api, address) => { + 'PaymentChannelCreate full': async (client, address) => { const txJSON = { Account: address, TransactionType: 'PaymentChannelCreate', - Amount: api.xrpToDrops('1'), // or '1000000' + Amount: client.xrpToDrops('1'), // or '1000000' Destination: 'rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW', SettleDelay: 86400, // Ensure this is in upper case if it is not already PublicKey: '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A'.toUpperCase(), - CancelAfter: api.iso8601ToRippleTime('2017-02-17T15:04:57Z'), + CancelAfter: client.iso8601ToRippleTime('2017-02-17T15:04:57Z'), SourceTag: 11747, DestinationTag: 23480 } - const response = await api.prepareTransaction(txJSON) + const response = await client.prepareTransaction(txJSON) assertResultMatch( response, responses.preparePaymentChannelCreate.full, @@ -1154,7 +1154,7 @@ export default { ) }, - 'PaymentChannelFund': async (api, address) => { + 'PaymentChannelFund': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -1164,9 +1164,9 @@ export default { TransactionType: 'PaymentChannelFund', Channel: 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', - Amount: api.xrpToDrops('1') // or '1000000' + Amount: client.xrpToDrops('1') // or '1000000' } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch( response, responses.preparePaymentChannelFund.normal, @@ -1174,17 +1174,17 @@ export default { ) }, - 'PaymentChannelFund full': async (api, address) => { + 'PaymentChannelFund full': async (client, address) => { const txJSON = { Account: address, TransactionType: 'PaymentChannelFund', Channel: 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', - Amount: api.xrpToDrops('1'), // or '1000000' - Expiration: api.iso8601ToRippleTime('2017-02-17T15:04:57Z') + Amount: client.xrpToDrops('1'), // or '1000000' + Expiration: client.iso8601ToRippleTime('2017-02-17T15:04:57Z') } - const response = await api.prepareTransaction(txJSON) + const response = await client.prepareTransaction(txJSON) assertResultMatch( response, responses.preparePaymentChannelFund.full, @@ -1192,7 +1192,7 @@ export default { ) }, - 'PaymentChannelClaim': async (api, address) => { + 'PaymentChannelClaim': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -1206,7 +1206,7 @@ export default { Flags: 0 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch( response, responses.preparePaymentChannelClaim.normal, @@ -1214,7 +1214,7 @@ export default { ) }, - 'PaymentChannelClaim with renew': async (api, address) => { + 'PaymentChannelClaim with renew': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -1225,17 +1225,17 @@ export default { TransactionType: 'PaymentChannelClaim', Channel: 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', - Balance: api.xrpToDrops('1'), // or '1000000' - Amount: api.xrpToDrops('1'), // or '1000000' + Balance: client.xrpToDrops('1'), // or '1000000' + Amount: client.xrpToDrops('1'), // or '1000000' Signature: '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B', PublicKey: '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', Flags: 0 } - txJSON.Flags |= api.txFlags.PaymentChannelClaim.Renew + txJSON.Flags |= client.txFlags.PaymentChannelClaim.Renew - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch( response, responses.preparePaymentChannelClaim.renew, @@ -1243,7 +1243,7 @@ export default { ) }, - 'PaymentChannelClaim with close': async (api, address) => { + 'PaymentChannelClaim with close': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012' @@ -1254,17 +1254,17 @@ export default { TransactionType: 'PaymentChannelClaim', Channel: 'C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198', - Balance: api.xrpToDrops('1'), // or 1000000 - Amount: api.xrpToDrops('1'), // or 1000000 + Balance: client.xrpToDrops('1'), // or 1000000 + Amount: client.xrpToDrops('1'), // or 1000000 Signature: '30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA3CD7B9B', PublicKey: '32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A', Flags: 0 } - txJSON.Flags |= api.txFlags.PaymentChannelClaim.Close + txJSON.Flags |= client.txFlags.PaymentChannelClaim.Close - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch( response, responses.preparePaymentChannelClaim.close, @@ -1273,7 +1273,7 @@ export default { }, 'rejects Promise if both sequence and ticketSecuence are set': async ( - api, + client, address ) => { const localInstructions = { @@ -1287,13 +1287,13 @@ export default { Fee: '16' } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, 'instance is of prohibited type [object Object]' ) }, - 'sets sequence to 0 if a ticketSequence is passed': async (api, address) => { + 'sets sequence to 0 if a ticketSequence is passed': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', @@ -1317,12 +1317,12 @@ export default { Flags: 0 } - const response = await api.prepareTransaction(txJSON, localInstructions) + const response = await client.prepareTransaction(txJSON, localInstructions) assertResultMatch(response, responses.preparePayment.ticket, 'prepare') }, 'rejects Promise if a sequence with value 0 is passed': async ( - api, + client, address ) => { const localInstructions = { @@ -1349,7 +1349,7 @@ export default { } await assertRejects( - api.prepareTransaction(txJSON, localInstructions), + client.prepareTransaction(txJSON, localInstructions), ValidationError, '`sequence` cannot be 0' ) diff --git a/test/api/prepareTrustline/index.ts b/test/client/prepareTrustline/index.ts similarity index 72% rename from test/api/prepareTrustline/index.ts rename to test/client/prepareTrustline/index.ts index 278b6af1..5b07c434 100644 --- a/test/api/prepareTrustline/index.ts +++ b/test/client/prepareTrustline/index.ts @@ -6,11 +6,11 @@ const instructionsWithMaxLedgerVersionOffset = {maxLedgerVersionOffset: 100} /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'simple': async (api, address) => { - const result = await api.prepareTrustline( + 'simple': async (client, address) => { + const result = await client.prepareTrustline( address, requests.prepareTrustline.simple, instructionsWithMaxLedgerVersionOffset @@ -18,16 +18,16 @@ export default { assertResultMatch(result, responses.prepareTrustline.simple, 'prepare') }, - 'frozen': async (api, address) => { - const result = await api.prepareTrustline( + 'frozen': async (client, address) => { + const result = await client.prepareTrustline( address, requests.prepareTrustline.frozen ) assertResultMatch(result, responses.prepareTrustline.frozen, 'prepare') }, - 'complex': async (api, address) => { - const result = await api.prepareTrustline( + 'complex': async (client, address) => { + const result = await client.prepareTrustline( address, requests.prepareTrustline.complex, instructionsWithMaxLedgerVersionOffset @@ -35,23 +35,23 @@ export default { assertResultMatch(result, responses.prepareTrustline.complex, 'prepare') }, - 'invalid': async (api, address) => { + 'invalid': async (client, address) => { const trustline = Object.assign({}, requests.prepareTrustline.complex) delete trustline.limit // Make invalid await assertRejects( - api.prepareTrustline( + client.prepareTrustline( address, trustline, instructionsWithMaxLedgerVersionOffset ), - api.errors.ValidationError, + client.errors.ValidationError, 'instance.trustline requires property "limit"' ) }, - 'xaddress-issuer': async (api, address) => { - const result = await api.prepareTrustline( + 'xaddress-issuer': async (client, address) => { + const result = await client.prepareTrustline( address, requests.prepareTrustline.issuedXAddress, instructionsWithMaxLedgerVersionOffset @@ -59,13 +59,13 @@ export default { assertResultMatch(result, responses.prepareTrustline.issuedXAddress, 'prepare') }, - 'with ticket': async (api, address) => { + 'with ticket': async (client, address) => { const localInstructions = { ...instructionsWithMaxLedgerVersionOffset, maxFee: '0.000012', ticketSequence: 23 } - const result = await api.prepareTrustline( + const result = await client.prepareTrustline( address, requests.prepareTrustline.simple, localInstructions diff --git a/test/api/request/index.ts b/test/client/request/index.ts similarity index 65% rename from test/api/request/index.ts rename to test/client/request/index.ts index 7a2f22e7..be3f07ce 100644 --- a/test/api/request/index.ts +++ b/test/client/request/index.ts @@ -4,11 +4,11 @@ import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'request account_objects': async (api, address) => { - const result = await api.request('account_objects', { + 'request account_objects': async (client, address) => { + const result = await client.request('account_objects', { account: address }) @@ -19,9 +19,9 @@ export default { ) }, - 'request account_objects - invalid options': async (api, address) => { + 'request account_objects - invalid options': async (client, address) => { // Intentionally no local validation of these options - const result = await api.request('account_objects', { + const result = await client.request('account_objects', { account: address, invalid: 'options' }) diff --git a/test/client/requestNextPage/index.ts b/test/client/requestNextPage/index.ts new file mode 100644 index 00000000..1d4a02aa --- /dev/null +++ b/test/client/requestNextPage/index.ts @@ -0,0 +1,38 @@ +import assert from 'assert-diff' +import {LedgerData} from 'xrpl-local/common/types/objects' +import {assertRejects, TestSuite} from '../../utils' + +/** + * 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. + */ +export default { + 'requests the next page': async (client, address) => { + const response = await client.request('ledger_data') + const responseNextPage = await client.requestNextPage( + 'ledger_data', + {}, + response + ) + assert.equal( + responseNextPage.state[0].index, + '000B714B790C3C79FEE00D17C4DEB436B375466F29679447BA64F265FD63D731' + ) + }, + + 'rejects when there are no more pages': async (client, address) => { + const response = await client.request('ledger_data') + const responseNextPage = await client.requestNextPage( + 'ledger_data', + {}, + response + ) + assert(!client.hasNextPage(responseNextPage)) + await assertRejects( + client.requestNextPage('ledger_data', {}, responseNextPage), + Error, + 'response does not have a next page' + ) + } +} diff --git a/test/api/sign/index.ts b/test/client/sign/index.ts similarity index 84% rename from test/api/sign/index.ts rename to test/client/sign/index.ts index b94a6d01..78bea000 100644 --- a/test/api/sign/index.ts +++ b/test/client/sign/index.ts @@ -1,28 +1,28 @@ import assert from 'assert-diff' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import binary from 'ripple-binary-codec' import requests from '../../fixtures/requests' import responses from '../../fixtures/responses' import {TestSuite} from '../../utils' -const {schemaValidator} = RippleAPI._PRIVATE +const {schemaValidator} = Client._PRIVATE const {sign: REQUEST_FIXTURES} = requests const {sign: RESPONSE_FIXTURES} = responses /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'sign': async (api, address) => { + 'sign': async (client, address) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' - const result = api.sign(REQUEST_FIXTURES.normal.txJSON, secret) + const result = client.sign(REQUEST_FIXTURES.normal.txJSON, secret) assert.deepEqual(result, RESPONSE_FIXTURES.normal) schemaValidator.schemaValidate('sign', result) }, - 'sign with lowercase hex data in memo (hex should be case insensitive)': async (api, address) => { + 'sign with lowercase hex data in memo (hex should be case insensitive)': async (client, address) => { const secret = 'shd2nxpFD6iBRKWsRss2P4tKMWyy9'; const lowercaseMemoTxJson = { "TransactionType" : "Payment", @@ -46,7 +46,7 @@ export default { } const txParams = JSON.stringify(lowercaseMemoTxJson); - const result = api.sign(txParams, secret); + const result = client.sign(txParams, secret); assert.deepEqual(result, { signedTransaction: '120000228000000023000022B8240000000C2E0000270F201B00D5A36761400000000098968068400000000000000C73210305E09ED602D40AB1AF65646A4007C2DAC17CB6CDACDE301E74FB2D728EA057CF744730450221009C00E8439E017CA622A5A1EE7643E26B4DE9C808DE2ABE45D33479D49A4CEC66022062175BE8733442FA2A4D9A35F85A57D58252AE7B19A66401FE238B36FA28E5A081146C1856D0E36019EA75C56D7E8CBA6E35F9B3F71583147FB49CD110A1C46838788CD12764E3B0F837E0DDF9EA7C1F687474703A2F2F6578616D706C652E636F6D2F6D656D6F2F67656E657269637D0472656E74E1F1', id: '41B9CB78D8E18A796CDD4B0BC6FB0EA19F64C4F25FDE23049197852CAB71D10D' @@ -54,7 +54,7 @@ export default { }, 'sign with paths': async ( - api, + client, address ) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' @@ -77,8 +77,8 @@ export default { // eslint-disable-next-line no-useless-escape paths: '[[{\"currency\":\"USD\",\"issuer\":\"rVnYNK9yuxBz4uP8zC8LEFokM2nqH3poc\"}]]' } - const ret = await api.preparePayment(address, payment, {sequence: 1, maxLedgerVersion: 15696358}) - const result = api.sign(ret.txJSON, secret) + const ret = await client.preparePayment(address, payment, {sequence: 1, maxLedgerVersion: 15696358}) + const result = client.sign(ret.txJSON, secret) assert.deepEqual(result, { signedTransaction: '12000022800200002400000001201B00EF81E661EC6386F26FC0FFFF0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461968400000000000000C6940000000000000646AD3504529A0465E2E0000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D1664619732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402200A693FB5CA6B21250EBDFD8CFF526EE0DF7C9E4E31EB0660692E75E6A93BF5F802203CC39463DDA21386898CA31E18AD1A6828647D65741DD637BAD71BC83E29DB9481145E7B112523F68D2F5E879DB4EAC51C6698A693048314CA6EDC7A28252DAEA6F2045B24F4D7C333E146170112300000000000000000000000005553440000000000054F6F784A58F9EFB0A9EB90B83464F9D166461900', id: '78874FE5F5299FEE3EA85D3CF6C1FB1F1D46BB08F716662A3E3D1F0ADE4EF796' @@ -86,70 +86,70 @@ export default { schemaValidator.schemaValidate('sign', result) }, - 'already signed': async (api, address) => { + 'already signed': async (client, address) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' - const result = api.sign(REQUEST_FIXTURES.normal.txJSON, secret) + const result = client.sign(REQUEST_FIXTURES.normal.txJSON, secret) assert.throws(() => { const tx = JSON.stringify(binary.decode(result.signedTransaction)) - api.sign(tx, secret) + client.sign(tx, secret) }, /txJSON must not contain "TxnSignature" or "Signers" properties/) }, - 'EscrowExecution': async (api, address) => { + 'EscrowExecution': async (client, address) => { const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' - const result = api.sign(REQUEST_FIXTURES.escrow.txJSON, secret) + const result = client.sign(REQUEST_FIXTURES.escrow.txJSON, secret) assert.deepEqual(result, RESPONSE_FIXTURES.escrow) schemaValidator.schemaValidate('sign', result) }, - 'signAs': async (api, address) => { + 'signAs': async (client, address) => { const txJSON = REQUEST_FIXTURES.signAs const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' - const signature = api.sign(JSON.stringify(txJSON), secret, { + const signature = client.sign(JSON.stringify(txJSON), secret, { signAs: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' }) assert.deepEqual(signature, RESPONSE_FIXTURES.signAs) }, - 'withKeypair': async (api, address) => { + 'withKeypair': async (client, address) => { const keypair = { privateKey: '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A', publicKey: '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' } - const result = api.sign(REQUEST_FIXTURES.normal.txJSON, keypair) + const result = client.sign(REQUEST_FIXTURES.normal.txJSON, keypair) assert.deepEqual(result, RESPONSE_FIXTURES.normal) schemaValidator.schemaValidate('sign', result) }, - 'withKeypair already signed': async (api, address) => { + 'withKeypair already signed': async (client, address) => { const keypair = { privateKey: '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A', publicKey: '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' } - const result = api.sign(REQUEST_FIXTURES.normal.txJSON, keypair) + const result = client.sign(REQUEST_FIXTURES.normal.txJSON, keypair) assert.throws(() => { const tx = JSON.stringify(binary.decode(result.signedTransaction)) - api.sign(tx, keypair) + client.sign(tx, keypair) }, /txJSON must not contain "TxnSignature" or "Signers" properties/) }, - 'withKeypair EscrowExecution': async (api, address) => { + 'withKeypair EscrowExecution': async (client, address) => { const keypair = { privateKey: '001ACAAEDECE405B2A958212629E16F2EB46B153EEE94CDD350FDEFF52795525B7', publicKey: '0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020' } - const result = api.sign(REQUEST_FIXTURES.escrow.txJSON, keypair) + const result = client.sign(REQUEST_FIXTURES.escrow.txJSON, keypair) assert.deepEqual(result, RESPONSE_FIXTURES.escrow) schemaValidator.schemaValidate('sign', result) }, - 'withKeypair signAs': async (api, address) => { + 'withKeypair signAs': async (client, address) => { const txJSON = REQUEST_FIXTURES.signAs const keypair = { privateKey: @@ -157,14 +157,14 @@ export default { publicKey: '0330E7FC9D56BB25D6893BA3F317AE5BCF33B3291BD63DB32654A313222F7FD020' } - const signature = api.sign(JSON.stringify(txJSON), keypair, { + const signature = client.sign(JSON.stringify(txJSON), keypair, { signAs: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' }) assert.deepEqual(signature, RESPONSE_FIXTURES.signAs) }, - 'succeeds - prepared payment': async (api, address) => { - const payment = await api.preparePayment(address, { + 'succeeds - prepared payment': async (client, address) => { + const payment = await client.preparePayment(address, { source: { address: address, maxAmount: { @@ -181,7 +181,7 @@ export default { } }) const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' - const result = api.sign(payment.txJSON, secret) + const result = client.sign(payment.txJSON, secret) const expectedResult = { signedTransaction: '12000022800000002400000017201B008694F261400000000000000168400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100A9C91D4CFAE45686146EE0B56D4C53A2E7C2D672FB834D43E0BE2D2E9106519A022075DDA2F92DE552B0C45D83D4E6D35889B3FBF51BFBBD9B25EBF70DE3C96D0D6681145E7B112523F68D2F5E879DB4EAC51C6698A693048314FDB08D07AAA0EB711793A3027304D688E10C3648', @@ -191,11 +191,11 @@ export default { schemaValidator.schemaValidate('sign', result) }, - 'succeeds - no flags': async (api, address) => { + 'succeeds - no flags': async (client, address) => { const txJSON = '{"TransactionType":"Payment","Account":"r45Rev1EXGxy2hAUmJPCne97KUE7qyrD3j","Destination":"rQ3PTWGLCbPz8ZCicV5tCX3xuymojTng5r","Amount":"20000000","Sequence":1,"Fee":"12"}' const secret = 'shotKgaEotpcYsshSE39vmSnBDRim' - const result = api.sign(txJSON, secret) + const result = client.sign(txJSON, secret) const expectedResult = { signedTransaction: '1200002400000001614000000001312D0068400000000000000C7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100C104B7B97C31FACA4597E7D6FCF13BD85BD11375963A62A0AC45B0061236E39802207784F157F6A98DFC85B051CDDF61CC3084C4F5750B82674801C8E9950280D1998114EE3046A5DDF8422C40DDB93F1D522BB4FE6419158314FDB08D07AAA0EB711793A3027304D688E10C3648', @@ -211,7 +211,7 @@ export default { }, 'sign succeeds with source.amount/destination.minAmount': async ( - api, + client, address ) => { // See also: 'preparePayment with source.amount/destination.minAmount' @@ -219,7 +219,7 @@ export default { 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 = api.sign(txJSON, secret) + const result = client.sign(txJSON, secret) const expectedResult = { signedTransaction: '12000022800200002400000017201B0086955361EC6386F26FC0FFFF0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A68400000000000000C69D4438D7EA4C6800000000000000000000000000047425000000000000C155FFE99C8C91F67083CEFFDB69EBFE76348CA6AD4446F8C5D8A5E0B0000000000000000000000005553440000000000DC596C88BCDE4E818D416FCDEEBF2C8656BADC9A7321022B05847086686F9D0499B13136B94AD4323EE1B67D4C429ECC987AB35ACFA34574473045022100D9634523D8E232D4A7807A71856023D82AC928FA29848571B820867898413B5F022041AC00EC1F81A26A6504EBF844A38CC3204694EF2CC1A97A87632721631F93DA81145E7B112523F68D2F5E879DB4EAC51C6698A6930483149F500E50C2F016CA01945E5A1E5846B61EF2D376', @@ -235,10 +235,10 @@ export default { }, 'throws when encoded tx does not match decoded tx - prepared payment': async ( - api, + client, address ) => { - const payment = await api.preparePayment(address, { + const payment = await client.preparePayment(address, { source: { address: address, maxAmount: { @@ -256,12 +256,12 @@ export default { }) const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' assert.throws(() => { - api.sign(payment.txJSON, secret) + client.sign(payment.txJSON, secret) }, /^Error: 1\.1234567 is an illegal amount/) }, 'throws when encoded tx does not match decoded tx - prepared order': async ( - api, + client, address ) => { const order = { @@ -276,11 +276,11 @@ export default { value: '31415' } } - const prepared = await api.prepareOrder(address, order, {sequence: 123}) + const prepared = await client.prepareOrder(address, order, {sequence: 123}) const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' try { - api.sign(prepared.txJSON, secret) - return Promise.reject(new Error('api.sign should have thrown')) + client.sign(prepared.txJSON, secret) + return Promise.reject(new Error('client.sign should have thrown')) } catch (error) { assert.equal(error.name, 'ValidationError') assert.equal( @@ -296,7 +296,7 @@ export default { }, 'throws when encoded tx does not match decoded tx - AccountSet': async ( - api, + client, address ) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' @@ -311,12 +311,12 @@ export default { } assert.throws(() => { - api.sign(request.txJSON, secret) + client.sign(request.txJSON, secret) }, /Error: 1\.2 is an illegal amount/) }, 'throws when encoded tx does not match decoded tx - higher fee': async ( - api, + client, address ) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' @@ -331,11 +331,11 @@ export default { } assert.throws(() => { - api.sign(request.txJSON, secret) + client.sign(request.txJSON, secret) }, /Error: 1123456\.7 is an illegal amount/) }, - 'throws when Fee exceeds maxFeeXRP (in drops)': async (api, address) => { + 'throws when Fee exceeds maxFeeXRP (in drops)': async (client, address) => { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"${address}","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"2010000","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, @@ -347,15 +347,15 @@ export default { } assert.throws(() => { - api.sign(request.txJSON, secret) - }, /Fee" should not exceed "2000000"\. To use a higher fee, set `maxFeeXRP` in the RippleAPI constructor\./) + client.sign(request.txJSON, secret) + }, /Fee" should not exceed "2000000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./) }, 'throws when Fee exceeds maxFeeXRP (in drops) - custom maxFeeXRP': async ( - api, + client, address ) => { - api._maxFeeXRP = '1.9' + client._maxFeeXRP = '1.9' const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { txJSON: `{"Flags":2147483648,"TransactionType":"AccountSet","Account":"${address}","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"2010000","Sequence":23,"SigningPubKey":"02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8"}`, @@ -367,15 +367,15 @@ export default { } assert.throws(() => { - api.sign(request.txJSON, secret) - }, /Fee" should not exceed "1900000"\. To use a higher fee, set `maxFeeXRP` in the RippleAPI constructor\./) + client.sign(request.txJSON, secret) + }, /Fee" should not exceed "1900000"\. To use a higher fee, set `maxFeeXRP` in the Client constructor\./) }, 'permits fee exceeding 2000000 drops when maxFeeXRP is higher than 2 XRP': async ( - api, + client, address ) => { - api._maxFeeXRP = '2.1' + client._maxFeeXRP = '2.1' const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const request = { // TODO: This fails when address is X-address @@ -387,7 +387,7 @@ export default { } } - const result = api.sign(request.txJSON, secret) + const result = client.sign(request.txJSON, secret) const expectedResponse = { signedTransaction: @@ -399,9 +399,9 @@ export default { schemaValidator.schemaValidate('sign', result) }, - 'sign with ticket': async (api, address) => { + 'sign with ticket': async (client, address) => { const secret = 'sn7n5R1cR5Y3fRFkuWXA94Ts1frVJ' - const result = api.sign(REQUEST_FIXTURES.ticket.txJSON, secret) + const result = client.sign(REQUEST_FIXTURES.ticket.txJSON, secret) assert.deepEqual(result, RESPONSE_FIXTURES.ticket) schemaValidator.schemaValidate('sign', result) } diff --git a/test/api/signPaymentChannelClaim/index.ts b/test/client/signPaymentChannelClaim/index.ts similarity index 77% rename from test/api/signPaymentChannelClaim/index.ts rename to test/client/signPaymentChannelClaim/index.ts index 55ac004a..b33d2168 100644 --- a/test/api/signPaymentChannelClaim/index.ts +++ b/test/client/signPaymentChannelClaim/index.ts @@ -5,13 +5,13 @@ import responses from '../../fixtures/responses' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - signPaymentChannelClaim: async (api, address) => { + signPaymentChannelClaim: async (client, address) => { const privateKey = 'ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A' - const result = api.signPaymentChannelClaim( + const result = client.signPaymentChannelClaim( requests.signPaymentChannelClaim.channel, requests.signPaymentChannelClaim.amount, privateKey diff --git a/test/api/submit/index.ts b/test/client/submit/index.ts similarity index 56% rename from test/api/submit/index.ts rename to test/client/submit/index.ts index ce7beabb..4be4e8d7 100644 --- a/test/api/submit/index.ts +++ b/test/client/submit/index.ts @@ -4,16 +4,16 @@ import {assertRejects, assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'submit': async (api, address) => { - const result = await api.submit(responses.sign.normal.signedTransaction) + 'submit': async (client, address) => { + const result = await client.submit(responses.sign.normal.signedTransaction) assertResultMatch(result, responses.submit, 'submit') }, - 'submit - failure': async (api, address) => { - await assertRejects(api.submit('BAD'), api.errors.RippledError) + 'submit - failure': async (client, address) => { + await assertRejects(client.submit('BAD'), client.errors.RippledError) // assert.strictEqual(error.data.resultCode, 'temBAD_FEE') } } diff --git a/test/api/verifyPaymentChannelClaim/index.ts b/test/client/verifyPaymentChannelClaim/index.ts similarity index 75% rename from test/api/verifyPaymentChannelClaim/index.ts rename to test/client/verifyPaymentChannelClaim/index.ts index fb6f540d..bad29cdf 100644 --- a/test/api/verifyPaymentChannelClaim/index.ts +++ b/test/client/verifyPaymentChannelClaim/index.ts @@ -5,13 +5,13 @@ import {assertResultMatch, TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'verifyPaymentChannelClaim': async (api, address) => { + 'verifyPaymentChannelClaim': async (client, address) => { const publicKey = '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' - const result = api.verifyPaymentChannelClaim( + const result = client.verifyPaymentChannelClaim( requests.signPaymentChannelClaim.channel, requests.signPaymentChannelClaim.amount, responses.signPaymentChannelClaim, @@ -20,10 +20,10 @@ export default { assertResultMatch(result, true, 'verifyPaymentChannelClaim') }, - 'verifyPaymentChannelClaim - invalid': async (api, address) => { + 'verifyPaymentChannelClaim - invalid': async (client, address) => { const publicKey = '03A6523FE4281DA48A6FD77FAF3CB77F5C7001ABA0B32BCEDE0369AC009758D7D9' - const result = api.verifyPaymentChannelClaim( + const result = client.verifyPaymentChannelClaim( requests.signPaymentChannelClaim.channel, requests.signPaymentChannelClaim.amount, responses.signPaymentChannelClaim, diff --git a/test/api/xrpToDrops/index.ts b/test/client/xrpToDrops/index.ts similarity index 61% rename from test/api/xrpToDrops/index.ts rename to test/client/xrpToDrops/index.ts index 627d2690..65dfa1e6 100644 --- a/test/api/xrpToDrops/index.ts +++ b/test/client/xrpToDrops/index.ts @@ -5,100 +5,100 @@ import {TestSuite} from '../../utils' /** * Every test suite exports their tests in the default object. * - Check out the "TestSuite" type for documentation on the interface. - * - Check out "test/api/index.ts" for more information about the test runner. + * - Check out "test/client/index.ts" for more information about the test runner. */ export default { - 'works with a typical amount': function (api) { - const drops = api.xrpToDrops('2') + 'works with a typical amount': function (client) { + const drops = client.xrpToDrops('2') assert.strictEqual(drops, '2000000', '2 XRP equals 2 million drops') }, - 'works with fractions': function (api) { - let drops = api.xrpToDrops('3.456789') + 'works with fractions': function (client) { + let drops = client.xrpToDrops('3.456789') assert.strictEqual(drops, '3456789', '3.456789 XRP equals 3,456,789 drops') - drops = api.xrpToDrops('3.400000') + drops = client.xrpToDrops('3.400000') assert.strictEqual(drops, '3400000', '3.400000 XRP equals 3,400,000 drops') - drops = api.xrpToDrops('0.000001') + drops = client.xrpToDrops('0.000001') assert.strictEqual(drops, '1', '0.000001 XRP equals 1 drop') - drops = api.xrpToDrops('0.0000010') + drops = client.xrpToDrops('0.0000010') assert.strictEqual(drops, '1', '0.0000010 XRP equals 1 drop') }, - 'works with zero': function (api) { - let drops = api.xrpToDrops('0') + 'works with zero': function (client) { + let drops = client.xrpToDrops('0') assert.strictEqual(drops, '0', '0 XRP equals 0 drops') - drops = api.xrpToDrops('-0') // negative zero is equivalent to zero + drops = client.xrpToDrops('-0') // negative zero is equivalent to zero assert.strictEqual(drops, '0', '-0 XRP equals 0 drops') - drops = api.xrpToDrops('0.000000') + drops = client.xrpToDrops('0.000000') assert.strictEqual(drops, '0', '0.000000 XRP equals 0 drops') - drops = api.xrpToDrops('0.0000000') + drops = client.xrpToDrops('0.0000000') assert.strictEqual(drops, '0', '0.0000000 XRP equals 0 drops') }, - 'works with a negative value': function (api) { - const drops = api.xrpToDrops('-2') + 'works with a negative value': function (client) { + const drops = client.xrpToDrops('-2') assert.strictEqual(drops, '-2000000', '-2 XRP equals -2 million drops') }, - 'works with a value ending with a decimal point': function (api) { - let drops = api.xrpToDrops('2.') + 'works with a value ending with a decimal point': function (client) { + let drops = client.xrpToDrops('2.') assert.strictEqual(drops, '2000000', '2. XRP equals 2000000 drops') - drops = api.xrpToDrops('-2.') + drops = client.xrpToDrops('-2.') assert.strictEqual(drops, '-2000000', '-2. XRP equals -2000000 drops') }, - 'works with BigNumber objects': function (api) { - let drops = api.xrpToDrops(new BigNumber(2)) + 'works with BigNumber objects': function (client) { + let drops = client.xrpToDrops(new BigNumber(2)) assert.strictEqual( drops, '2000000', '(BigNumber) 2 XRP equals 2 million drops' ) - drops = api.xrpToDrops(new BigNumber(-2)) + drops = client.xrpToDrops(new BigNumber(-2)) assert.strictEqual( drops, '-2000000', '(BigNumber) -2 XRP equals -2 million drops' ) }, - 'works with a number': function (api) { + 'works with a number': function (client) { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. - let drops = api.xrpToDrops(2) + let drops = client.xrpToDrops(2) assert.strictEqual( drops, '2000000', '(number) 2 XRP equals 2 million drops' ) - drops = api.xrpToDrops(-2) + drops = client.xrpToDrops(-2) assert.strictEqual( drops, '-2000000', '(number) -2 XRP equals -2 million drops' ) }, - 'throws with an amount with too many decimal places': function (api) { + 'throws with an amount with too many decimal places': function (client) { assert.throws(() => { - api.xrpToDrops('1.1234567') + client.xrpToDrops('1.1234567') }, /has too many decimal places/) assert.throws(() => { - api.xrpToDrops('0.0000001') + client.xrpToDrops('0.0000001') }, /has too many decimal places/) }, - 'throws with an invalid value': function (api) { + 'throws with an invalid value': function (client) { assert.throws(() => { - api.xrpToDrops('FOO') + client.xrpToDrops('FOO') }, /invalid value/) assert.throws(() => { - api.xrpToDrops('1e-7') + client.xrpToDrops('1e-7') }, /invalid value/) assert.throws(() => { - api.xrpToDrops('2,0') + client.xrpToDrops('2,0') }, /invalid value/) assert.throws(() => { - api.xrpToDrops('.') + client.xrpToDrops('.') }, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./) }, - 'throws with an amount more than one decimal point': function (api) { + 'throws with an amount more than one decimal point': function (client) { assert.throws(() => { - api.xrpToDrops('1.0.0') + client.xrpToDrops('1.0.0') }, /xrpToDrops: invalid value '1\.0\.0'/) assert.throws(() => { - api.xrpToDrops('...') + client.xrpToDrops('...') }, /xrpToDrops: invalid value '\.\.\.'/) } } diff --git a/test/connection-test.ts b/test/connection-test.ts index 4d8997b0..ac77b013 100644 --- a/test/connection-test.ts +++ b/test/connection-test.ts @@ -1,11 +1,11 @@ import _ from 'lodash' import net from 'net' import assert from 'assert-diff' -import setupAPI from './setup-api' -import {RippleAPI} from 'ripple-api' +import setupClient from './setup-client' +import {Client} from 'xrpl-local' import ledgerClose from './fixtures/rippled/ledger-close.json' import {ignoreWebSocketDisconnect} from './utils' -const utils = RippleAPI._PRIVATE.ledgerUtils +const utils = Client._PRIVATE.ledgerUtils const TIMEOUT = 200000 // how long before each test case times out const isBrowser = (process as any).browser @@ -25,8 +25,8 @@ function createServer() { describe('Connection', function () { this.timeout(TIMEOUT) - beforeEach(setupAPI.setup) - afterEach(setupAPI.teardown) + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) it('default options', function () { const connection: any = new utils.common.Connection('url') @@ -82,23 +82,23 @@ describe('Connection', function () { }) it('ledger methods work as expected', async function () { - assert.strictEqual(await this.api.connection.getLedgerVersion(), 8819951) + assert.strictEqual(await this.client.connection.getLedgerVersion(), 8819951) assert.strictEqual( - await this.api.connection.hasLedgerVersion(8819951), + await this.client.connection.hasLedgerVersion(8819951), true ) assert.strictEqual( - await this.api.connection.hasLedgerVersions(8819951, undefined), + await this.client.connection.hasLedgerVersions(8819951, undefined), true ) // It would be nice to test a better range, but the mocked ledger only supports this single number assert.strictEqual( - await this.api.connection.hasLedgerVersions(8819951, 8819951), + await this.client.connection.hasLedgerVersions(8819951, 8819951), true ) - assert.strictEqual(await this.api.connection.getFeeBase(), 10) - assert.strictEqual(await this.api.connection.getFeeRef(), 10) - assert.strictEqual(await this.api.connection.getReserveBase(), 20000000) // 20 XRP + assert.strictEqual(await this.client.connection.getFeeBase(), 10) + assert.strictEqual(await this.client.connection.getFeeRef(), 10) + assert.strictEqual(await this.client.connection.getReserveBase(), 20000000) // 20 XRP }) it('with proxy', function (done) { @@ -125,22 +125,22 @@ describe('Connection', function () { trustedCertificates: ['path/to/pem'] } const connection = new utils.common.Connection( - this.api.connection._url, + this.client.connection._url, options ) connection.connect().catch((err) => { - assert(err instanceof this.api.errors.NotConnectedError) + assert(err instanceof this.client.errors.NotConnectedError) }) }, done) }) it('Multiply disconnect calls', function () { - this.api.disconnect() - return this.api.disconnect() + this.client.disconnect() + return this.client.disconnect() }) it('reconnect', function () { - return this.api.connection.reconnect() + return this.client.connection.reconnect() }) it('NotConnectedError', function () { @@ -151,7 +151,7 @@ describe('Connection', function () { assert(false, 'Should throw NotConnectedError') }) .catch((error) => { - assert(error instanceof this.api.errors.NotConnectedError) + assert(error instanceof this.client.errors.NotConnectedError) }) }) @@ -171,76 +171,76 @@ describe('Connection', function () { ) connection.on('error', done) connection.connect().catch((error) => { - assert(error instanceof this.api.errors.NotConnectedError) + assert(error instanceof this.client.errors.NotConnectedError) done() }) }) it('DisconnectedError', async function () { - await this.api.connection.request({ + await this.client.connection.request({ command: 'config', data: {disconnectOnServerInfo: true} }) - return this.api + return this.client .getServerInfo() .then(() => { assert(false, 'Should throw DisconnectedError') }) .catch((error) => { - assert(error instanceof this.api.errors.DisconnectedError) + assert(error instanceof this.client.errors.DisconnectedError) }) }) it('TimeoutError', function () { - this.api.connection._ws.send = function (message, options, callback) { + this.client.connection._ws.send = function (message, options, callback) { callback(null) } const request = {command: 'server_info'} - return this.api.connection + return this.client.connection .request(request, 10) .then(() => { assert(false, 'Should throw TimeoutError') }) .catch((error) => { - assert(error instanceof this.api.errors.TimeoutError) + assert(error instanceof this.client.errors.TimeoutError) }) }) it('DisconnectedError on send', function () { - this.api.connection._ws.send = function (message, options, callback) { + this.client.connection._ws.send = function (message, options, callback) { callback({message: 'not connected'}) } - return this.api + return this.client .getServerInfo() .then(() => { assert(false, 'Should throw DisconnectedError') }) .catch((error) => { - assert(error instanceof this.api.errors.DisconnectedError) + assert(error instanceof this.client.errors.DisconnectedError) assert.strictEqual(error.message, 'not connected') }) }) it('DisconnectedError on initial _onOpen send', async function () { // _onOpen previously could throw PromiseRejectionHandledWarning: Promise rejection was handled asynchronously - // do not rely on the api.setup hook to test this as it bypasses the case, disconnect api connection first - await this.api.disconnect() + // do not rely on the client.setup hook to test this as it bypasses the case, disconnect client connection first + await this.client.disconnect() // stub _onOpen to only run logic relevant to test case - this.api.connection._onOpen = () => { + this.client.connection._onOpen = () => { // overload websocket send on open when _ws exists - this.api.connection._ws.send = function (data, options, cb) { + this.client.connection._ws.send = function (data, options, cb) { // recent ws throws this error instead of calling back throw new Error('WebSocket is not open: readyState 0 (CONNECTING)') } const request = {command: 'subscribe', streams: ['ledger']} - return this.api.connection.request(request) + return this.client.connection.request(request) } try { - await this.api.connect() + await this.client.connect() } catch (error) { - assert(error instanceof this.api.errors.DisconnectedError) + assert(error instanceof this.client.errors.DisconnectedError) assert.strictEqual( error.message, 'WebSocket is not open: readyState 0 (CONNECTING)' @@ -249,22 +249,22 @@ describe('Connection', function () { }) it('ResponseFormatError', function () { - return this.api + return this.client .request('test_command', {data: {unrecognizedResponse: true}}) .then(() => { assert(false, 'Should throw ResponseFormatError') }) .catch((error) => { - assert(error instanceof this.api.errors.ResponseFormatError) + assert(error instanceof this.client.errors.ResponseFormatError) }) }) it('reconnect on unexpected close', function (done) { - this.api.connection.on('connected', () => { + this.client.connection.on('connected', () => { done() }) setTimeout(() => { - this.api.connection._ws.close() + this.client.connection._ws.close() }, 1) }) @@ -281,7 +281,7 @@ describe('Connection', function () { this.timeout(70001) const self = this function breakConnection() { - self.api.connection + self.client.connection .request({ command: 'test_command', data: {disconnectIn: 10} @@ -293,15 +293,15 @@ describe('Connection', function () { let disconnectsCount = 0 let reconnectsCount = 0 let code = 0 - this.api.connection.on('reconnecting', () => { + this.client.connection.on('reconnecting', () => { reconnectsCount += 1 }) - this.api.connection.on('disconnected', (_code) => { + this.client.connection.on('disconnected', (_code) => { code = _code disconnectsCount += 1 }) const num = 3 - this.api.connection.on('connected', () => { + this.client.connection.on('connected', () => { connectsCount += 1 if (connectsCount < num) { breakConnection() @@ -353,13 +353,13 @@ describe('Connection', function () { } } // Set the heartbeat to less than the 1 second ping response - this.api.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) // Hook up a listener for the reconnect event - this.api.connection.on('reconnect', () => done()) + this.client.connection.on('reconnect', () => done()) // Trigger a heartbeat - this.api.connection._heartbeat().catch((error) => { + this.client.connection._heartbeat().catch((error) => { /* ignore - test expects heartbeat failure */ }) }) @@ -374,41 +374,41 @@ describe('Connection', function () { } } // Set the heartbeat to less than the 1 second ping response - this.api.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) // fail on reconnect/connection - this.api.connection.reconnect = async () => { + this.client.connection.reconnect = async () => { throw new Error('error on reconnect') } // Hook up a listener for the reconnect error event - this.api.on('error', (error, message) => { + this.client.on('error', (error, message) => { if (error === 'reconnect' && message === 'error on reconnect') { return done() } return done(new Error('Expected error on reconnect')) }) // Trigger a heartbeat - this.api.connection._heartbeat() + this.client.connection._heartbeat() }) it('should emit disconnected event with code 1000 (CLOSE_NORMAL)', function (done) { - this.api.once('disconnected', (code) => { + this.client.once('disconnected', (code) => { assert.strictEqual(code, 1000) done() }) - this.api.disconnect() + this.client.disconnect() }) it('should emit disconnected event with code 1006 (CLOSE_ABNORMAL)', function (done) { - this.api.connection.once('error', (error) => { + this.client.connection.once('error', (error) => { done(new Error('should not throw error, got ' + String(error))) }) - this.api.connection.once('disconnected', (code) => { + this.client.connection.once('disconnected', (code) => { assert.strictEqual(code, 1006) done() }) - this.api.connection + this.client.connection .request({ command: 'test_command', data: {disconnectIn: 10} @@ -417,18 +417,18 @@ describe('Connection', function () { }) it('should emit connected event on after reconnect', function (done) { - this.api.once('connected', done) - this.api.connection._ws.close() + this.client.once('connected', done) + this.client.connection._ws.close() }) it('Multiply connect calls', function () { - return this.api.connect().then(() => { - return this.api.connect() + return this.client.connect().then(() => { + return this.client.connect() }) }) it('hasLedgerVersion', function () { - return this.api.connection.hasLedgerVersion(8819951).then((result) => { + return this.client.connection.hasLedgerVersion(8819951).then((result) => { assert(result) }) }) @@ -442,7 +442,7 @@ describe('Connection', function () { }) .catch((error) => { assert( - error instanceof this.api.errors.ConnectionError, + error instanceof this.client.errors.ConnectionError, 'Should throw ConnectionError' ) }) @@ -450,48 +450,48 @@ describe('Connection', function () { it('connect multiserver error', function () { assert.throws(function () { - new RippleAPI({ + new Client({ servers: ['wss://server1.com', 'wss://server2.com'] } as any) - }, this.api.errors.RippleError) + }, this.client.errors.RippleError) }) it('connect throws error', function (done) { - this.api.once('error', (type, info) => { + this.client.once('error', (type, info) => { assert.strictEqual(type, 'type') assert.strictEqual(info, 'info') done() }) - this.api.connection.emit('error', 'type', 'info') + this.client.connection.emit('error', 'type', 'info') }) it('emit stream messages', function (done) { let transactionCount = 0 let pathFindCount = 0 - this.api.connection.on('transaction', () => { + this.client.connection.on('transaction', () => { transactionCount++ }) - this.api.connection.on('path_find', () => { + this.client.connection.on('path_find', () => { pathFindCount++ }) - this.api.connection.on('response', (message) => { + this.client.connection.on('response', (message) => { assert.strictEqual(message.id, 1) assert.strictEqual(transactionCount, 1) assert.strictEqual(pathFindCount, 1) done() }) - this.api.connection._onMessage( + this.client.connection._onMessage( JSON.stringify({ type: 'transaction' }) ) - this.api.connection._onMessage( + this.client.connection._onMessage( JSON.stringify({ type: 'path_find' }) ) - this.api.connection._onMessage( + this.client.connection._onMessage( JSON.stringify({ type: 'response', id: 1 @@ -500,13 +500,13 @@ describe('Connection', function () { }) it('invalid message id', function (done) { - this.api.on('error', (errorCode, errorMessage, message) => { + 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.api.connection._onMessage( + this.client.connection._onMessage( JSON.stringify({ type: 'response', id: 'must be integer' @@ -515,13 +515,13 @@ describe('Connection', function () { }) it('propagates error message', function (done) { - this.api.on('error', (errorCode, errorMessage, data) => { + 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.api.connection._onMessage( + this.client.connection._onMessage( JSON.stringify({ error: 'slowDown', error_message: 'slow down' @@ -530,7 +530,7 @@ describe('Connection', function () { }) it('propagates RippledError data', function (done) { - this.api.request('subscribe', {streams: 'validations'}).catch((error) => { + this.client.request('subscribe', {streams: 'validations'}).catch((error) => { assert.strictEqual(error.name, 'RippledError') assert.strictEqual(error.data.error, 'invalidParams') assert.strictEqual(error.message, 'Invalid parameters.') @@ -550,21 +550,21 @@ describe('Connection', function () { it('unrecognized message type', function (done) { // This enables us to automatically support any // new messages added by rippled in the future. - this.api.connection.on('unknown', (event) => { + this.client.connection.on('unknown', (event) => { assert.deepEqual(event, {type: 'unknown'}) done() }) - this.api.connection._onMessage(JSON.stringify({type: 'unknown'})) + this.client.connection._onMessage(JSON.stringify({type: 'unknown'})) }) it('ledger close without validated_ledgers', function (done) { const message = _.omit(ledgerClose, 'validated_ledgers') - this.api.on('ledger', function (ledger) { + this.client.on('ledger', function (ledger) { assert.strictEqual(ledger.ledgerVersion, 8819951) done() }) - this.api.connection._ws.emit('message', JSON.stringify(message)) + this.client.connection._ws.emit('message', JSON.stringify(message)) }) it( @@ -573,19 +573,19 @@ describe('Connection', function () { async function () { this.timeout(3000) - await this.api.connection.request({ + await this.client.connection.request({ command: 'global_config', data: {returnEmptySubscribeRequest: 1} }) - const api = new RippleAPI({server: this.api.connection._url}) - return api.connect().then( + const client = new Client({server: this.client.connection._url}) + return client.connect().then( () => { assert(false, 'Must have thrown!') }, (error) => { assert( - error instanceof this.api.errors.RippledNotInitializedError, + error instanceof this.client.errors.RippledNotInitializedError, 'Must throw RippledNotInitializedError, got instead ' + String(error) ) @@ -595,40 +595,40 @@ describe('Connection', function () { ) it('should clean up websocket connection if error after websocket is opened', async function () { - await this.api.disconnect() + await this.client.disconnect() // fail on connection - this.api.connection._subscribeToLedger = async () => { + this.client.connection._subscribeToLedger = async () => { throw new Error('error on _subscribeToLedger') } try { - await this.api.connect() + await this.client.connect() throw new Error('expected connect() to reject, but it resolved') } catch (err) { assert(err.message === 'error on _subscribeToLedger') // _ws.close event listener should have cleaned up the socket when disconnect _ws.close is run on connection error // do not fail on connection anymore - this.api.connection._subscribeToLedger = async () => {} - await this.api.connection.reconnect() + this.client.connection._subscribeToLedger = async () => {} + await this.client.connection.reconnect() } }) it('should try to reconnect on empty subscribe response on reconnect', function (done) { this.timeout(23000) - this.api.on('error', (error) => { + this.client.on('error', (error) => { done(error || new Error('Should not emit error.')) }) let disconnectedCount = 0 - this.api.on('connected', () => { + this.client.on('connected', () => { done( disconnectedCount !== 1 ? new Error('Wrong number of disconnects') : undefined ) }) - this.api.on('disconnected', () => { + this.client.on('disconnected', () => { disconnectedCount++ }) - this.api.connection.request({ + this.client.connection.request({ command: 'test_command', data: {disconnectIn: 5} }) diff --git a/test/integration/integration-test.ts b/test/integration/integration-test.ts index c4c9ee91..e794213a 100644 --- a/test/integration/integration-test.ts +++ b/test/integration/integration-test.ts @@ -2,11 +2,11 @@ import _ from 'lodash' import assert from 'assert' import wallet from './wallet' import requests from '../fixtures/requests' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import {isValidClassicAddress} from 'ripple-address-codec' import {payTo, ledgerAccept} from './utils' -import {errors} from 'ripple-api/common' -import {isValidSecret} from 'ripple-api/common/utils' +import {errors} from 'xrpl-local/common' +import {isValidSecret} from 'xrpl-local/common/utils' // how long before each test case times out const TIMEOUT = 20000 @@ -18,13 +18,13 @@ const serverUrl = `ws://${HOST}:${PORT}` console.log(serverUrl) -function acceptLedger(api) { - return api.connection.request({command: 'ledger_accept'}) +function acceptLedger(client) { + return client.connection.request({command: 'ledger_accept'}) } function verifyTransaction(testcase, hash, type, options, txData, address) { console.log('VERIFY...') - return testcase.api + return testcase.client .getTransaction(hash, options) .then((data) => { assert(data && data.outcome) @@ -71,13 +71,13 @@ function testTransaction( assert(txJSON, 'missing txJSON') const txData = JSON.parse(txJSON) assert.strictEqual(txData.Account, address) - const signedData = testcase.api.sign(txJSON, secret) + const signedData = testcase.client.sign(txJSON, secret) console.log('PREPARED...') - return testcase.api + return testcase.client .submit(signedData.signedTransaction) .then((data) => testcase.test.title.indexOf('multisign') !== -1 - ? acceptLedger(testcase.api).then(() => data) + ? acceptLedger(testcase.client).then(() => data) : data ) .then((data) => { @@ -87,7 +87,7 @@ function testTransaction( minLedgerVersion: lastClosedLedgerVersion, maxLedgerVersion: txData.LastLedgerSequence } - ledgerAccept(testcase.api) + ledgerAccept(testcase.client) return new Promise((resolve, reject) => { setTimeout( () => @@ -106,9 +106,9 @@ function testTransaction( } function setup(this: any, server = serverUrl) { - this.api = new RippleAPI({server}) + this.client = new Client({server}) console.log('CONNECTING...') - return this.api.connect().then( + return this.client.connect().then( () => { console.log('CONNECTED...') }, @@ -123,48 +123,48 @@ const masterAccount = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' const masterSecret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb' function makeTrustLine(testcase, address, secret) { - const api = testcase.api + const client = testcase.client const specification = { currency: 'USD', counterparty: masterAccount, limit: '1341.1', ripplingDisabled: true } - const trust = api + const trust = client .prepareTrustline(address, specification, {}) .then((data) => { - const signed = api.sign(data.txJSON, secret) + const signed = client.sign(data.txJSON, secret) if (address === wallet.getAddress()) { testcase.transactions.push(signed.id) } - return api.submit(signed.signedTransaction) + return client.submit(signed.signedTransaction) }) - .then(() => ledgerAccept(api)) + .then(() => ledgerAccept(client)) return trust } -function makeOrder(api, address, specification, secret) { - return api +function makeOrder(client, address, specification, secret) { + return client .prepareOrder(address, specification) - .then((data) => api.sign(data.txJSON, secret)) - .then((signed) => api.submit(signed.signedTransaction)) - .then(() => ledgerAccept(api)) + .then((data) => client.sign(data.txJSON, secret)) + .then((signed) => client.submit(signed.signedTransaction)) + .then(() => ledgerAccept(client)) } function setupAccounts(testcase) { - const api = testcase.api + const client = testcase.client - const promise = payTo(api, 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM') - .then(() => payTo(api, wallet.getAddress())) - .then(() => payTo(api, testcase.newWallet.address)) - .then(() => payTo(api, 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc')) - .then(() => payTo(api, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) + const promise = payTo(client, 'rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM') + .then(() => payTo(client, wallet.getAddress())) + .then(() => payTo(client, testcase.newWallet.address)) + .then(() => payTo(client, 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc')) + .then(() => payTo(client, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { - return api + return client .prepareSettings(masterAccount, {defaultRipple: true}) - .then((data) => api.sign(data.txJSON, masterSecret)) - .then((signed) => api.submit(signed.signedTransaction)) - .then(() => ledgerAccept(api)) + .then((data) => client.sign(data.txJSON, masterSecret)) + .then((signed) => client.submit(signed.signedTransaction)) + .then(() => ledgerAccept(client)) }) .then(() => makeTrustLine(testcase, wallet.getAddress(), wallet.getSecret()) @@ -176,8 +176,8 @@ function setupAccounts(testcase) { testcase.newWallet.secret ) ) - .then(() => payTo(api, wallet.getAddress(), '123', 'USD', masterAccount)) - .then(() => payTo(api, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) + .then(() => payTo(client, wallet.getAddress(), '123', 'USD', masterAccount)) + .then(() => payTo(client, 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q')) .then(() => { const orderSpecification = { direction: 'buy', @@ -192,7 +192,7 @@ function setupAccounts(testcase) { } } return makeOrder( - testcase.api, + testcase.client, testcase.newWallet.address, orderSpecification, testcase.newWallet.secret @@ -212,7 +212,7 @@ function setupAccounts(testcase) { } } return makeOrder( - testcase.api, + testcase.client, masterAccount, orderSpecification, masterSecret @@ -222,7 +222,7 @@ function setupAccounts(testcase) { } function teardown(this: any) { - return this.api.disconnect() + return this.client.disconnect() } function suiteSetup(this: any) { @@ -231,12 +231,12 @@ function suiteSetup(this: any) { return ( setup .bind(this)(serverUrl) - .then(() => ledgerAccept(this.api)) - .then(() => (this.newWallet = this.api.generateAddress())) + .then(() => ledgerAccept(this.client)) + .then(() => (this.newWallet = this.client.generateAddress())) // two times to give time to server to send `ledgerClosed` event // so getLedgerVersion will return right value - .then(() => ledgerAccept(this.api)) - .then(() => this.api.getLedgerVersion()) + .then(() => ledgerAccept(this.client)) + .then(() => this.client.getLedgerVersion()) .then((ledgerVersion) => { this.startLedgerVersion = ledgerVersion }) @@ -255,8 +255,8 @@ describe('integration tests', function () { afterEach(teardown) it('settings', function () { - return this.api.getLedgerVersion().then((ledgerVersion) => { - return this.api + return this.client.getLedgerVersion().then((ledgerVersion) => { + return this.client .prepareSettings(address, requests.prepareSettings.domain, instructions) .then((prepared) => testTransaction(this, 'settings', ledgerVersion, prepared) @@ -265,8 +265,8 @@ describe('integration tests', function () { }) it('trustline', function () { - return this.api.getLedgerVersion().then((ledgerVersion) => { - return this.api + return this.client.getLedgerVersion().then((ledgerVersion) => { + return this.client .prepareTrustline( address, requests.prepareTrustline.simple, @@ -290,8 +290,8 @@ describe('integration tests', function () { amount: amount } } - return this.api.getLedgerVersion().then((ledgerVersion) => { - return this.api + return this.client.getLedgerVersion().then((ledgerVersion) => { + return this.client .preparePayment(address, paymentSpecification, instructions) .then((prepared) => testTransaction(this, 'payment', ledgerVersion, prepared) @@ -312,15 +312,15 @@ describe('integration tests', function () { value: '0.0002' } } - return this.api.getLedgerVersion().then((ledgerVersion) => { - return this.api + return this.client.getLedgerVersion().then((ledgerVersion) => { + return this.client .prepareOrder(address, orderSpecification, instructions) .then((prepared) => testTransaction(this, 'order', ledgerVersion, prepared) ) .then((result) => { const txData = JSON.parse(result.txJSON) - return this.api.getOrders(address).then((orders) => { + return this.client.getOrders(address).then((orders) => { assert(orders && orders.length > 0) const createdOrder = ( orders.filter((order) => { @@ -334,7 +334,7 @@ describe('integration tests', function () { }) }) .then((txData) => - this.api + this.client .prepareOrderCancellation( address, {orderSequence: txData.Sequence}, @@ -353,17 +353,17 @@ describe('integration tests', function () { }) it('isConnected', function () { - assert(this.api.isConnected()) + assert(this.client.isConnected()) }) it('getServerInfo', function () { - return this.api.getServerInfo().then((data) => { + return this.client.getServerInfo().then((data) => { assert(data && data.pubkeyNode) }) }) it('getFee', function () { - return this.api.getFee().then((fee) => { + return this.client.getFee().then((fee) => { assert.strictEqual(typeof fee, 'string') assert(!isNaN(Number(fee))) assert(parseFloat(fee) === Number(fee)) @@ -371,7 +371,7 @@ describe('integration tests', function () { }) it('getLedgerVersion', function () { - return this.api.getLedgerVersion().then((ledgerVersion) => { + return this.client.getLedgerVersion().then((ledgerVersion) => { assert.strictEqual(typeof ledgerVersion, 'number') assert(ledgerVersion >= this.startLedgerVersion) }) @@ -382,7 +382,7 @@ describe('integration tests', function () { initiated: true, minLedgerVersion: this.startLedgerVersion } - return this.api + return this.client .getTransactions(address, options) .then((transactionsData) => { assert(transactionsData) @@ -394,7 +394,7 @@ describe('integration tests', function () { const fixture = requests.prepareTrustline.simple const { currency, counterparty } = fixture const options = { currency, counterparty } - return this.api.getTrustlines(address, options).then((data) => { + 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)) @@ -407,7 +407,7 @@ describe('integration tests', function () { const fixture = requests.prepareTrustline.simple const { currency, counterparty } = fixture const options = { currency, counterparty } - return this.api.getBalances(address, options).then((data) => { + 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) @@ -415,7 +415,7 @@ describe('integration tests', function () { }) it('getSettings', function () { - return this.api.getSettings(address).then((data) => { + return this.client.getSettings(address).then((data) => { assert(data) assert.strictEqual(data.domain, requests.prepareSettings.domain.domain) }) @@ -431,7 +431,7 @@ describe('integration tests', function () { counterparty: masterAccount } } - return this.api.getOrderbook(address, orderbook).then((book) => { + 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] @@ -463,7 +463,7 @@ describe('integration tests', function () { } } } - return this.api.getPaths(pathfind).then((data) => { + return this.client.getPaths(pathfind).then((data) => { assert(data && data.length > 0) const path = data[0] assert(path && path.source) @@ -489,7 +489,7 @@ describe('integration tests', function () { } } - return this.api.getPaths(pathfind).then((data) => { + return this.client.getPaths(pathfind).then((data) => { assert(data && data.length > 0) assert( data.every((path) => { @@ -507,7 +507,7 @@ describe('integration tests', function () { }) it('generateWallet', function () { - const newWallet = this.api.generateAddress() + const newWallet = this.client.generateAddress() assert(newWallet && newWallet.address && newWallet.secret) assert(isValidClassicAddress(newWallet.address)) assert(isValidSecret(newWallet.secret)) @@ -536,11 +536,11 @@ describe('integration tests - standalone rippled', function () { ] } let minLedgerVersion = null - return payTo(this.api, address) + return payTo(this.client, address) .then(() => { - return this.api.getLedgerVersion().then((ledgerVersion) => { + return this.client.getLedgerVersion().then((ledgerVersion) => { minLedgerVersion = ledgerVersion - return this.api + return this.client .prepareSettings(address, {signers}, instructions) .then((prepared) => { return testTransaction( @@ -558,26 +558,26 @@ describe('integration tests - standalone rippled', function () { const multisignInstructions = Object.assign({}, instructions, { signersCount: 2 }) - return this.api + return this.client .prepareSettings( address, {domain: 'example.com'}, multisignInstructions ) .then((prepared) => { - const signed1 = this.api.sign(prepared.txJSON, signer1secret, { + const signed1 = this.client.sign(prepared.txJSON, signer1secret, { signAs: signer1address }) - const signed2 = this.api.sign(prepared.txJSON, signer2secret, { + const signed2 = this.client.sign(prepared.txJSON, signer2secret, { signAs: signer2address }) - const combined = this.api.combine([ + const combined = this.client.combine([ signed1.signedTransaction, signed2.signedTransaction ]) - return this.api + return this.client .submit(combined.signedTransaction) - .then((response) => acceptLedger(this.api).then(() => response)) + .then((response) => acceptLedger(this.client).then(() => response)) .then((response) => { assert.strictEqual(response.resultCode, 'tesSUCCESS') const options = {minLedgerVersion} diff --git a/test/integration/utils.js b/test/integration/utils.js index da8ceccd..3bda5fc4 100644 --- a/test/integration/utils.js +++ b/test/integration/utils.js @@ -3,12 +3,12 @@ const masterAccount = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'; const masterSecret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb'; -function ledgerAccept(api) { +function ledgerAccept(client) { const request = {command: 'ledger_accept'}; - return api.connection.request(request); + return client.connection.request(request); } -function pay(api, from, to, amount, secret, currency = 'XRP', counterparty) { +function pay(client, from, to, amount, secret, currency = 'XRP', counterparty) { const paymentSpecification = { source: { address: from, @@ -32,19 +32,19 @@ function pay(api, from, to, amount, secret, currency = 'XRP', counterparty) { } let id = null; - return api.preparePayment(from, paymentSpecification, {}) - .then(data => api.sign(data.txJSON, secret)) + return client.preparePayment(from, paymentSpecification, {}) + .then(data => client.sign(data.txJSON, secret)) .then(signed => { id = signed.id; - return api.submit(signed.signedTransaction); + return client.submit(signed.signedTransaction); }) - .then(() => ledgerAccept(api)) + .then(() => ledgerAccept(client)) .then(() => id); } -function payTo(api, to, amount = '4003218', currency = 'XRP', counterparty) { - return pay(api, masterAccount, to, amount, masterSecret, currency, +function payTo(client, to, amount = '4003218', currency = 'XRP', counterparty) { + return pay(client, masterAccount, to, amount, masterSecret, currency, counterparty); } diff --git a/test/localrunner.html b/test/localrunner.html index 7f66774f..c0bb8252 100644 --- a/test/localrunner.html +++ b/test/localrunner.html @@ -18,9 +18,9 @@ mocha.ui('bdd') - + - + diff --git a/test/localrunnermin.html b/test/localrunnermin.html index 0d72c5b1..9551d77d 100644 --- a/test/localrunnermin.html +++ b/test/localrunnermin.html @@ -18,9 +18,9 @@ mocha.ui('bdd') - + - + diff --git a/test/models/baseTransaction.ts b/test/models/baseTransaction.ts index c8ceb7bd..2fae7e62 100644 --- a/test/models/baseTransaction.ts +++ b/test/models/baseTransaction.ts @@ -1,4 +1,4 @@ -import { ValidationError } from 'ripple-api/common/errors' +import { ValidationError } from 'xrpl-local/common/errors' import { verifyBaseTransaction } from './../../src/models/transactions/common' import { assert } from 'chai' diff --git a/test/models/checkCancel.ts b/test/models/checkCancel.ts index 6989c0a0..7e3768a1 100644 --- a/test/models/checkCancel.ts +++ b/test/models/checkCancel.ts @@ -1,4 +1,4 @@ -import { ValidationError } from 'ripple-api/common/errors' +import { ValidationError } from 'xrpl-local/common/errors' import { verifyCheckCancel} from './../../src/models/transactions/checkCancel' import { assert } from 'chai' diff --git a/test/models/checkCash.ts b/test/models/checkCash.ts index 3eed17e6..a51dcb1d 100644 --- a/test/models/checkCash.ts +++ b/test/models/checkCash.ts @@ -1,4 +1,4 @@ -import { ValidationError } from 'ripple-api/common/errors' +import { ValidationError } from 'xrpl-local/common/errors' import { verifyCheckCash } from './../../src/models/transactions/checkCash' import { assert } from 'chai' diff --git a/test/models/checkCreate.ts b/test/models/checkCreate.ts index ee7dbad0..d0e04fae 100644 --- a/test/models/checkCreate.ts +++ b/test/models/checkCreate.ts @@ -1,4 +1,4 @@ -import { ValidationError } from 'ripple-api/common/errors' +import { ValidationError } from 'xrpl-local/common/errors' import { verifyCheckCreate } from './../../src/models/transactions/checkCreate' import { assert } from 'chai' diff --git a/test/models/offerCreate.ts b/test/models/offerCreate.ts index d7dfdc36..c082f37e 100644 --- a/test/models/offerCreate.ts +++ b/test/models/offerCreate.ts @@ -1,4 +1,4 @@ -import { ValidationError } from 'ripple-api/common/errors' +import { ValidationError } from 'xrpl-local/common/errors' import { verifyOfferCreate } from './../../src/models/transactions/offerCreate' import { assert } from 'chai' diff --git a/test/node_modules/ripple-api b/test/node_modules/xrpl-local similarity index 100% rename from test/node_modules/ripple-api rename to test/node_modules/xrpl-local diff --git a/test/rangeset-test.ts b/test/rangeset-test.ts index 0849846e..9df4e9d0 100644 --- a/test/rangeset-test.ts +++ b/test/rangeset-test.ts @@ -1,6 +1,6 @@ import assert from 'assert' -import {RippleAPI} from 'ripple-api' -const RangeSet = RippleAPI._PRIVATE.RangeSet +import {Client} from 'xrpl-local' +const RangeSet = Client._PRIVATE.RangeSet describe('RangeSet', function () { it('addRange()/addValue()', function () { diff --git a/test/ripple-api-test-private.ts b/test/ripple-client-test-private.ts similarity index 77% rename from test/ripple-api-test-private.ts rename to test/ripple-client-test-private.ts index c10f5660..adf28087 100644 --- a/test/ripple-api-test-private.ts +++ b/test/ripple-client-test-private.ts @@ -1,55 +1,55 @@ import assert from 'assert-diff' import _ from 'lodash' -import {RippleAPI} from 'ripple-api' -import {RecursiveData} from 'ripple-api/ledger/utils' +import {Client} from 'xrpl-local' +import {RecursiveData} from 'xrpl-local/ledger/utils' import {assertRejects, assertResultMatch} from './utils' import addresses from './fixtures/addresses.json' import responses from './fixtures/responses' import ledgerClosed from './fixtures/rippled/ledger-close-newer.json' -import setupAPI from './setup-api' +import setupClient from './setup-client' -const {validate, schemaValidator, ledgerUtils} = RippleAPI._PRIVATE +const {validate, schemaValidator, ledgerUtils} = Client._PRIVATE const address = addresses.ACCOUNT assert.options.strict = true // how long before each test case times out const TIMEOUT = 20000 -describe('RippleAPI', function () { +describe('Client', function () { this.timeout(TIMEOUT) - beforeEach(setupAPI.setup) - afterEach(setupAPI.teardown) + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) - it('RippleAPI - implicit server port', function () { - new RippleAPI({server: 'wss://s1.ripple.com'}) + it('Client - implicit server port', function () { + new Client({server: 'wss://s1.ripple.com'}) }) - it('RippleAPI invalid options', function () { + it('Client invalid options', function () { // @ts-ignore - This is intentionally invalid - assert.throws(() => new RippleAPI({invalid: true})) + assert.throws(() => new Client({invalid: true})) }) - it('RippleAPI valid options', function () { - const api = new RippleAPI({server: 'wss://s:1'}) - const privateConnectionUrl = (api.connection as any)._url + it('Client valid options', function () { + const client = new Client({server: 'wss://s:1'}) + const privateConnectionUrl = (client.connection as any)._url assert.deepEqual(privateConnectionUrl, 'wss://s:1') }) - it('RippleAPI invalid server uri', function () { - assert.throws(() => new RippleAPI({server: 'wss//s:1'})) + it('Client invalid server uri', function () { + assert.throws(() => new Client({server: 'wss//s:1'})) }) - xit('RippleAPI connect() times out after 2 seconds', function () { + xit('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. }) it('ledger closed event', function (done) { - this.api.on('ledger', (message) => { + this.client.on('ledger', (message) => { assertResultMatch(message, responses.ledgerEvent, 'ledgerEvent') done() }) - this.api.connection._ws.emit('message', JSON.stringify(ledgerClosed)) + this.client.connection._ws.emit('message', JSON.stringify(ledgerClosed)) }) describe('[private] schema-validator', function () { @@ -65,13 +65,13 @@ describe('RippleAPI', function () { it('invalid', function () { assert.throws(function () { schemaValidator.schemaValidate('hash256', 'invalid') - }, this.api.errors.ValidationError) + }, this.client.errors.ValidationError) }) it('invalid - empty value', function () { assert.throws(function () { schemaValidator.schemaValidate('hash256', '') - }, this.api.errors.ValidationError) + }, this.client.errors.ValidationError) }) it('schema not found error', function () { @@ -88,7 +88,7 @@ describe('RippleAPI', function () { maxLedgerVersion: 10000 } const thunk = _.partial(validate.getTransactions, {address, options}) - assert.throws(thunk, this.api.errors.ValidationError) + assert.throws(thunk, this.client.errors.ValidationError) assert.throws( thunk, /minLedgerVersion must not be greater than maxLedgerVersion/ @@ -104,29 +104,29 @@ describe('RippleAPI', function () { ) assert.throws( _.partial(validateSecret, 'shzjfakiK79YQdMjy4h8cGGfQSV6v'), - this.api.errors.ValidationError + this.client.errors.ValidationError ) assert.throws( _.partial(validateSecret, 1), - this.api.errors.ValidationError + this.client.errors.ValidationError ) assert.throws( _.partial(validateSecret, ''), - this.api.errors.ValidationError + this.client.errors.ValidationError ) assert.throws( _.partial(validateSecret, 's!!!'), - this.api.errors.ValidationError + this.client.errors.ValidationError ) assert.throws( _.partial(validateSecret, 'passphrase'), - this.api.errors.ValidationError + this.client.errors.ValidationError ) // 32 0s is a valid hex repr of seed bytes const hex = new Array(33).join('0') assert.throws( _.partial(validateSecret, hex), - this.api.errors.ValidationError + this.client.errors.ValidationError ) }) }) diff --git a/test/ripple-api-test.ts b/test/ripple-client-test.ts similarity index 71% rename from test/ripple-api-test.ts rename to test/ripple-client-test.ts index f8b12e6e..c0042a66 100644 --- a/test/ripple-api-test.ts +++ b/test/ripple-client-test.ts @@ -1,42 +1,42 @@ -import setupAPI from './setup-api' -import {RippleAPI} from 'ripple-api' +import setupClient from './setup-client' +import {Client} from 'xrpl-local' import addresses from './fixtures/addresses.json' import {getAllPublicMethods, loadTestSuites} from './utils' /** - * RippleAPI Test Runner + * Client Test Runner * - * Background: "test/api-test.ts" had hit 4000+ lines of test code and 300+ + * Background: "test/client-test.ts" had hit 4000+ lines of test code and 300+ * individual tests. Additionally, a new address format was added which * forced us to copy-paste duplicate the test file to test both the old forms * of address. This added a significant maintenance burden. * - * This test runner allows us to split our tests by RippleAPI method, and + * This test runner allows us to split our tests by Client method, and * automatically load, validate, and run them. Each tests accepts arguments to * test with, which allows us to re-run tests across different data * (ex: different address styles). * * Additional benefits: * - Throw errors when we detect the absence of tests. - * - Type the API object under test and catch typing issues (currently untyped). + * - Type the Client object under test and catch typing issues (currently untyped). * - Sets the stage for more cleanup, like moving test-specific fixtures closer to their tests. */ -describe('RippleAPI [Test Runner]', function () { - beforeEach(setupAPI.setup) - afterEach(setupAPI.teardown) +describe('Client [Test Runner]', function () { + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) // Collect all the tests: - const allPublicMethods = getAllPublicMethods(new RippleAPI()) + const allPublicMethods = getAllPublicMethods(new Client()) const allTestSuites = loadTestSuites() // Run all the tests: for (const {name: methodName, tests, config} of allTestSuites) { - describe(`api.${methodName}`, () => { + describe(`client.${methodName}`, () => { // Run each test that does not use an address. for (const [testName, fn] of tests) { if (fn.length === 1) { it(testName, function () { - return fn(this.api, addresses.ACCOUNT) + return fn(this.client, addresses.ACCOUNT) }) } } @@ -45,7 +45,7 @@ describe('RippleAPI [Test Runner]', function () { for (const [testName, fn] of tests) { if (fn.length === 2) { it(testName, function () { - return fn(this.api, addresses.ACCOUNT) + return fn(this.client, addresses.ACCOUNT) }) } } @@ -56,7 +56,7 @@ describe('RippleAPI [Test Runner]', function () { for (const [testName, fn] of tests) { if (fn.length === 2) { it(testName, function () { - return fn(this.api, addresses.ACCOUNT_X) + return fn(this.client, addresses.ACCOUNT_X) }) } } @@ -72,7 +72,7 @@ describe('RippleAPI [Test Runner]', function () { // TODO: Once migration is complete, remove `.skip()` so that missing tests are reported as failures. it.skip(`${methodName} - no test suite found`, () => { throw new Error( - `Test file not found! Create file "test/api/${methodName}/index.ts".` + `Test file not found! Create file "test/client/${methodName}/index.ts".` ) }) } diff --git a/test/setup-api-web.ts b/test/setup-client-web.ts similarity index 62% rename from test/setup-api-web.ts rename to test/setup-client-web.ts index c0bd2a3c..b555c03b 100644 --- a/test/setup-api-web.ts +++ b/test/setup-client-web.ts @@ -1,27 +1,27 @@ -import {RippleAPI, RippleAPIBroadcast} from 'ripple-api' +import {Client, ClientBroadcast} from 'xrpl-local' import ledgerClosed from './fixtures/rippled/ledger-close.json' const port = 34371 const baseUrl = 'ws://testripple.circleci.com:' function setup(this: any, port_ = port) { - const tapi = new RippleAPI({server: baseUrl + port_}) - return tapi + const tclient = new Client({server: baseUrl + port_}) + return tclient .connect() .then(() => { - return tapi.connection.request({ + return tclient.connection.request({ command: 'test_command', data: {openOnOtherPort: true} }) }) .then((got) => { return new Promise((resolve, reject) => { - this.api = new RippleAPI({server: baseUrl + got.port}) - this.api + this.client = new Client({server: baseUrl + got.port}) + this.client .connect() .then(() => { - this.api.once('ledger', () => resolve()) - this.api.connection._ws.emit( + this.client.once('ledger', () => resolve()) + this.client.connection._ws.emit( 'message', JSON.stringify(ledgerClosed) ) @@ -30,19 +30,19 @@ function setup(this: any, port_ = port) { }) }) .then(() => { - return tapi.disconnect() + return tclient.disconnect() }) } function setupBroadcast(this: any) { const servers = [port, port + 1].map((port_) => baseUrl + port_) - this.api = new RippleAPIBroadcast(servers) + this.client = new ClientBroadcast(servers) return new Promise((resolve, reject) => { - this.api + this.client .connect() .then(() => { - this.api.once('ledger', () => resolve()) - this.api._apis[0].connection._ws.emit( + this.client.once('ledger', () => resolve()) + this.client._clients[0].connection._ws.emit( 'message', JSON.stringify(ledgerClosed) ) @@ -52,8 +52,8 @@ function setupBroadcast(this: any) { } function teardown(this: any) { - if (this.api.isConnected()) { - return this.api.disconnect() + if (this.client.isConnected()) { + return this.client.disconnect() } return undefined } diff --git a/test/setup-api.ts b/test/setup-client.ts similarity index 80% rename from test/setup-api.ts rename to test/setup-client.ts index ea9e5fd1..c53b4c99 100644 --- a/test/setup-api.ts +++ b/test/setup-client.ts @@ -1,4 +1,4 @@ -import {RippleAPI, RippleAPIBroadcast} from 'ripple-api' +import {Client, ClientBroadcast} from 'xrpl-local' import ledgerClosed from './fixtures/rippled/ledger-close.json' import {createMockRippled} from './mock-rippled' import {getFreePort} from './utils' @@ -7,12 +7,12 @@ function setupMockRippledConnection(testcase, port) { return new Promise((resolve, reject) => { testcase.mockRippled = createMockRippled(port) testcase._mockedServerPort = port - testcase.api = new RippleAPI({server: 'ws://localhost:' + port}) - testcase.api + testcase.client = new Client({server: 'ws://localhost:' + port}) + testcase.client .connect() .then(() => { - testcase.api.once('ledger', () => resolve()) - testcase.api.connection._ws.emit( + testcase.client.once('ledger', () => resolve()) + testcase.client.connection._ws.emit( 'message', JSON.stringify(ledgerClosed) ) @@ -25,11 +25,11 @@ function setupMockRippledConnectionForBroadcast(testcase, ports) { return new Promise((resolve, reject) => { const servers = ports.map((port) => 'ws://localhost:' + port) testcase.mocks = ports.map((port) => createMockRippled(port)) - testcase.api = new RippleAPIBroadcast(servers) - testcase.api + testcase.client = new ClientBroadcast(servers) + testcase.client .connect() .then(() => { - testcase.api.once('ledger', () => resolve()) + testcase.client.once('ledger', () => resolve()) testcase.mocks[0].socket.send(JSON.stringify(ledgerClosed)) }) .catch(reject) @@ -49,7 +49,7 @@ function setupBroadcast(this: any) { } function teardown(this: any, done) { - this.api + this.client .disconnect() .then(() => { if (this.mockRippled != null) { diff --git a/test/utils.ts b/test/utils.ts index 1d4da715..20a87e28 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -2,17 +2,17 @@ import net from 'net' import _ from 'lodash' import fs from 'fs' import path from 'path' -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import assert from 'assert-diff' -const {schemaValidator} = RippleAPI._PRIVATE +const {schemaValidator} = Client._PRIVATE /** - * The test function. It takes a RippleAPI object and then some other data to + * The test function. It takes a Client object and then some other data to * test (currently: an address). May be called multiple times with different * arguments, to test different types of data. */ export type TestFn = ( - api: RippleAPI, + client: Client, address: string ) => void | PromiseLike @@ -112,17 +112,17 @@ export function getFreePort() { }) } -export function getAllPublicMethods(api: RippleAPI) { +export function getAllPublicMethods(client: Client) { return Array.from( new Set([ - ...Object.getOwnPropertyNames(api), - ...Object.getOwnPropertyNames(RippleAPI.prototype) + ...Object.getOwnPropertyNames(client), + ...Object.getOwnPropertyNames(Client.prototype) ]) ).filter((key) => !key.startsWith('_')) } export function loadTestSuites(): LoadedTestSuite[] { - const allTests = fs.readdirSync(path.join(__dirname, 'api'), { + const allTests = fs.readdirSync(path.join(__dirname, 'client'), { encoding: 'utf8' }) return allTests @@ -130,7 +130,7 @@ export function loadTestSuites(): LoadedTestSuite[] { if (methodName.startsWith('.DS_Store')) { return null } - const testSuite = require(`./api/${methodName}`) + const testSuite = require(`./client/${methodName}`) return { name: methodName, config: testSuite.config || {}, diff --git a/test/wallet-generation-test.ts b/test/wallet-generation-test.ts index dcd5e5af..8024ee29 100644 --- a/test/wallet-generation-test.ts +++ b/test/wallet-generation-test.ts @@ -1,35 +1,35 @@ import assert from 'assert-diff' -import setupAPI from './setup-api' +import setupClient from './setup-client' import {getFaucetUrl, FaucetNetwork} from '../src/wallet/wallet-generation' describe('Get Faucet URL', function () { - beforeEach(setupAPI.setup) - afterEach(setupAPI.teardown) + beforeEach(setupClient.setup) + afterEach(setupClient.teardown) it('returns the Devnet URL', function () { const expectedFaucet = FaucetNetwork.Devnet - this.api.connection._url = FaucetNetwork.Devnet + this.client.connection._url = FaucetNetwork.Devnet - assert.strictEqual(getFaucetUrl(this.api), expectedFaucet) + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) }) it('returns the Testnet URL', function () { const expectedFaucet = FaucetNetwork.Testnet - this.api.connection._url = FaucetNetwork.Testnet + this.client.connection._url = FaucetNetwork.Testnet - assert.strictEqual(getFaucetUrl(this.api), expectedFaucet) + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) }) it('returns the Testnet URL with the XRPL Labs server', function () { const expectedFaucet = FaucetNetwork.Testnet - this.api.connection._url = 'wss://testnet.xrpl-labs.com' + this.client.connection._url = 'wss://testnet.xrpl-labs.com' - assert.strictEqual(getFaucetUrl(this.api), expectedFaucet) + assert.strictEqual(getFaucetUrl(this.client), expectedFaucet) }) it('returns undefined if not a Testnet or Devnet server URL', function () { - // Info: setupAPI.setup creates a connection to 'localhost' - assert.strictEqual(getFaucetUrl(this.api), undefined) + // Info: setupClient.setup creates a connection to 'localhost' + assert.strictEqual(getFaucetUrl(this.client), undefined) }) }) diff --git a/test/wallet/signTransaction/index.ts b/test/wallet/signTransaction/index.ts index 89959bbe..c8fcc0aa 100644 --- a/test/wallet/signTransaction/index.ts +++ b/test/wallet/signTransaction/index.ts @@ -1,8 +1,8 @@ -import {RippleAPI} from 'ripple-api' +import {Client} from 'xrpl-local' import {TestSuite} from '../../utils' import Wallet from '../../../src/Wallet' -const {schemaValidator} = RippleAPI._PRIVATE +const {schemaValidator} = Client._PRIVATE const publicKey = '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' const privateKey = diff --git a/test/wallet/verifyTransaction/index.ts b/test/wallet/verifyTransaction/index.ts index b71f911e..59e886fd 100644 --- a/test/wallet/verifyTransaction/index.ts +++ b/test/wallet/verifyTransaction/index.ts @@ -1,6 +1,6 @@ import assert from 'assert-diff' import {TestSuite} from '../../utils' -import Wallet from 'ripple-api/Wallet' +import Wallet from 'xrpl-local/Wallet' const publicKey = '030E58CDD076E798C84755590AAF6237CA8FAE821070A59F648B517A30DC6F589D' diff --git a/webpack.config.js b/webpack.config.js index 50aefed3..bd067cb6 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -50,7 +50,7 @@ function webpackForTest(testFileName) { cache: true, externals: [{ 'lodash': '_', - 'ripple-api': 'ripple', + 'xrpl-local': 'ripple', 'net': 'null' }], entry: testFileName,