-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
HavenoClient.ts
1474 lines (1362 loc) · 56 KB
/
HavenoClient.ts
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
/*
* Copyright Haveno
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import console from "console";
import HavenoError from "./types/HavenoError";
import HavenoUtils from "./utils/HavenoUtils";
import TaskLooper from "./utils/TaskLooper";
import type * as grpcWeb from "grpc-web";
import { GetTradeStatisticsClient, GetVersionClient, AccountClient, XmrConnectionsClient, DisputesClient, DisputeAgentsClient, NotificationsClient, WalletsClient, PriceClient, OffersClient, PaymentAccountsClient, TradesClient, ShutdownServerClient, XmrNodeClient } from './protobuf/GrpcServiceClientPb';
import { GetTradeStatisticsRequest, GetTradeStatisticsReply, GetVersionRequest, GetVersionReply, IsAppInitializedRequest, IsAppInitializedReply, RegisterDisputeAgentRequest, UnregisterDisputeAgentRequest, MarketPriceRequest, MarketPriceReply, MarketPricesRequest, MarketPricesReply, MarketPriceInfo, MarketDepthRequest, MarketDepthReply, MarketDepthInfo, GetBalancesRequest, GetBalancesReply, XmrBalanceInfo, GetMyOfferRequest, GetMyOfferReply, GetOffersRequest, GetOffersReply, OfferInfo, GetPaymentMethodsRequest, GetPaymentMethodsReply, GetPaymentAccountFormRequest, CreatePaymentAccountRequest, ValidateFormFieldRequest, CreatePaymentAccountReply, GetPaymentAccountFormReply, GetPaymentAccountsRequest, GetPaymentAccountsReply, CreateCryptoCurrencyPaymentAccountRequest, CreateCryptoCurrencyPaymentAccountReply, DeletePaymentAccountRequest, DeletePaymentAccountReply, PostOfferRequest, PostOfferReply, CancelOfferRequest, TakeOfferRequest, TakeOfferReply, TradeInfo, GetTradeRequest, GetTradeReply, GetTradesRequest, GetTradesReply, GetXmrSeedRequest, GetXmrSeedReply, GetXmrPrimaryAddressRequest, GetXmrPrimaryAddressReply, GetXmrNewSubaddressRequest, GetXmrNewSubaddressReply, ConfirmPaymentSentRequest, ConfirmPaymentReceivedRequest, CompleteTradeRequest, XmrTx, GetXmrTxsRequest, GetXmrTxsReply, XmrDestination, CreateXmrTxRequest, CreateXmrTxReply, RelayXmrTxRequest, RelayXmrTxReply, CreateAccountRequest, AccountExistsRequest, AccountExistsReply, DeleteAccountRequest, OpenAccountRequest, IsAccountOpenRequest, IsAccountOpenReply, CloseAccountRequest, ChangePasswordRequest, BackupAccountRequest, BackupAccountReply, RestoreAccountRequest, StopRequest, NotificationMessage, RegisterNotificationListenerRequest, SendNotificationRequest, UrlConnection, AddConnectionRequest, RemoveConnectionRequest, GetConnectionRequest, GetConnectionsRequest, SetConnectionRequest, CheckConnectionRequest, CheckConnectionsReply, CheckConnectionsRequest, StartCheckingConnectionRequest, StopCheckingConnectionRequest, GetBestAvailableConnectionRequest, SetAutoSwitchRequest, GetAutoSwitchRequest, CheckConnectionReply, GetConnectionsReply, GetConnectionReply, GetBestAvailableConnectionReply, GetDisputeRequest, GetDisputeReply, GetDisputesRequest, GetDisputesReply, OpenDisputeRequest, ResolveDisputeRequest, SendDisputeChatMessageRequest, SendChatMessageRequest, GetChatMessagesRequest, GetChatMessagesReply, StartXmrNodeRequest, StopXmrNodeRequest, IsXmrNodeOnlineRequest, IsXmrNodeOnlineReply, GetXmrNodeSettingsRequest, GetXmrNodeSettingsReply } from "./protobuf/grpc_pb";
import { TradeStatistics3, OfferDirection, PaymentMethod, PaymentAccountForm, PaymentAccountFormField, PaymentAccount, PaymentAccountPayload, AvailabilityResult, Attachment, DisputeResult, Dispute, ChatMessage, XmrNodeSettings } from "./protobuf/pb_pb";
/**
* Haveno daemon client.
*/
export default class HavenoClient {
// grpc clients
/** @private */ _appName: string | undefined;
/** @private */ _getTradeStatisticsClient: GetTradeStatisticsClient;
/** @private */ _getVersionClient: GetVersionClient;
/** @private */ _disputeAgentsClient: DisputeAgentsClient;
/** @private */ _disputesClient: DisputesClient;
/** @private */ _notificationsClient: NotificationsClient;
/** @private */ _notificationStream: grpcWeb.ClientReadableStream<NotificationMessage> | undefined;
/** @private */ _xmrConnectionsClient: XmrConnectionsClient;
/** @private */ _xmrNodeClient: XmrNodeClient;
/** @private */ _walletsClient: WalletsClient;
/** @private */ _priceClient: PriceClient;
/** @private */ _paymentAccountsClient: PaymentAccountsClient;
/** @private */ _offersClient: OffersClient;
/** @private */ _tradesClient: TradesClient;
/** @private */ _accountClient: AccountClient;
/** @private */ _shutdownServerClient: ShutdownServerClient;
// state variables
/** @private */ _url: string;
/** @private */ _password: string;
/** @private */ _process: any;
/** @private */ _processLogging = false;
/** @private */ _walletRpcPort: number | undefined;
/** @private */ _notificationListeners: ((_notification: NotificationMessage) => void)[] = [];
/** @private */ _registerNotificationListenerCalled = false;
/** @private */ _keepAliveLooper: any;
/** @private */ _keepAlivePeriodMs = 60000;
/** @private */ _paymentMethods: PaymentMethod[] | undefined; // cached for performance
// constants
/** @private */ static readonly _fullyInitializedMessage = "Application fully initialized";
/** @private */ static readonly _loginRequiredMessage = "Interactive login required";
/**
* Construct a client connected to a Haveno daemon.
*
* @param {string} url - Haveno daemon url
* @param {string} password - Haveno daemon password
*/
constructor(url: string, password: string) {
if (!url) throw new HavenoError("Must provide URL of Haveno daemon");
if (!password) throw new HavenoError("Must provide password of Haveno daemon");
HavenoUtils.log(2, "Creating Haveno client connected to " + url);
this._url = url;
this._password = password;
this._getTradeStatisticsClient = new GetTradeStatisticsClient(this._url);
this._getVersionClient = new GetVersionClient(this._url);
this._accountClient = new AccountClient(this._url);
this._xmrConnectionsClient = new XmrConnectionsClient(this._url);
this._xmrNodeClient = new XmrNodeClient(this._url);
this._disputeAgentsClient = new DisputeAgentsClient(this._url);
this._disputesClient = new DisputesClient(this._url);
this._walletsClient = new WalletsClient(this._url);
this._priceClient = new PriceClient(this._url);
this._paymentAccountsClient = new PaymentAccountsClient(this._url);
this._offersClient = new OffersClient(this._url);
this._tradesClient = new TradesClient(this._url);
this._notificationsClient = new NotificationsClient(this._url);
this._shutdownServerClient = new ShutdownServerClient(this._url);
}
/**
* Start a new Haveno process.
*
* @param {string} havenoPath - path to Haveno binaries
* @param {string[]} cmd - command to start the process
* @param {string} url - Haveno daemon url (must proxy to api port)
* @param {boolean} enableLogging - specifies if logging is enabled or disabled at log level 3
* @return {HavenoClient} a client connected to the newly started Haveno process
*/
static async startProcess(havenoPath: string, cmd: string[], url: string, enableLogging: boolean): Promise<HavenoClient> {
try {
return await new Promise((resolve, reject) => {
HavenoUtils.log(2, "Starting Haveno process: " + cmd + " on proxy url: " + url);
// state variables
let output = "";
let isStarted = false;
let daemon: HavenoClient | undefined = undefined;
// start process
const childProcess = require('child_process').spawn(cmd[0], cmd.slice(1), {cwd: havenoPath});
childProcess.stdout.setEncoding('utf8');
childProcess.stderr.setEncoding('utf8');
// handle stdout
childProcess.stdout.on('data', async function(data: any) {
const line = data.toString();
if (loggingEnabled()) process.stdout.write(line);
output += line + '\n'; // capture output in case of error
// initialize daemon on success or login required message
if (!daemon && (line.indexOf(HavenoClient._fullyInitializedMessage) >= 0 || line.indexOf(HavenoClient._loginRequiredMessage) >= 0)) {
// get api password
const passwordIdx = cmd.indexOf("--apiPassword");
if (passwordIdx < 0) {
reject("Must provide API password to start Haveno daemon");
return;
}
const password = cmd[passwordIdx + 1];
// create client connected to internal process
daemon = new HavenoClient(url, password);
daemon._process = childProcess;
daemon._processLogging = enableLogging;
daemon._appName = cmd[cmd.indexOf("--appName") + 1];
// get wallet rpc port
const walletRpcPortIdx = cmd.indexOf("--walletRpcBindPort");
if (walletRpcPortIdx >= 0) daemon._walletRpcPort = parseInt(cmd[walletRpcPortIdx + 1]);
// resolve promise with client connected to internal process
isStarted = true;
resolve(daemon);
}
// read error message
if (line.indexOf("[HavenoDaemonMain] ERROR") >= 0) {
if (!isStarted) await rejectStartup(new Error(line));
}
});
// handle stderr
childProcess.stderr.on('data', function(data: any) {
if (loggingEnabled()) process.stderr.write(data);
});
// handle exit
childProcess.on("exit", async function(code: any) {
if (!isStarted) await rejectStartup(new Error("Haveno process terminated with exit code " + code + (output ? ":\n\n" + output : "")));
});
// handle error
childProcess.on("error", async function(err: any) {
if (err.message.indexOf("ENOENT") >= 0) reject(new Error("haveno-daemon does not exist at path '" + cmd[0] + "'"));
if (!isStarted) await rejectStartup(err);
});
// handle uncaught exception
childProcess.on("uncaughtException", async function(err: any, origin: any) {
console.error("Uncaught exception in Haveno process: " + err.message);
console.error(origin);
await rejectStartup(err);
});
async function rejectStartup(err: any) {
await HavenoUtils.kill(childProcess);
reject(err);
}
function loggingEnabled(): boolean {
return (daemon && daemon._processLogging) || (!daemon && enableLogging);
}
});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Return the process running the haveno daemon.
*
* @return the process running the haveno daemon
*/
getProcess() {
return this._process;
}
/**
* Enable or disable process logging.
*
* @param {boolean} enabled - specifies if logging is enabled or disabled
*/
setProcessLogging(enabled: boolean) {
if (this._process === undefined) throw new HavenoError("haveno instance not created from new process");
this._processLogging = enabled;
}
/**
* Get the URL of the Haveno daemon.
*
* @return {string} the URL of the Haveno daemon
*/
getUrl(): string {
return this._url;
}
/**
* Get the port of the primary wallet rpc instance if known.
*
* @return {number|undefined} the port of the primary wallet rpc instance if known
*/
getWalletRpcPort(): number|undefined {
return this._walletRpcPort;
}
/**
* Get the name of the Haveno application folder.
*/
getAppName(): string|undefined {
return this._appName;
}
/**
* Get the Haveno version.
*
* @return {string} the Haveno daemon version
*/
async getVersion(): Promise<string> {
try {
return (await this._getVersionClient.getVersion(new GetVersionRequest(), {password: this._password})).getVersion();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Indicates if connected and authenticated with the Haveno daemon.
*
* @return {boolean} true if connected with the Haveno daemon, false otherwise
*/
async isConnectedToDaemon(): Promise<boolean> {
try {
await this.getVersion();
return true;
} catch (err) {
return false;
}
}
/**
* Indicates if the Haveno account is created.
*
* @return {boolean} true if the account is created, false otherwise
*/
async accountExists(): Promise<boolean> {
try {
return (await this._accountClient.accountExists(new AccountExistsRequest(), {password: this._password})).getAccountExists();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Indicates if the Haveno account is open and authenticated with the correct password.
*
* @return {boolean} true if the account is open and authenticated, false otherwise
*/
async isAccountOpen(): Promise<boolean> {
try {
return (await this._accountClient.isAccountOpen(new IsAccountOpenRequest(), {password: this._password})).getIsAccountOpen();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Create and open a new Haveno account.
*
* @param {string} password - the password to encrypt the account
*/
async createAccount(password: string): Promise<void> {
try {
await this._accountClient.createAccount(new CreateAccountRequest().setPassword(password), {password: this._password});
await this._awaitAppInitialized(); // TODO: grpc should not return before setup is complete
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Open existing Haveno account.
*
* @param {string} password - the account password
*/
async openAccount(password: string): Promise<void> {
try {
await this._accountClient.openAccount(new OpenAccountRequest().setPassword(password), {password: this._password});
return this._awaitAppInitialized(); // TODO: grpc should not return before setup is complete
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Change the Haveno account password.
*
* @param {string} password - the new account password
*/
async changePassword(oldPassword: string, newPassword: string): Promise<void> {
try {
const request = new ChangePasswordRequest()
.setOldPassword(oldPassword)
.setNewPassword(newPassword);
await this._accountClient.changePassword(request, {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Close the currently open account.
*/
async closeAccount(): Promise<void> {
try {
await this._accountClient.closeAccount(new CloseAccountRequest(), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Permanently delete the Haveno account.
*/
async deleteAccount(): Promise<void> {
try {
await this._accountClient.deleteAccount(new DeleteAccountRequest(), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Backup the account to the given stream. TODO: stream type?
*/
async backupAccount(stream: any): Promise<number> {
try {
return await new Promise((resolve, reject) => {
let total = 0;
const response = this._accountClient.backupAccount(new BackupAccountRequest(), {password: this._password});
response.on('data', (chunk: any) => {
const bytes = (chunk as BackupAccountReply).getZipBytes(); // TODO: right api?
total += bytes.length;
stream.write(bytes);
});
response.on('error', function(err: any) {
if(err) reject(err);
});
response.on('end', function() {
resolve(total);
});
});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Restore the account from zip bytes.
*
* Sends chunked requests if size over max grpc envelope size (41943404 bytes).
*
* @param {Uint8Array} zipBytes - the bytes of the zipped account to restore
*/
async restoreAccount(zipBytes: Uint8Array): Promise<void> {
if (zipBytes.length === 0) throw new HavenoError("Zip bytes must not be empty")
const totalLength = zipBytes.byteLength;
let offset = 0;
let chunkSize = 4000000; // the max frame size is 4194304 but leave room for http headers
let hasMore = true;
// eslint-disable-next-line no-constant-condition
while (true) {
if (zipBytes.byteLength <= offset + 1) return;
if (zipBytes.byteLength <= offset + chunkSize) {
chunkSize = zipBytes.byteLength - offset - 1;
hasMore = false;
}
const subArray = zipBytes.subarray(offset, offset + chunkSize);
await this._restoreAccountChunk(subArray, offset, totalLength, hasMore);
offset += chunkSize;
}
}
/**
* Add a listener to receive notifications from the Haveno daemon.
*
* @param {(notification: NotificationMessage) => void} listener - the notification listener to add
*/
async addNotificationListener(listener: (_notification: NotificationMessage) => void): Promise<void> {
this._notificationListeners.push(listener);
await this._updateNotificationListenerRegistration();
}
/**
* Remove a notification listener.
*
* @param {(notification: NotificationMessage) => void} listener - the notification listener to remove
*/
async removeNotificationListener(listener: (_notification: NotificationMessage) => void): Promise<void> {
const idx = this._notificationListeners.indexOf(listener);
if (idx > -1) this._notificationListeners.splice(idx, 1);
else throw new HavenoError("Notification listener is not registered");
await this._updateNotificationListenerRegistration();
}
/**
* Indicates if connected to the Monero network based on last connection check.
*
* @return {boolean} true if connected to the Monero network, false otherwise
*/
async isConnectedToMonero(): Promise<boolean> {
const connection = await this.getMoneroConnection();
return connection !== undefined &&
connection.getOnlineStatus()! === UrlConnection.OnlineStatus.ONLINE &&
connection.getAuthenticationStatus()! !== UrlConnection.AuthenticationStatus.NOT_AUTHENTICATED;
}
/**
* Add a Monero daemon connection.
*
* @param {string | UrlConnection} connection - daemon url or connection to add
*/
async addMoneroConnection(connection: string | UrlConnection): Promise<void> {
try {
await this._xmrConnectionsClient.addConnection(new AddConnectionRequest().setConnection(typeof connection === "string" ? new UrlConnection().setUrl(connection) : connection), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Remove a Monero daemon connection.
*
* @param {string} url - url of the daemon connection to remove
*/
async removeMoneroConnection(url: string): Promise<void> {
try {
await this._xmrConnectionsClient.removeConnection(new RemoveConnectionRequest().setUrl(url), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the current Monero daemon connection.
*
* @return {UrlConnection | undefined} the current daemon connection, undefined if no current connection
*/
async getMoneroConnection(): Promise<UrlConnection | undefined> {
try {
return await (await this._xmrConnectionsClient.getConnection(new GetConnectionRequest(), {password: this._password})).getConnection();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get all Monero daemon connections.
*
* @return {UrlConnection[]} all daemon connections
*/
async getMoneroConnections(): Promise<UrlConnection[]> {
try {
return (await this._xmrConnectionsClient.getConnections(new GetConnectionsRequest(), {password: this._password})).getConnectionsList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Set the current Monero daemon connection.
*
* Add the connection if not previously seen.
* If the connection is provided as string, connect to the URI with any previously set credentials and priority.
* If the connection is provided as UrlConnection, overwrite any previously set credentials and priority.
* If undefined connection provided, disconnect the client.
*
* @param {string | UrlConnection} connection - connection to set as current
*/
async setMoneroConnection(connection?: string | UrlConnection): Promise<void> {
const request = new SetConnectionRequest();
if (typeof connection === "string") request.setUrl(connection);
else request.setConnection(connection);
try {
await this._xmrConnectionsClient.setConnection(request, {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Check the current Monero daemon connection.
*
* If disconnected and auto switch enabled, switch to the best available connection and return its status.
*
* @return {UrlConnection | undefined} the current daemon connection status, undefined if no current connection
*/
async checkMoneroConnection(): Promise<UrlConnection | undefined> {
try {
return (await this._xmrConnectionsClient.checkConnection(new CheckConnectionRequest(), {password: this._password})).getConnection();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Check all Monero daemon connections.
*
* @return {UrlConnection[]} status of all managed connections.
*/
async checkMoneroConnections(): Promise<UrlConnection[]> {
try {
return (await this._xmrConnectionsClient.checkConnections(new CheckConnectionsRequest(), {password: this._password})).getConnectionsList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Check the connection and start checking the connection periodically.
*
* @param {number} refreshPeriod - time between checks in milliseconds (default 15000 ms or 15 seconds)
*/
async startCheckingConnection(refreshPeriod: number): Promise<void> {
try {
await this._xmrConnectionsClient.startCheckingConnection(new StartCheckingConnectionRequest().setRefreshPeriod(refreshPeriod), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Stop checking the connection status periodically.
*/
async stopCheckingConnection(): Promise<void> {
try {
await this._xmrConnectionsClient.stopCheckingConnection(new StopCheckingConnectionRequest(), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the best available connection in order of priority then response time.
*
* @return {UrlConnection | undefined} the best available connection in order of priority then response time, undefined if no connections available
*/
async getBestAvailableConnection(): Promise<UrlConnection | undefined> {
try {
return (await this._xmrConnectionsClient.getBestAvailableConnection(new GetBestAvailableConnectionRequest(), {password: this._password})).getConnection();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Automatically switch to the best available connection if current connection is disconnected after being checked.
*
* @param {boolean} autoSwitch - whether auto switch is enabled or disabled
*/
async setAutoSwitch(autoSwitch: boolean): Promise<void> {
try {
await this._xmrConnectionsClient.setAutoSwitch(new SetAutoSwitchRequest().setAutoSwitch(autoSwitch), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the current auto switch setting.
*
* @return {boolean} whether auto switch is enabled or disabled
*/
async getAutoSwitch(): Promise<boolean> {
try {
return (await this._xmrConnectionsClient.getAutoSwitch(new GetAutoSwitchRequest(), {password: this._password})).getAutoSwitch();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Returns whether daemon is running a local monero node.
*/
async isMoneroNodeOnline(): Promise<boolean> {
try {
return (await this._xmrNodeClient.isXmrNodeOnline(new IsXmrNodeOnlineRequest(), {password: this._password})).getIsRunning();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Gets the current local monero node settings.
*/
async getMoneroNodeSettings(): Promise<XmrNodeSettings | undefined> {
try {
const request = new GetXmrNodeSettingsRequest();
return (await this._xmrNodeClient.getXmrNodeSettings(request, {password: this._password})).getSettings();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Starts the local monero node.
*
* @param {MoneroNodeSettings} settings - the settings to start the local node with
*/
async startMoneroNode(settings: XmrNodeSettings): Promise<void> {
try {
const request = new StartXmrNodeRequest().setSettings(settings);
await this._xmrNodeClient.startXmrNode(request, {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Stops the local monero node.
*/
async stopMoneroNode(): Promise<void> {
try {
await this._xmrNodeClient.stopXmrNode(new StopXmrNodeRequest(), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Register as a dispute agent.
*
* @param {string} disputeAgentType - type of dispute agent to register, e.g. mediator, refundagent
* @param {string} registrationKey - registration key
*/
async registerDisputeAgent(disputeAgentType: string, registrationKey: string): Promise<void> {
try {
const request = new RegisterDisputeAgentRequest()
.setDisputeAgentType(disputeAgentType)
.setRegistrationKey(registrationKey);
await this._disputeAgentsClient.registerDisputeAgent(request, {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Unregister as a dispute agent.
*
* @param {string} disputeAgentType - type of dispute agent to register, e.g. mediator, refundagent
*/
async unregisterDisputeAgent(disputeAgentType: string): Promise<void> {
try {
await this._disputeAgentsClient.unregisterDisputeAgent(new UnregisterDisputeAgentRequest().setDisputeAgentType(disputeAgentType), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the user's balances.
*
* @return {XmrBalanceInfo} the user's balances
*/
async getBalances(): Promise<XmrBalanceInfo> {
try {
return (await this._walletsClient.getBalances(new GetBalancesRequest().setCurrencyCode("XMR"), {password: this._password})).getBalances()!.getXmr()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the mnemonic seed phrase of the Monero wallet.
*
* @return {string} the mnemonic seed phrase of the Monero wallet
*/
async getXmrSeed(): Promise<string> {
try {
return (await this._walletsClient.getXmrSeed(new GetXmrSeedRequest(), {password: this._password})).getSeed();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the primary address of the Monero wallet.
*
* @return {string} the primary address of the Monero wallet
*/
async getXmrPrimaryAddress(): Promise<string> {
try {
return (await this._walletsClient.getXmrPrimaryAddress(new GetXmrPrimaryAddressRequest(), {password: this._password})).getPrimaryAddress();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get a new subaddress in the Monero wallet to receive deposits.
*
* @return {string} the deposit address (a subaddress in the Haveno wallet)
*/
async getXmrNewSubaddress(): Promise<string> {
try {
return (await this._walletsClient.getXmrNewSubaddress(new GetXmrNewSubaddressRequest(), {password: this._password})).getSubaddress();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get all transactions in the Monero wallet.
*
* @return {XmrTx[]} the transactions
*/
async getXmrTxs(): Promise<XmrTx[]> {
try {
return (await this._walletsClient.getXmrTxs(new GetXmrTxsRequest(), {password: this._password})).getTxsList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get a transaction by hash in the Monero wallet.
*
* @param {String} txHash - hash of the transaction to get
* @return {XmrTx} the transaction with the hash
*/
async getXmrTx(txHash: string): Promise<XmrTx|undefined> {
const txs = await this.getXmrTxs(); // TODO (woodser): implement getXmrTx(hash) grpc call
for (const tx of txs) {
if (tx.getHash() === txHash) return tx;
}
return undefined;
}
/**
* Create but do not relay a transaction to send funds from the Monero wallet.
*
* @return {XmrTx} the created transaction
*/
async createXmrTx(destinations: XmrDestination[]): Promise<XmrTx> {
try {
return (await this._walletsClient.createXmrTx(new CreateXmrTxRequest().setDestinationsList(destinations), {password: this._password})).getTx()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Relay a previously created transaction to send funds from the Monero wallet.
*
* @return {string} the hash of the relayed transaction
*/
async relayXmrTx(metadata: string): Promise<string> {
try {
return (await this._walletsClient.relayXmrTx(new RelayXmrTxRequest().setMetadata(metadata), {password: this._password})).getHash();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get all asset codes with price information.
*
* TODO: replace this with getSupportedAssetCodes(): Promise<TradeCurrency[]>)
*
* @return {Promise<string[]>} all supported trade assets
*/
async getPricedAssetCodes(): Promise<string[]> {
const assetCodes: string[] = [];
for (const price of await this.getPrices()) assetCodes.push(price.getCurrencyCode());
return assetCodes;
}
/**
* Get the current market price per 1 XMR in the given currency.
*
* @param {string} assetCode - asset code to get the price of
* @return {number} the price of the asset per 1 XMR
*/
async getPrice(assetCode: string): Promise<number> {
try {
return (await this._priceClient.getMarketPrice(new MarketPriceRequest().setCurrencyCode(assetCode), {password: this._password})).getPrice();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the current market prices of all a.
*
* @return {MarketPrice[]} prices of the assets per 1 XMR
*/
async getPrices(): Promise<MarketPriceInfo[]> {
try {
return (await this._priceClient.getMarketPrices(new MarketPricesRequest(), {password: this._password})).getMarketPriceList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get the market depth of a currency.
*
* @param {string} assetCode - asset to get the market depth of
* @return {MarketDepthInfo} market depth of the given currency
*/
async getMarketDepth(assetCode: string): Promise<MarketDepthInfo> {
try {
return (await this._priceClient.getMarketDepth(new MarketDepthRequest().setCurrencyCode(assetCode), {password: this._password})).getMarketDepth()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get payment methods.
*
* @param {string} assetCode - get payment methods supporting this asset code (optional)
* @return {PaymentMethod[]} the payment methods
*/
async getPaymentMethods(assetCode?: string): Promise<PaymentMethod[]> {
try {
if (!this._paymentMethods) {
this._paymentMethods = (await this._paymentAccountsClient.getPaymentMethods(new GetPaymentMethodsRequest(), {password: this._password})).getPaymentMethodsList();
}
if (!assetCode) return this._paymentMethods!;
const assetPaymentMethods: PaymentMethod[] = [];
for (const paymentMethod of this._paymentMethods!) {
if (paymentMethod.getSupportedAssetCodesList().includes(assetCode)) assetPaymentMethods.push(paymentMethod);
}
return assetPaymentMethods;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get payment accounts.
*
* @return {PaymentAccount[]} the payment accounts
*/
async getPaymentAccounts(): Promise<PaymentAccount[]> {
try {
return (await this._paymentAccountsClient.getPaymentAccounts(new GetPaymentAccountsRequest(), {password: this._password})).getPaymentAccountsList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get a payment account by id.
*
* @param {string} paymentAccountId - the payment account id to get
* @return {PaymentAccount} the payment account
*/
async getPaymentAccount(paymentAccountId: string): Promise<PaymentAccount> {
// TODO (woodser): implement this on the backend
const paymentAccounts = await this.getPaymentAccounts();
for (const paymentAccount of paymentAccounts) {
if (paymentAccount.getId() === paymentAccountId) return paymentAccount;
}
throw new HavenoError("No payment account with id " + paymentAccountId);
}
/**
* Get a form for the given payment method to complete and create a new payment account.
*
* @param {string | PaymentAccountForm.FormId} paymentMethodId - the id of the payment method
* @return {PaymentAccountForm} the payment account form
*/
async getPaymentAccountForm(paymentMethodId: string | PaymentAccountForm.FormId): Promise<PaymentAccountForm> {
try {
paymentMethodId = HavenoUtils.getPaymentMethodId(paymentMethodId); // validate and normalize
return (await this._paymentAccountsClient.getPaymentAccountForm(new GetPaymentAccountFormRequest().setPaymentMethodId(paymentMethodId), {password: this._password})).getPaymentAccountForm()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get a form from the given payment account payload.
*
* @param {PaymentAccountPayload} paymentAccountPayload - payload to get as a form
* @return {PaymentAccountForm} the payment account form
*/
async getPaymentAccountPayloadForm(paymentAccountPayload: PaymentAccountPayload): Promise<PaymentAccountForm> {
try {
return (await this._paymentAccountsClient.getPaymentAccountForm(new GetPaymentAccountFormRequest().setPaymentAccountPayload(paymentAccountPayload), {password: this._password})).getPaymentAccountForm()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/*
* Validate a form field.
*
* @param {object} form - form context to validate the given value
* @param {PaymentAccountFormField.FieldId} fieldId - id of the field to validate
* @param {string} value - input value to validate
*/
async validateFormField(form: PaymentAccountForm, fieldId: PaymentAccountFormField.FieldId, value: string): Promise<void> {
const request = new ValidateFormFieldRequest()
.setForm(form)
.setFieldId(fieldId)
.setValue(value);
try {
await this._paymentAccountsClient.validateFormField(request, {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Create a payment account.
*
* @param {PaymentAccountForm} paymentAccountForm - the completed form to create the payment account
* @return {PaymentAccount} the created payment account
*/
async createPaymentAccount(paymentAccountForm: PaymentAccountForm): Promise<PaymentAccount> {
try {
return (await this._paymentAccountsClient.createPaymentAccount(new CreatePaymentAccountRequest().setPaymentAccountForm(paymentAccountForm), {password: this._password})).getPaymentAccount()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Create a crypto payment account.
*
* @param {string} accountName - description of the account
* @param {string} assetCode - traded asset code
* @param {string} address - payment address of the account
* @return {PaymentAccount} the created payment account
*/
async createCryptoPaymentAccount(accountName: string, assetCode: string, address: string): Promise<PaymentAccount> {
try {
const request = new CreateCryptoCurrencyPaymentAccountRequest()
.setAccountName(accountName)
.setCurrencyCode(assetCode)
.setAddress(address)
.setTradeInstant(false); // not using instant trades
return (await this._paymentAccountsClient.createCryptoCurrencyPaymentAccount(request, {password: this._password})).getPaymentAccount()!;
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Delete a payment account.
*
* @param {string} paymentAccountId the id of the payment account to delete
*/
async deletePaymentAccount(paymentAccountId: string): Promise<void> {
try {
await this._paymentAccountsClient.deletePaymentAccount(new DeletePaymentAccountRequest().setPaymentAccountId(paymentAccountId), {password: this._password});
} catch (e: any) {
throw new HavenoError(e.message, e.code);
}
}
/**
* Get available offers to buy or sell XMR.
*
* @param {string} assetCode - traded asset code
* @param {OfferDirection|undefined} direction - "buy" or "sell" (default all)
* @return {OfferInfo[]} the available offers
*/
async getOffers(assetCode: string, direction?: OfferDirection): Promise<OfferInfo[]> {
try {
if (direction === undefined) return (await this.getOffers(assetCode, OfferDirection.BUY)).concat(await this.getOffers(assetCode, OfferDirection.SELL)); // TODO: implement in backend
return (await this._offersClient.getOffers(new GetOffersRequest().setDirection(direction === OfferDirection.BUY ? "buy" : "sell").setCurrencyCode(assetCode), {password: this._password})).getOffersList();
} catch (e: any) {
throw new HavenoError(e.message, e.code);