-
Notifications
You must be signed in to change notification settings - Fork 574
Expand file tree
/
Copy pathindex.ts
More file actions
1259 lines (1183 loc) · 41.2 KB
/
Copy pathindex.ts
File metadata and controls
1259 lines (1183 loc) · 41.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable jsdoc/require-jsdoc -- Request has many aliases, but they don't need unique docs */
/* eslint-disable max-lines -- Client is a large file w/ lots of imports/exports */
import { EventEmitter } from 'eventemitter3'
import { XrplDefinitionsBase } from 'ripple-binary-codec'
import {
RippledError,
NotFoundError,
ValidationError,
XrplError,
} from '../errors'
import {
APIVersion,
LedgerIndex,
Balance,
DEFAULT_API_VERSION,
} from '../models/common'
import {
Request,
// account methods
AccountChannelsRequest,
AccountChannelsResponse,
AccountInfoRequest,
AccountLinesRequest,
AccountLinesResponse,
AccountObjectsRequest,
AccountObjectsResponse,
AccountOffersRequest,
AccountOffersResponse,
AccountTxRequest,
AccountTxResponse,
// ledger methods
LedgerDataRequest,
LedgerDataResponse,
TxResponse,
} from '../models/methods'
import type {
RequestResponseMap,
RequestAllResponseMap,
MarkerRequest,
MarkerResponse,
SubmitResponse,
SimulateRequest,
} from '../models/methods'
import type { BookOffer, BookOfferCurrency } from '../models/methods/bookOffers'
import {
SimulateBinaryResponse,
SimulateJsonResponse,
} from '../models/methods/simulate'
import type {
EventTypes,
OnEventToListenerMap,
} from '../models/methods/subscribe'
import type { SubmittableTransaction } from '../models/transactions'
import { convertTxFlagsToNumber } from '../models/utils/flags'
import {
ensureClassicAddress,
submitRequest,
getSignedTx,
getLastLedgerSequence,
waitForFinalTransactionOutcome,
} from '../sugar'
import {
setValidAddresses,
setNextValidSequenceNumber,
setLatestValidatedLedgerSequence,
checkAccountDeleteBlockers,
txNeedsNetworkID,
autofillBatchTxn,
handleDeliverMax,
getTransactionFee,
} from '../sugar/autofill'
import { formatBalances } from '../sugar/balances'
import {
validateOrderbookOptions,
createBookOffersRequest,
requestAllOffers,
reverseRequest,
extractOffers,
combineOrders,
separateBuySellOrders,
sortAndLimitOffers,
} from '../sugar/getOrderbook'
import { dropsToXrp, hashes, isValidClassicAddress } from '../utils'
import { Wallet } from '../Wallet'
import {
type FaucetRequestBody,
FundingOptions,
requestFunding,
} from '../Wallet/fundWallet'
import {
Connection,
ConnectionUserOptions,
INTENTIONAL_DISCONNECT_CODE,
} from './connection'
import {
handlePartialPayment,
handleStreamPartialPayment,
} from './partialPayment'
export interface ClientOptions extends ConnectionUserOptions {
/**
* Multiplication factor to multiply estimated fee by to provide a cushion in case the
* required fee rises during submission of a transaction. Defaults to 1.2.
*
* @category Fee
*/
feeCushion?: number
/**
* Maximum transaction cost to allow, in decimal XRP. Must be a string-encoded
* number. Defaults to '2'.
*
* @category Fee
*/
maxFeeXRP?: string
/**
* Duration to wait for a request to timeout.
*/
timeout?: number
}
// Make sure to update both this and `RequestNextPageReturnMap` at the same time
type RequestNextPageType =
| AccountChannelsRequest
| AccountLinesRequest
| AccountObjectsRequest
| AccountOffersRequest
| AccountTxRequest
| LedgerDataRequest
type RequestNextPageReturnMap<T> = T extends AccountChannelsRequest
? AccountChannelsResponse
: T extends AccountLinesRequest
? AccountLinesResponse
: T extends AccountObjectsRequest
? AccountObjectsResponse
: T extends AccountOffersRequest
? AccountOffersResponse
: T extends AccountTxRequest
? AccountTxResponse
: T extends LedgerDataRequest
? LedgerDataResponse
: never
/**
* Get the response key / property name that contains the listed data for a
* command. This varies from command to command, but we need to know it to
* properly count across many requests.
*
* @param command - The rippled request command.
* @returns The property key corresponding to the command.
*/
function getCollectKeyFromCommand(command: string): string | null {
switch (command) {
case 'account_channels':
return 'channels'
case 'account_lines':
return 'lines'
case 'account_objects':
return 'account_objects'
case 'account_tx':
return 'transactions'
case 'account_offers':
case 'book_offers':
return 'offers'
case 'ledger_data':
return 'state'
default:
return null
}
}
function clamp(value: number, min: number, max: number): number {
if (min > max) {
throw new Error('Illegal clamp bounds')
}
return Math.min(Math.max(value, min), max)
}
const DEFAULT_FEE_CUSHION = 1.2
const DEFAULT_MAX_FEE_XRP = '2'
const MIN_LIMIT = 10
const MAX_LIMIT = 400
const NORMAL_DISCONNECT_CODE = 1000
/**
* Client for interacting with rippled servers.
*
* @category Clients
*/
class Client extends EventEmitter<EventTypes> {
/*
* Underlying connection to rippled.
*/
public readonly connection: Connection
/**
* Factor to multiply estimated fee by to provide a cushion in case the
* required fee rises during submission of a transaction. Defaults to 1.2.
*
* @category Fee
*/
public readonly feeCushion: number
/**
* Maximum transaction cost to allow, in decimal XRP. Must be a string-encoded
* number. Defaults to '2'.
*
* @category Fee
*/
public readonly maxFeeXRP: string
/**
* Network ID of the server this client is connected to
*
*/
public networkID: number | undefined
/**
* Rippled Version used by the server this client is connected to
*
*/
public buildVersion: string | undefined
/**
* Custom rippled types to use instead of the default. Used for sidechains and amendments.
*
*/
public definitions: XrplDefinitionsBase | undefined
/**
* API Version used by the server this client is connected to
*
*/
public apiVersion: APIVersion = DEFAULT_API_VERSION
/**
* Creates a new Client with a websocket connection to a rippled server.
*
* @param server - URL of the server to connect to.
* @param options - Options for client settings.
* @category Constructor
*
* @example
* ```ts
* import { Client } from "xrpl"
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* ```
*/
/* eslint-disable max-lines-per-function -- the constructor requires more lines to implement the logic */
public constructor(server: string, options: ClientOptions = {}) {
super()
if (typeof server !== 'string' || !/wss?(?:\+unix)?:\/\//u.exec(server)) {
throw new ValidationError(
'server URI must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.',
)
}
this.feeCushion = options.feeCushion ?? DEFAULT_FEE_CUSHION
this.maxFeeXRP = options.maxFeeXRP ?? DEFAULT_MAX_FEE_XRP
this.connection = new Connection(server, options)
this.connection.on('error', (errorCode, errorMessage, data) => {
this.emit('error', errorCode, errorMessage, data)
})
this.connection.on('reconnect', () => {
this.connection.on('connected', () => this.emit('connected'))
})
this.connection.on('disconnected', (code: number) => {
let finalCode = code
/*
* 4000: Connection uses a 4000 code internally to indicate a manual disconnect/close
* Since 4000 is a normal disconnect reason, we convert this to the standard exit code 1000
*/
if (finalCode === INTENTIONAL_DISCONNECT_CODE) {
finalCode = NORMAL_DISCONNECT_CODE
}
this.emit('disconnected', finalCode)
})
this.connection.on('ledgerClosed', (ledger) => {
this.emit('ledgerClosed', ledger)
})
this.connection.on('transaction', (tx) => {
// mutates `tx` to add warnings
handleStreamPartialPayment(tx, this.connection.trace)
this.emit('transaction', tx)
})
this.connection.on('validationReceived', (validation) => {
this.emit('validationReceived', validation)
})
this.connection.on('manifestReceived', (manifest) => {
this.emit('manifestReceived', manifest)
})
this.connection.on('peerStatusChange', (status) => {
this.emit('peerStatusChange', status)
})
this.connection.on('consensusPhase', (consensus) => {
this.emit('consensusPhase', consensus)
})
this.connection.on('path_find', (path) => {
this.emit('path_find', path)
})
}
/* eslint-enable max-lines-per-function */
/**
* Get the url that the client is connected to.
*
* @returns The URL of the server this client is connected to.
* @category Network
*/
public get url(): string {
return this.connection.getUrl()
}
/**
* Makes a request to the client with the given command and
* additional request body parameters.
*
* @category Network
* @param req - Request to send to the server.
* @returns The response from the server.
*
* @example
* ```ts
* const response = await client.request({
* command: 'account_info',
* account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
* })
* console.log(response)
* ```
*/
public async request<
R extends Request,
V extends APIVersion = typeof DEFAULT_API_VERSION,
T = RequestResponseMap<R, V>,
>(req: R): Promise<T> {
const request = {
...req,
account:
typeof req.account === 'string'
? ensureClassicAddress(req.account)
: undefined,
api_version: req.api_version ?? this.apiVersion,
}
const response = await this.connection.request<R, T>(request)
// mutates `response` to add warnings
handlePartialPayment(req.command, response)
return response
}
/**
* Requests the next page of data.
*
* @category Network
*
* @param req - Request to send.
* @param resp - Response with the marker to use in the request.
* @returns The response with the next page of data.
*
* @example
* ```ts
* const response = await client.request({
* command: 'account_tx',
* account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
* })
* console.log(response)
* const nextResponse = await client.requestNextPage({
* command: 'account_tx',
* account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
* },
* response)
* console.log(nextResponse)
* ```
*/
public async requestNextPage<
T extends RequestNextPageType,
U extends RequestNextPageReturnMap<T>,
>(req: T, resp: U): Promise<RequestNextPageReturnMap<T>> {
if (!resp.result.marker) {
return Promise.reject(
new NotFoundError('response does not have a next page'),
)
}
const nextPageRequest = { ...req, marker: resp.result.marker }
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Necessary for overloading
return this.request(nextPageRequest) as unknown as U
}
/**
* Event handler for subscription streams.
*
* @category Network
*
* @param eventName - Name of the event. Only forwards streams.
* @param listener - Function to run on event.
* @returns This, because it inherits from EventEmitter.
*
* * @example
* ```ts
* const api = new Client('wss://s.altnet.rippletest.net:51233')
*
* api.on('transaction', (tx: TransactionStream) => {
* console.log("Received Transaction")
* console.log(tx)
* })
*
* await api.connect()
* const response = await api.request({
* command: 'subscribe',
* streams: ['transactions_proposed']
* })
* ```
*/
public on<
T extends EventTypes,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- needs to be any for overload
U extends (...args: any[]) => void = OnEventToListenerMap<T>,
>(eventName: T, listener: U): this {
return super.on(eventName, listener)
}
/**
* Makes multiple paged requests to the client to return a given number of
* resources. Multiple paged requests will be made until the `limit`
* number of resources is reached (if no `limit` is provided, a single request
* will be made).
*
* If the command is unknown, an additional `collect` property is required to
* know which response key contains the array of resources.
*
* NOTE: This command is used by existing methods and is not recommended for
* general use. Instead, use rippled's built-in pagination and make multiple
* requests as needed.
*
* @category Network
*
* @param request - The initial request to send to the server.
* @param collect - (Optional) the param to use to collect the array of resources (only needed if command is unknown).
* @returns The array of all responses.
* @throws ValidationError if there is no collection key (either from a known command or for the unknown command).
*
* @example
* // Request all ledger data pages
* const allResponses = await client.requestAll({ command: 'ledger_data' });
* console.log(allResponses);
*
* @example
* // Request all transaction data pages
* const allResponses = await client.requestAll({ command: 'transaction_data' });
* console.log(allResponses);
*/
public async requestAll<
T extends MarkerRequest,
U = RequestAllResponseMap<T, APIVersion>,
>(request: T, collect?: string): Promise<U[]> {
/*
* The data under collection is keyed based on the command. Fail if command
* not recognized and collection key not provided.
*/
const collectKey = collect ?? getCollectKeyFromCommand(request.command)
if (!collectKey) {
throw new ValidationError(`no collect key for command ${request.command}`)
}
/*
* If limit is not provided, fetches all data over multiple requests.
* NOTE: This may return much more than needed. Set limit when possible.
*/
const countTo: number = request.limit ?? Infinity
let count = 0
let marker: unknown = request.marker
const results: U[] = []
do {
const countRemaining = clamp(countTo - count, MIN_LIMIT, MAX_LIMIT)
const repeatProps = {
...request,
limit: countRemaining,
marker,
}
// eslint-disable-next-line no-await-in-loop -- Necessary for this, it really has to wait
const singleResponse = await this.connection.request(repeatProps)
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true
const singleResult = (singleResponse as MarkerResponse<APIVersion>).result
if (!(collectKey in singleResult)) {
throw new XrplError(`${collectKey} not in result`)
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Should be true
const collectedData = singleResult[collectKey]
marker = singleResult.marker
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Should be true
results.push(singleResponse as U)
// Make sure we handle when no data (not even an empty array) is returned.
if (Array.isArray(collectedData)) {
count += collectedData.length
}
} while (Boolean(marker) && count < countTo)
return results
}
/**
* Get networkID and buildVersion from server_info
*
* @returns void
* @example
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.getServerInfo()
* console.log(client.networkID)
* console.log(client.buildVersion)
* ```
*/
public async getServerInfo(): Promise<void> {
try {
const response = await this.request({
command: 'server_info',
})
this.networkID = response.result.info.network_id ?? undefined
this.buildVersion = response.result.info.build_version
} catch (error) {
// eslint-disable-next-line no-console -- Print the error to console but allows client to be connected.
console.error(error)
}
}
/**
* Tells the Client instance to connect to its rippled server.
*
* @example
*
* Client.connect() establishes a connection between a Client object and the server.
*
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* // do something with the client
* await client.disconnect()
* ```
* If you open a client connection, be sure to close it with `await client.disconnect()`
* before exiting your application.
* @returns A promise that resolves with a void value when a connection is established.
* @category Network
*
* @example
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* // do something with the client
* await client.disconnect()
* ```
*/
public async connect(): Promise<void> {
return this.connection.connect().then(async () => {
await this.getServerInfo()
this.emit('connected')
})
}
/**
* Disconnects the XRPL client from the server and cancels all pending requests and subscriptions. Call when
* you want to disconnect the client from the server, such as when you're finished using the client or when you
* need to switch to a different server.
*
* @example
*
* To use the disconnect() method, you first need to create a new Client object and connect it to a server:
*
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* // do something with the client
* await client.disconnect()
* ```
*
* @returns A promise that resolves with a void value when a connection is destroyed.
* @category Network
*/
public async disconnect(): Promise<void> {
/*
* 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()
}
/**
* Checks if the Client instance is connected to its rippled server.
*
* @returns Whether the client instance is connected.
* @category Network
* @example
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* console.log(client.isConnected())
* // true
* await client.disconnect()
* console.log(client.isConnected())
* // false
* ```
*/
public isConnected(): boolean {
return this.connection.isConnected()
}
/**
* Autofills fields in a transaction. This will set `Sequence`, `Fee`,
* `lastLedgerSequence` according to the current state of the server this Client
* is connected to. It also converts all X-Addresses to classic addresses and
* flags interfaces into numbers.
*
* @category Core
*
* @example
*
* ```ts
* const { Client } = require('xrpl')
*
* const client = new Client('wss://s.altnet.rippletest.net:51233')
*
* async function createAndAutofillTransaction() {
* const transaction = {
* TransactionType: 'Payment',
* Account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
* Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
* Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)
* }
*
* try {
* const autofilledTransaction = await client.autofill(transaction)
* console.log(autofilledTransaction)
* } catch (error) {
* console.error(`Failed to autofill transaction: ${error}`)
* }
* }
*
* createAndAutofillTransaction()
* ```
*
* Autofill helps fill in fields which should be included in a transaction, but can be determined automatically
* such as `LastLedgerSequence` and `Fee`. If you override one of the fields `autofill` changes, your explicit
* values will be used instead. By default, this is done as part of `submit` and `submitAndWait` when you pass
* in an unsigned transaction along with your wallet to be submitted.
*
* @template T
* @param transaction - A {@link SubmittableTransaction} in JSON format
* @param signersCount - The expected number of signers for this transaction.
* Only used for multisigned transactions.
* @returns The autofilled transaction.
* @throws ValidationError If Amount and DeliverMax fields are not identical in a Payment Transaction
*/
public async autofill<T extends SubmittableTransaction>(
transaction: T,
signersCount?: number,
): Promise<T> {
const tx = { ...transaction }
setValidAddresses(tx)
tx.Flags = convertTxFlagsToNumber(tx)
const promises: Array<Promise<void>> = []
tx.NetworkID ??= txNeedsNetworkID(this) ? this.networkID : undefined
if (tx.Sequence == null) {
promises.push(setNextValidSequenceNumber(this, tx))
}
if (tx.Fee == null) {
promises.push(getTransactionFee(this, tx, signersCount))
}
if (tx.LastLedgerSequence == null) {
promises.push(setLatestValidatedLedgerSequence(this, tx))
}
if (tx.TransactionType === 'AccountDelete') {
promises.push(checkAccountDeleteBlockers(this, tx))
}
if (tx.TransactionType === 'Batch') {
promises.push(autofillBatchTxn(this, tx))
}
if (tx.TransactionType === 'Payment' && tx.DeliverMax != null) {
handleDeliverMax(tx)
}
return Promise.all(promises).then(() => tx)
}
/**
* Simulates an unsigned transaction.
* Steps performed on a transaction:
* 1. Autofill.
* 2. Sign & Encode.
* 3. Submit.
*
* @category Core
*
* @param transaction - A transaction to autofill, sign & encode, and submit.
* @param opts - (Optional) Options used to sign and submit a transaction.
* @param opts.binary - If true, return the metadata in a binary encoding.
*
* @returns A promise that contains SimulateResponse.
* @throws RippledError if the simulate request fails.
*/
public async simulate<Binary extends boolean = false>(
transaction: SubmittableTransaction | string,
opts?: {
// If true, return the binary-encoded representation of the results.
binary?: Binary
},
): Promise<
Binary extends true ? SimulateBinaryResponse : SimulateJsonResponse
> {
// send request
const binary = opts?.binary ?? false
const request: SimulateRequest =
typeof transaction === 'string'
? { command: 'simulate', tx_blob: transaction, binary }
: { command: 'simulate', tx_json: transaction, binary }
return this.request(request)
}
/**
* Submits a signed/unsigned transaction.
* Steps performed on a transaction:
* 1. Autofill.
* 2. Sign & Encode.
* 3. Submit.
*
* @category Core
*
* @param transaction - A transaction to autofill, sign & encode, and submit.
* @param opts - (Optional) Options used to sign and submit a transaction.
* @param opts.autofill - If true, autofill a transaction.
* @param opts.failHard - If true, and the transaction fails locally, do not retry or relay the transaction to other servers.
* @param opts.wallet - A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
*
* @returns A promise that contains SubmitResponse.
* @throws RippledError if submit request fails.
*
* @example
* ```ts
* const { Client, Wallet } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* const wallet = Wallet.generate()
* const transaction = {
* TransactionType: 'Payment',
* Account: wallet.classicAddress,
* Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
* Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)
* }
* const submitResponse = await client.submit(transaction, { wallet })
* console.log(submitResponse)
* ```
*/
public async submit(
transaction: SubmittableTransaction | string,
opts?: {
// If true, autofill a transaction.
autofill?: boolean
// If true, and the transaction fails locally, do not retry or relay the transaction to other servers.
failHard?: boolean
// A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
wallet?: Wallet
},
): Promise<SubmitResponse> {
const signedTx = await getSignedTx(this, transaction, {
...opts,
definitions: this.definitions,
})
return submitRequest(this, signedTx, opts?.failHard)
}
/**
* Asynchronously submits a transaction and verifies that it has been included in a
* validated ledger (or has errored/will not be included for some reason).
* See [Reliable Transaction Submission](https://xrpl.org/reliable-transaction-submission.html).
*
* @category Core
*
* @example
*
* ```ts
* const { Client, Wallet } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
*
* async function submitTransaction() {
* const senderWallet = client.fundWallet()
* const recipientWallet = client.fundWallet()
*
* const transaction = {
* TransactionType: 'Payment',
* Account: senderWallet.address,
* Destination: recipientWallet.address,
* Amount: '10'
* }
*
* try {
* await client.submit(signedTransaction, { wallet: senderWallet })
* console.log(result)
* } catch (error) {
* console.error(`Failed to submit transaction: ${error}`)
* }
* }
*
* submitTransaction()
* ```
*
* In this example we submit a payment transaction between two newly created testnet accounts.
*
* Under the hood, `submit` will call `client.autofill` by default, and because we've passed in a `Wallet` it
* Will also sign the transaction for us before submitting the signed transaction binary blob to the ledger.
*
* This is similar to `submit`, which does all of the above, but also waits to see if the transaction has been validated.
* @param transaction - A transaction to autofill, sign & encode, and submit.
* @param opts - (Optional) Options used to sign and submit a transaction.
* @param opts.autofill - If true, autofill a transaction.
* @param opts.failHard - If true, and the transaction fails locally, do not retry or relay the transaction to other servers.
* @param opts.wallet - A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
* @throws Connection errors: If the `Client` object is unable to establish a connection to the specified WebSocket endpoint,
* an error will be thrown.
* @throws Transaction errors: If the submitted transaction is invalid or cannot be included in a validated ledger for any
* reason, the promise returned by `submitAndWait()` will be rejected with an error. This could include issues with insufficient
* balance, invalid transaction fields, or other issues specific to the transaction being submitted.
* @throws Ledger errors: If the ledger being used to submit the transaction is undergoing maintenance or otherwise unavailable,
* an error will be thrown.
* @throws Timeout errors: If the transaction takes longer than the specified timeout period to be included in a validated
* ledger, the promise returned by `submitAndWait()` will be rejected with an error.
* @returns A promise that contains TxResponse, that will return when the transaction has been validated.
*/
public async submitAndWait<
T extends SubmittableTransaction = SubmittableTransaction,
>(
transaction: T | string,
opts?: {
// If true, autofill a transaction.
autofill?: boolean
// If true, and the transaction fails locally, do not retry or relay the transaction to other servers.
failHard?: boolean
// A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
wallet?: Wallet
},
): Promise<TxResponse<T>> {
const signedTx = await getSignedTx(this, transaction, {
...opts,
definitions: this.definitions,
})
const lastLedger = getLastLedgerSequence(signedTx)
if (lastLedger == null) {
throw new ValidationError(
'Transaction must contain a LastLedgerSequence value for reliable submission.',
)
}
const response = await submitRequest(this, signedTx, opts?.failHard)
if (response.result.engine_result.startsWith('tem')) {
throw new XrplError(
`Transaction failed, ${response.result.engine_result}: ${response.result.engine_result_message}`,
)
}
const txHash = hashes.hashSignedTx(signedTx)
return waitForFinalTransactionOutcome(
this,
txHash,
lastLedger,
response.result.engine_result,
)
}
/**
* Deprecated: Use autofill instead, provided for users familiar with v1
*
* @param transaction - A {@link Transaction} in JSON format
* @param signersCount - The expected number of signers for this transaction.
* Only used for multisigned transactions.
* @returns The prepared transaction with required fields autofilled.
* @deprecated Use autofill instead, provided for users familiar with v1
*/
public async prepareTransaction(
transaction: SubmittableTransaction,
signersCount?: number,
): ReturnType<Client['autofill']> {
return this.autofill(transaction, signersCount)
}
/**
* Retrieves the XRP balance of a given account address.
*
* @category Abstraction
*
* @example
* ```ts
* const client = new Client(wss://s.altnet.rippletest.net:51233)
* await client.connect()
* const balance = await client.getXrpBalance('rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn')
* console.log(balance)
* await client.disconnect()
* /// '200'
* ```
*
* @param address - The XRP address to retrieve the balance for.
* @param [options] - Additional options for fetching the balance (optional).
* @param [options.ledger_hash] - The hash of the ledger to retrieve the balance from (optional).
* @param [options.ledger_index] - The index of the ledger to retrieve the balance from (optional).
* @returns A promise that resolves with the XRP balance as a number.
*/
public async getXrpBalance(
address: string,
options: {
ledger_hash?: string
ledger_index?: LedgerIndex
} = {},
): Promise<number> {
const xrpRequest: AccountInfoRequest = {
command: 'account_info',
account: address,
ledger_index: options.ledger_index ?? 'validated',
ledger_hash: options.ledger_hash,
}
const response = await this.request(xrpRequest)
return dropsToXrp(response.result.account_data.Balance)
}
/**
* Get XRP/non-XRP balances for an account.
*
* @category Abstraction
*
* @example
* ```ts
* const { Client } = require('xrpl')
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
*
* async function getAccountBalances(address) {
* try {
* const options = {
* ledger_index: 'validated',
* limit: 10
* };
*
* const balances = await xrplClient.getBalances(address, options);
*
* console.log('Account Balances:');
* balances.forEach((balance) => {
* console.log(`Currency: ${balance.currency}`);
* console.log(`Value: ${balance.value}`);
* console.log(`Issuer: ${balance.issuer}`);
* console.log('---');
* });
* } catch (error) {
* console.error('Error retrieving account balances:', error);
* }
* }
*
* const address = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh';
* await getAccountBalances(address);
* await client.disconnect();
* ```
*
* @param address - Address of the account to retrieve balances for.
* @param options - Allows the client to specify a ledger_hash, ledger_index,
* filter by peer, and/or limit number of balances.
* @param options.ledger_index - Retrieve the account balances at a given
* ledger_index.
* @param options.ledger_hash - Retrieve the account balances at the ledger with
* a given ledger_hash.
* @param options.peer - Filter balances by peer.
* @param options.limit - Limit number of balances to return.
* @returns An array of XRP/non-XRP balances for the given account.
*/
/* eslint-disable max-lines-per-function -- getBalances requires more lines to implement logic */
public async getBalances(
address: string,
options: {
ledger_hash?: string
ledger_index?: LedgerIndex
peer?: string