Edit Client constructor to take a server URI (#1544)

* edit Client

* fix TS issues + tests

* minor edits

* rename ClientBroadcast -> BroadcastClient
This commit is contained in:
Mayukha Vadari
2021-08-20 13:16:15 -04:00
parent d1cfbf42e6
commit e90257be2f
17 changed files with 64 additions and 67 deletions

View File

@@ -1,8 +1,6 @@
import {Client} from '../../dist/npm' import {Client} from '../../dist/npm'
const client = new Client({ const client = new Client('wss://s.altnet.rippletest.net:51233')
server: 'wss://s.altnet.rippletest.net:51233'
})
getTransaction() getTransaction()

View File

@@ -1,6 +1,6 @@
import {Client} from '../../dist/npm' import {Client} from '../../dist/npm'
const client = new Client({server: 'wss://s.altnet.rippletest.net:51233'}) const client = new Client('wss://s.altnet.rippletest.net:51233')
parseAccountFlags() parseAccountFlags()

View File

@@ -1,10 +1,10 @@
import {Client} from '../../dist/npm' import {Client} from '../../dist/npm'
const client = new Client({ const client = new Client(
// server: 'wss://s.altnet.rippletest.net:51233' // 'wss://s.altnet.rippletest.net:51233'
// server: 'ws://35.158.96.209:51233' // 'ws://35.158.96.209:51233'
server: 'ws://34.210.87.206:51233' 'ws://34.210.87.206:51233'
}) )
sign() sign()

View File

@@ -68,7 +68,7 @@ async function reliableTransactionSubmissionExample() {
async function performPayments(payments) { async function performPayments(payments) {
const finalResults = [] const finalResults = []
const txFinalizedPromises = [] const txFinalizedPromises = []
const client = new Client({server: 'wss://s.altnet.rippletest.net:51233'}) const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect() await client.connect()
for (let i = 0; i < payments.length; i++) { for (let i = 0; i < payments.length; i++) {

View File

@@ -1,14 +1,14 @@
import {Client, ClientOptions} from './client' import {Client, ClientOptions} from './'
class ClientBroadcast extends Client { class BroadcastClient extends Client {
ledgerVersion: number | undefined = undefined ledgerVersion: number | undefined = undefined
private _clients: Client[] private _clients: Client[]
constructor(servers, options: ClientOptions = {}) { constructor(servers, options: ClientOptions = {}) {
super(options) super(servers[0], options)
const clients: Client[] = servers.map( const clients: Client[] = servers.map(
(server) => new Client(Object.assign({}, options, {server})) (server) => new Client(server, options)
) )
// exposed for testing // exposed for testing
@@ -69,4 +69,4 @@ class ClientBroadcast extends Client {
} }
} }
export {ClientBroadcast} export {BroadcastClient}

View File

@@ -159,9 +159,9 @@ import {
computePaymentChannelHash computePaymentChannelHash
} from '../common/hashes' } from '../common/hashes'
import generateFaucetWallet from '../wallet/wallet-generation' import generateFaucetWallet from '../wallet/wallet-generation'
import { ValidationError } from '../common/errors'
export interface ClientOptions extends ConnectionUserOptions { export interface ClientOptions extends ConnectionUserOptions {
server?: string
feeCushion?: number feeCushion?: number
maxFeeXRP?: string maxFeeXRP?: string
proxy?: string proxy?: string
@@ -223,37 +223,38 @@ class Client extends EventEmitter {
schemaValidator schemaValidator
} }
constructor(options: ClientOptions = {}) { constructor(server: string, options: ClientOptions = {}) {
super() super()
validate.apiOptions(options) if (typeof server !== 'string' || !server.match("^(wss?|wss?\\+unix)://")) {
throw new ValidationError("server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.")
}
this._feeCushion = options.feeCushion || 1.2 this._feeCushion = options.feeCushion || 1.2
this._maxFeeXRP = options.maxFeeXRP || '2' this._maxFeeXRP = options.maxFeeXRP || '2'
const serverURL = options.server
if (serverURL != null) { this.connection = new Connection(server, options)
this.connection = new Connection(serverURL, options)
this.connection.on('ledgerClosed', (message: LedgerStream) => { this.connection.on('ledgerClosed', (message: LedgerStream) => {
this.emit('ledger', formatLedgerClose(message)) this.emit('ledger', formatLedgerClose(message))
}) })
this.connection.on('error', (errorCode, errorMessage, data) => {
this.emit('error', errorCode, errorMessage, data) this.connection.on('error', (errorCode, errorMessage, data) => {
}) this.emit('error', errorCode, errorMessage, data)
this.connection.on('connected', () => { })
this.emit('connected')
}) this.connection.on('connected', () => {
this.connection.on('disconnected', (code) => { this.emit('connected')
let finalCode = code })
// 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close
// Since 4000 is a normal disconnect reason, we convert this to the standard exit code 1000 this.connection.on('disconnected', (code) => {
if (finalCode === 4000) { let finalCode = code
finalCode = 1000 // 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close
} // Since 4000 is a normal disconnect reason, we convert this to the standard exit code 1000
this.emit('disconnected', finalCode) if (finalCode === 4000) {
}) finalCode = 1000
} else { }
// use null object pattern to provide better error message if user this.emit('disconnected', finalCode)
// tries to call a method that requires a connection })
this.connection = new Connection(null, options)
}
} }
/** /**

View File

@@ -9,6 +9,6 @@ export * from './models/methods'
export * from './offline/utils' export * from './offline/utils'
// Broadcast client is experimental // Broadcast client is experimental
export {ClientBroadcast} from './broadcast' export {BroadcastClient} from './client/broadcast'
export * from './Wallet' export * from './Wallet'

View File

@@ -16,7 +16,7 @@ function checkResult(expected, response) {
return response return response
} }
describe('ClientBroadcast', function () { describe('BroadcastClient', function () {
this.timeout(TIMEOUT) this.timeout(TIMEOUT)
beforeEach(setupClient.setupBroadcast) beforeEach(setupClient.setupBroadcast)
afterEach(setupClient.teardown) afterEach(setupClient.teardown)

View File

@@ -156,7 +156,6 @@ export default <TestSuite>{
}, },
'computeLedgerHash': async (client, address) => { 'computeLedgerHash': async (client, address) => {
// const client = new Client()
const header = REQUEST_FIXTURES.header const header = REQUEST_FIXTURES.header
const ledgerHash = client.computeLedgerHash(header) const ledgerHash = client.computeLedgerHash(header)
assert.strictEqual( assert.strictEqual(
@@ -166,7 +165,6 @@ export default <TestSuite>{
}, },
'computeLedgerHash - with transactions': async (client, address) => { 'computeLedgerHash - with transactions': async (client, address) => {
// const client = new Client()
const header = { const header = {
...REQUEST_FIXTURES.header, ...REQUEST_FIXTURES.header,
transactionHash: undefined, transactionHash: undefined,
@@ -180,7 +178,6 @@ export default <TestSuite>{
}, },
'computeLedgerHash - incorrent transaction_hash': async (client, address) => { 'computeLedgerHash - incorrent transaction_hash': async (client, address) => {
// const client = new Client()
const header = Object.assign({}, REQUEST_FIXTURES.header, { const header = Object.assign({}, REQUEST_FIXTURES.header, {
transactionHash: transactionHash:
'325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9' '325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9'

View File

@@ -9,7 +9,7 @@ import {Client} from 'xrpl-local'
*/ */
export default <TestSuite>{ export default <TestSuite>{
'Client - implicit server port': () => { 'Client - implicit server port': () => {
new Client({server: 'wss://s1.ripple.com'}) new Client('wss://s1.ripple.com')
}, },
'Client invalid options': () => { 'Client invalid options': () => {
@@ -18,12 +18,12 @@ export default <TestSuite>{
}, },
'Client valid options': () => { 'Client valid options': () => {
const client = new Client({server: 'wss://s:1'}) const client = new Client('wss://s:1')
const privateConnectionUrl = (client.connection as any)._url const privateConnectionUrl = (client.connection as any)._url
assert.deepEqual(privateConnectionUrl, 'wss://s:1') assert.deepEqual(privateConnectionUrl, 'wss://s:1')
}, },
'Client invalid server uri': () => { 'Client invalid server uri': () => {
assert.throws(() => new Client({server: 'wss//s:1'})) assert.throws(() => new Client('wss//s:1'))
} }
} }

View File

@@ -236,7 +236,6 @@ export default <TestSuite>{
} }
}, },
'offline': async (client, address) => { 'offline': async (client, address) => {
// const client = new Client()
const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV' const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV'
const settings = requests.prepareSettings.domain const settings = requests.prepareSettings.domain

View File

@@ -578,7 +578,7 @@ describe('Connection', function () {
data: {returnEmptySubscribeRequest: 1} data: {returnEmptySubscribeRequest: 1}
}) })
const client = new Client({server: this.client.connection._url}) const client = new Client(this.client.connection._url)
return client.connect().then( return client.connect().then(
() => { () => {
assert(false, 'Must have thrown!') assert(false, 'Must have thrown!')

View File

@@ -106,7 +106,7 @@ function testTransaction(
} }
function setup(this: any, server = serverUrl) { function setup(this: any, server = serverUrl) {
this.client = new Client({server}) this.client = new Client(server)
console.log('CONNECTING...') console.log('CONNECTING...')
return this.client.connect().then( return this.client.connect().then(
() => { () => {

View File

@@ -21,7 +21,7 @@ describe('Client', function () {
afterEach(setupClient.teardown) afterEach(setupClient.teardown)
it('Client - implicit server port', function () { it('Client - implicit server port', function () {
new Client({server: 'wss://s1.ripple.com'}) new Client('wss://s1.ripple.com')
}) })
it('Client invalid options', function () { it('Client invalid options', function () {
@@ -30,16 +30,16 @@ describe('Client', function () {
}) })
it('Client valid options', function () { it('Client valid options', function () {
const client = new Client({server: 'wss://s:1'}) const client = new Client('wss://s:1')
const privateConnectionUrl = (client.connection as any)._url const privateConnectionUrl = (client.connection as any)._url
assert.deepEqual(privateConnectionUrl, 'wss://s:1') assert.deepEqual(privateConnectionUrl, 'wss://s:1')
}) })
it('Client invalid server uri', function () { it('Client invalid server uri', function () {
assert.throws(() => new Client({server: 'wss//s:1'})) assert.throws(() => new Client('wss//s:1'))
}) })
xit('Client connect() times out after 2 seconds', function () { it('Client connect() times out after 2 seconds', function () {
// TODO: Use a timer mock like https://jestjs.io/docs/en/timer-mocks // TODO: Use a timer mock like https://jestjs.io/docs/en/timer-mocks
// to test that connect() times out after 2 seconds. // to test that connect() times out after 2 seconds.
}) })

View File

@@ -26,7 +26,9 @@ describe('Client [Test Runner]', function () {
afterEach(setupClient.teardown) afterEach(setupClient.teardown)
// Collect all the tests: // Collect all the tests:
const allPublicMethods = getAllPublicMethods(new Client()) const allPublicMethods = getAllPublicMethods(new Client("wss://"))
// doesn't need the client, just needs to instantiate to get public methods
const allTestSuites = loadTestSuites() const allTestSuites = loadTestSuites()
// Run all the tests: // Run all the tests:

View File

@@ -1,11 +1,11 @@
import {Client, ClientBroadcast} from 'xrpl-local' import {Client, BroadcastClient} from 'xrpl-local'
import ledgerClosed from './fixtures/rippled/ledger-close.json' import ledgerClosed from './fixtures/rippled/ledger-close.json'
const port = 34371 const port = 34371
const baseUrl = 'ws://testripple.circleci.com:' const baseUrl = 'ws://testripple.circleci.com:'
function setup(this: any, port_ = port) { function setup(this: any, port_ = port) {
const tclient = new Client({server: baseUrl + port_}) const tclient = new Client(baseUrl + port_)
return tclient return tclient
.connect() .connect()
.then(() => { .then(() => {
@@ -19,7 +19,7 @@ function setup(this: any, port_ = port) {
.then((got) => { .then((got) => {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
// @ts-ignore // @ts-ignore
this.client = new Client({server: baseUrl + got.port}) this.client = new Client(baseUrl + got.port)
this.client this.client
.connect() .connect()
.then(() => { .then(() => {
@@ -39,7 +39,7 @@ function setup(this: any, port_ = port) {
function setupBroadcast(this: any) { function setupBroadcast(this: any) {
const servers = [port, port + 1].map((port_) => baseUrl + port_) const servers = [port, port + 1].map((port_) => baseUrl + port_)
this.client = new ClientBroadcast(servers) this.client = new BroadcastClient(servers)
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
this.client this.client
.connect() .connect()

View File

@@ -1,4 +1,4 @@
import {Client, ClientBroadcast} from 'xrpl-local' import {Client, BroadcastClient} from 'xrpl-local'
import ledgerClosed from './fixtures/rippled/ledger-close.json' import ledgerClosed from './fixtures/rippled/ledger-close.json'
import {createMockRippled} from './mock-rippled' import {createMockRippled} from './mock-rippled'
import {getFreePort} from './utils' import {getFreePort} from './utils'
@@ -7,7 +7,7 @@ function setupMockRippledConnection(testcase, port) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
testcase.mockRippled = createMockRippled(port) testcase.mockRippled = createMockRippled(port)
testcase._mockedServerPort = port testcase._mockedServerPort = port
testcase.client = new Client({server: 'ws://localhost:' + port}) testcase.client = new Client('ws://localhost:' + port)
testcase.client testcase.client
.connect() .connect()
.then(() => { .then(() => {
@@ -25,7 +25,7 @@ function setupMockRippledConnectionForBroadcast(testcase, ports) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
const servers = ports.map((port) => 'ws://localhost:' + port) const servers = ports.map((port) => 'ws://localhost:' + port)
testcase.mocks = ports.map((port) => createMockRippled(port)) testcase.mocks = ports.map((port) => createMockRippled(port))
testcase.client = new ClientBroadcast(servers) testcase.client = new BroadcastClient(servers)
testcase.client testcase.client
.connect() .connect()
.then(() => { .then(() => {