/
api.js
897 lines (815 loc) · 33 KB
/
api.js
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
// @flow
import { split, get, unionBy } from 'lodash';
import { action } from 'mobx';
import BigNumber from 'bignumber.js';
import moment from 'moment';
// domains
import Wallet from '../domains/Wallet';
import { WalletTransaction, transactionTypes } from '../domains/WalletTransaction';
import WalletAddress from '../domains/WalletAddress';
// Accounts requests
import { getAccounts } from './accounts/requests/getAccounts';
// Addresses requests
import { getAddress } from './addresses/requests/getAddress';
import { createAddress } from './addresses/requests/createAddress';
// Nodes requests
import { applyNodeUpdate } from './nodes/requests/applyNodeUpdate';
import { getNodeInfo } from './nodes/requests/getNodeInfo';
import { getNextNodeUpdate } from './nodes/requests/getNextNodeUpdate';
import { postponeNodeUpdate } from './nodes/requests/postponeNodeUpdate';
// Transactions requests
import { getTransactionFee } from './transactions/requests/getTransactionFee';
import { getTransactionHistory } from './transactions/requests/getTransactionHistory';
import { createTransaction } from './transactions/requests/createTransaction';
import { redeemAda } from './transactions/requests/redeemAda';
import { redeemPaperVendedAda } from './transactions/requests/redeemPaperVendedAda';
// Wallets requests
import { resetWalletState } from './wallets/requests/resetWalletState';
import { changeSpendingPassword } from './wallets/requests/changeSpendingPassword';
import { deleteWallet } from './wallets/requests/deleteWallet';
import { exportWalletAsJSON } from './wallets/requests/exportWalletAsJSON';
import { importWalletAsJSON } from './wallets/requests/importWalletAsJSON';
import { getWallets } from './wallets/requests/getWallets';
import { importWalletAsKey } from './wallets/requests/importWalletAsKey';
import { createWallet } from './wallets/requests/createWallet';
import { restoreWallet } from './wallets/requests/restoreWallet';
import { updateWallet } from './wallets/requests/updateWallet';
// utility functions
import { awaitUpdateChannel, cardanoFaultInjectionChannel } from '../ipc/cardano.ipc';
import patchAdaApi from './utils/patchAdaApi';
import { isValidMnemonic } from '../../../common/crypto/decrypt';
import { utcStringToDate, encryptPassphrase } from './utils';
import { Logger } from '../utils/logging';
import {
isValidRedemptionKey,
isValidPaperVendRedemptionKey
} from '../utils/redemption-key-validation';
import {
unscrambleMnemonics,
scrambleMnemonics,
generateAccountMnemonics,
generateAdditionalMnemonics
} from './utils/mnemonics';
import { filterLogData } from '../../../common/utils/logging';
// config constants
import {
LOVELACES_PER_ADA,
MAX_TRANSACTIONS_PER_PAGE,
MAX_TRANSACTION_CONFIRMATIONS,
TX_AGE_POLLING_THRESHOLD
} from '../config/numbersConfig';
import {
ADA_CERTIFICATE_MNEMONIC_LENGTH,
ADA_REDEMPTION_PASSPHRASE_LENGTH,
WALLET_RECOVERY_PHRASE_WORD_COUNT
} from '../config/cryptoConfig';
// Accounts types
import type { Accounts } from './accounts/types';
// Addresses Types
import type {
Address,
GetAddressesRequest,
CreateAddressRequest,
GetAddressesResponse
} from './addresses/types';
// Common Types
import type {
RequestConfig,
} from './common/types';
// Nodes Types
import type {
NodeInfo,
NodeSoftware,
GetNetworkStatusResponse
} from './nodes/types';
import type { NodeQueryParams } from './nodes/requests/getNodeInfo';
// Transactions Types
import type { RedeemAdaParams } from './transactions/requests/redeemAda';
import type { RedeemPaperVendedAdaParams } from './transactions/requests/redeemPaperVendedAda';
import type {
Transaction,
Transactions,
TransactionFee,
TransactionRequest,
GetTransactionsRequest,
GetTransactionsResponse
} from './transactions/types';
// Wallets Types
import type {
AdaWallet,
AdaWallets,
CreateWalletRequest,
DeleteWalletRequest,
RestoreWalletRequest,
UpdateSpendingPasswordRequest,
ExportWalletToFileRequest,
GetWalletCertificateRecoveryPhraseRequest,
GetWalletRecoveryPhraseFromCertificateRequest,
ImportWalletFromKeyRequest,
ImportWalletFromFileRequest,
UpdateWalletRequest
} from './wallets/types';
// Common errors
import {
GenericApiError,
IncorrectSpendingPasswordError,
InvalidMnemonicError,
ForbiddenMnemonicError
} from './common/errors';
// Wallets errors
import {
WalletAlreadyRestoredError,
WalletAlreadyImportedError,
WalletFileImportError
} from './wallets/errors';
// Transactions errors
import {
CanNotCalculateTransactionFeesError,
NotAllowedToSendMoneyToRedeemAddressError,
NotEnoughFundsForTransactionFeesError,
NotEnoughFundsForTransactionError,
NotEnoughMoneyToSendError,
RedeemAdaError
} from './transactions/errors';
import type { FaultInjectionIpcRequest } from '../../../common/types/cardano-node.types';
export default class AdaApi {
config: RequestConfig;
constructor(isTest: boolean, config: RequestConfig) {
this.setRequestConfig(config);
if (isTest) patchAdaApi(this);
}
setRequestConfig(config: RequestConfig) {
this.config = config;
}
getWallets = async (): Promise<Array<Wallet>> => {
Logger.debug('AdaApi::getWallets called');
try {
const response: AdaWallets = await getWallets(this.config);
Logger.debug('AdaApi::getWallets success', { wallets: response });
return response.map(data => _createWalletFromServerData(data));
} catch (error) {
Logger.error('AdaApi::getWallets error', { error });
throw new GenericApiError();
}
};
getAddresses = async (request: GetAddressesRequest): Promise<GetAddressesResponse> => {
Logger.debug('AdaApi::getAddresses called', { parameters: filterLogData(request) });
const { walletId } = request;
try {
const accounts: Accounts = await getAccounts(this.config, { walletId });
const response = accounts.map(account => (
Object.assign({}, account, { addresses: account.addresses.length })
));
Logger.debug('AdaApi::getAddresses success', { response });
if (!accounts || !accounts.length) {
return new Promise(resolve => resolve({ accountIndex: null, addresses: [] }));
}
// For now only the first wallet account is used
const firstAccount = accounts[0];
const { index: accountIndex, addresses } = firstAccount;
return new Promise(resolve => resolve({ accountIndex, addresses }));
} catch (error) {
Logger.error('AdaApi::getAddresses error', { error });
throw new GenericApiError();
}
};
getTransactions = async (request: GetTransactionsRequest): Promise<GetTransactionsResponse> => {
const requestTimestamp = moment();
const requestStats = Object.assign({}, request, {
cachedTransactions: request.cachedTransactions.length,
});
Logger.debug('AdaApi::searchHistory called', { parameters: requestStats });
const {
walletId, skip, limit,
isFirstLoad, // during first load we fetch all wallet's transactions
isRestoreActive, // during restoration we fetch only missing transactions
isRestoreCompleted, // once restoration is done we fetch potentially missing transactions
cachedTransactions,
} = request;
const accounts: Accounts = await getAccounts(this.config, { walletId });
if (!accounts.length || !accounts[0].index) {
return new Promise(resolve => resolve({ transactions: [], total: 0 }));
}
let perPage = limit;
const shouldLoadAll = limit === null;
if (shouldLoadAll || limit > MAX_TRANSACTIONS_PER_PAGE) {
perPage = MAX_TRANSACTIONS_PER_PAGE;
}
const params = {
wallet_id: walletId,
account_index: accounts[0].index,
page: skip === 0 ? 1 : skip + 1,
per_page: perPage,
sort_by: 'DES[created_at]',
created_at: `LTE[${moment.utc().format('YYYY-MM-DDTHH:mm:ss')}]`,
// ^^ By setting created_at filter to current time we make sure
// all subsequent multi-pages requests load the same set of transactions
};
const shouldLoadOnlyFresh = !isFirstLoad && !isRestoreActive && !isRestoreCompleted;
if (shouldLoadOnlyFresh) {
const tenMinutesAgo =
moment.utc(Date.now() - TX_AGE_POLLING_THRESHOLD).format('YYYY-MM-DDTHH:mm:ss');
// Since we load all transactions in a first load, later on we only care about fresh ones
Object.assign(params, { created_at: `GTE[${tenMinutesAgo}]` });
}
const pagesToBeLoaded = Math.ceil(limit / params.per_page);
try {
// Load first page of transactions
const response: Transactions = await getTransactionHistory(this.config, params);
const { meta, data: txHistory } = response;
const { totalPages, totalEntries: totalTransactions } = meta.pagination;
let transactions = txHistory.map(tx => _createTransactionFromServerData(tx));
// Load additional pages of transactions
const hasMultiplePages = (totalPages > 1 && (shouldLoadAll || limit > perPage));
if (hasMultiplePages) {
let page = 2;
const hasNextPage = () => {
const hasMorePages = (page < totalPages + 1);
if ((isRestoreActive || isRestoreCompleted) && hasMorePages) {
const loadedTransactions = unionBy(transactions, cachedTransactions, 'id');
const hasMoreTransactions = (totalTransactions - loadedTransactions.length) > 0;
return hasMoreTransactions;
}
return hasMorePages;
};
const shouldLoadNextPage = () => shouldLoadAll || page <= pagesToBeLoaded;
if (isRestoreActive || isRestoreCompleted) {
const latestLoadedTransactionDate = transactions[0].date;
const latestLoadedTransactionDateString =
moment.utc(latestLoadedTransactionDate).format('YYYY-MM-DDTHH:mm:ss');
// During restoration we need to fetch only transactions older than the latest loaded one
// as this ensures that both totalPages and totalEntries remain unchanged throught out
// subsequent page loads (as in the meantime new transactions can be discovered)
Object.assign(params, { created_at: `LTE[${latestLoadedTransactionDateString}]` });
}
for (page; (hasNextPage() && shouldLoadNextPage()); page++) {
const { data: pageHistory } =
await getTransactionHistory(this.config, Object.assign(params, { page }));
transactions.push(...pageHistory.map(tx => _createTransactionFromServerData(tx)));
}
}
// Merge newly loaded and previously loaded transactions
// - unionBy also serves the purpose of removing transaction duplicates
// which may occur as a side-effect of transaction request pagination
// as multi-page requests are not executed at the exact same time!
transactions = unionBy(transactions, cachedTransactions, 'id');
// Enforce the limit in case we are not loading all transactions
if (!shouldLoadAll) transactions.splice(limit);
const total = transactions.length;
const responseStats = {
apiRequested: limit || 'all',
apiFiltered: shouldLoadOnlyFresh ? 'fresh' : '',
apiReturned: totalTransactions,
apiPagesTotal: totalPages,
apiPagesRequested: params.page,
daedalusCached: cachedTransactions.length,
daedalusLoaded: total - cachedTransactions.length,
daedalusTotal: total,
requestDurationInMs: moment.duration(moment().diff(requestTimestamp)).as('milliseconds'),
};
Logger.debug(`AdaApi::searchHistory success: ${total} transactions loaded`, { responseStats });
return new Promise(resolve => resolve({ transactions, total }));
} catch (error) {
Logger.error('AdaApi::searchHistory error', { error });
throw new GenericApiError();
}
};
createWallet = async (request: CreateWalletRequest): Promise<Wallet> => {
Logger.debug('AdaApi::createWallet called', { parameters: filterLogData(request) });
const { name, mnemonic, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
const assuranceLevel = 'normal';
try {
const walletInitData = {
operation: 'create',
backupPhrase: split(mnemonic, ' '),
assuranceLevel,
name,
spendingPassword,
};
const wallet: AdaWallet = await createWallet(this.config, { walletInitData });
Logger.debug('AdaApi::createWallet success', { wallet });
return _createWalletFromServerData(wallet);
} catch (error) {
Logger.error('AdaApi::createWallet error', { error });
throw new GenericApiError();
}
};
deleteWallet = async (request: DeleteWalletRequest): Promise<boolean> => {
Logger.debug('AdaApi::deleteWallet called', { parameters: filterLogData(request) });
try {
const { walletId } = request;
const response = await deleteWallet(this.config, { walletId });
Logger.debug('AdaApi::deleteWallet success', { response });
return true;
} catch (error) {
Logger.error('AdaApi::deleteWallet error', { error });
throw new GenericApiError();
}
};
createTransaction = async (
request: TransactionRequest
): Promise<WalletTransaction> => {
Logger.debug('AdaApi::createTransaction called', { parameters: filterLogData(request) });
const { accountIndex, walletId, address, amount, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
try {
const data = {
source: {
accountIndex,
walletId,
},
destinations: [
{
address,
amount,
},
],
groupingPolicy: 'OptimizeForSecurity',
spendingPassword,
};
const response: Transaction = await createTransaction(this.config, { data });
Logger.debug('AdaApi::createTransaction success', { transaction: response });
return _createTransactionFromServerData(response);
} catch (error) {
Logger.error('AdaApi::createTransaction error', { error });
if (error.message === 'OutputIsRedeem') {
throw new NotAllowedToSendMoneyToRedeemAddressError();
}
if (
error.message === 'NotEnoughMoney' ||
error.message === 'UtxoNotEnoughFragmented'
) {
throw new NotEnoughMoneyToSendError();
}
if (error.message === 'CannotCreateAddress') {
throw new IncorrectSpendingPasswordError();
}
throw new GenericApiError();
}
};
calculateTransactionFee = async (
request: TransactionRequest
): Promise<BigNumber> => {
Logger.debug('AdaApi::calculateTransactionFee called', { parameters: filterLogData(request) });
const {
accountIndex,
walletId, walletBalance,
address, amount,
} = request;
try {
const data = {
source: {
accountIndex,
walletId,
},
destinations: [
{
address,
amount,
},
],
groupingPolicy: 'OptimizeForSecurity',
};
const response: TransactionFee = await getTransactionFee(this.config, { data });
Logger.debug('AdaApi::calculateTransactionFee success', { transactionFee: response });
return _createTransactionFeeFromServerData(response);
} catch (error) {
Logger.error('AdaApi::calculateTransactionFee error', { error });
if (
error.message === 'NotEnoughMoney' ||
error.message === 'UtxoNotEnoughFragmented'
) {
const errorMessage = get(error, 'diagnostic.details.msg', '');
if (errorMessage.includes('Not enough coins to cover fee')) {
// Amount + fees exceeds walletBalance:
// - error.diagnostic.details.msg === 'Not enough coins to cover fee.'
// = show "Not enough Ada for fees. Try sending a smaller amount."
throw new NotEnoughFundsForTransactionFeesError();
} else if (errorMessage.includes('Not enough available coins to proceed')) {
const availableBalance = new BigNumber(
get(error, 'diagnostic.details.availableBalance', 0)
).dividedBy(LOVELACES_PER_ADA);
if (walletBalance.gt(availableBalance)) {
// Amount exceeds availableBalance due to pending transactions:
// - error.diagnostic.details.msg === 'Not enough available coins to proceed.'
// - total walletBalance > error.diagnostic.details.availableBalance
// = show "Cannot calculate fees while there are pending transactions."
throw new CanNotCalculateTransactionFeesError();
} else {
// Amount exceeds walletBalance:
// - error.diagnostic.details.msg === 'Not enough available coins to proceed.'
// - total walletBalance === error.diagnostic.details.availableBalance
// = show "Not enough Ada. Try sending a smaller amount."
throw new NotEnoughFundsForTransactionError();
}
} else {
// Amount exceeds walletBalance:
// = show "Not enough Ada. Try sending a smaller amount."
throw new NotEnoughFundsForTransactionError();
}
}
throw new GenericApiError();
}
};
createAddress = async (request: CreateAddressRequest): Promise<Address> => {
Logger.debug('AdaApi::createAddress called', { parameters: filterLogData(request) });
const { accountIndex, walletId, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
try {
const address: Address = await createAddress(
this.config, { spendingPassword, accountIndex, walletId }
);
Logger.debug('AdaApi::createAddress success', { address });
return _createAddressFromServerData(address);
} catch (error) {
Logger.error('AdaApi::createAddress error', { error });
if (error.message === 'CannotCreateAddress') {
throw new IncorrectSpendingPasswordError();
}
throw new GenericApiError();
}
};
async isValidAddress(address: string): Promise<boolean> {
Logger.debug('AdaApi::isValidAdaAddress called', { parameters: { address } });
try {
const response: Address = await getAddress(this.config, { address });
Logger.debug('AdaApi::isValidAdaAddress success', { response });
return true;
} catch (error) {
Logger.error('AdaApi::isValidAdaAddress error', { error });
return false;
}
}
isValidMnemonic = (mnemonic: string): boolean => (
isValidMnemonic(mnemonic, WALLET_RECOVERY_PHRASE_WORD_COUNT)
);
isValidRedemptionKey = (mnemonic: string): boolean => (isValidRedemptionKey(mnemonic));
isValidPaperVendRedemptionKey = (mnemonic: string): boolean => (
isValidPaperVendRedemptionKey(mnemonic)
);
isValidRedemptionMnemonic = (mnemonic: string): boolean => (
isValidMnemonic(mnemonic, ADA_REDEMPTION_PASSPHRASE_LENGTH)
);
isValidCertificateMnemonic = (mnemonic: string): boolean => (
mnemonic.split(' ').length === ADA_CERTIFICATE_MNEMONIC_LENGTH
);
getWalletRecoveryPhrase(): Promise<Array<string>> {
Logger.debug('AdaApi::getWalletRecoveryPhrase called');
try {
const response: Promise<Array<string>> = new Promise(
(resolve) => resolve(generateAccountMnemonics())
);
Logger.debug('AdaApi::getWalletRecoveryPhrase success');
return response;
} catch (error) {
Logger.error('AdaApi::getWalletRecoveryPhrase error', { error });
throw new GenericApiError();
}
}
// eslint-disable-next-line max-len
getWalletCertificateAdditionalMnemonics(): Promise<Array<string>> {
Logger.debug('AdaApi::getWalletCertificateAdditionalMnemonics called');
try {
const response: Promise<Array<string>> = new Promise(
(resolve) => resolve(generateAdditionalMnemonics())
);
Logger.debug('AdaApi::getWalletCertificateAdditionalMnemonics success');
return response;
} catch (error) {
Logger.error('AdaApi::getWalletCertificateAdditionalMnemonics error', { error });
throw new GenericApiError();
}
}
getWalletCertificateRecoveryPhrase(
request: GetWalletCertificateRecoveryPhraseRequest
): Promise<Array<string>> {
Logger.debug('AdaApi::getWalletCertificateRecoveryPhrase called');
const { passphrase, input: scrambledInput } = request;
try {
const response: Promise<Array<string>> = new Promise(
(resolve) => resolve(scrambleMnemonics({ passphrase, scrambledInput }))
);
Logger.debug('AdaApi::getWalletCertificateRecoveryPhrase success');
return response;
} catch (error) {
Logger.error('AdaApi::getWalletCertificateRecoveryPhrase error', { error });
throw new GenericApiError();
}
}
getWalletRecoveryPhraseFromCertificate(
request: GetWalletRecoveryPhraseFromCertificateRequest
): Promise<Array<string>> {
Logger.debug('AdaApi::getWalletRecoveryPhraseFromCertificate called');
const { passphrase, scrambledInput } = request;
try {
const response = unscrambleMnemonics({ passphrase, scrambledInput });
Logger.debug('AdaApi::getWalletRecoveryPhraseFromCertificate success');
return Promise.resolve(response);
} catch (error) {
Logger.error('AdaApi::getWalletRecoveryPhraseFromCertificate error', { error });
return Promise.reject(new InvalidMnemonicError());
}
}
restoreWallet = async (request: RestoreWalletRequest): Promise<Wallet> => {
Logger.debug('AdaApi::restoreWallet called', { parameters: filterLogData(request) });
const { recoveryPhrase, walletName, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
const assuranceLevel = 'normal';
const walletInitData = {
operation: 'restore',
backupPhrase: split(recoveryPhrase, ' '),
assuranceLevel,
name: walletName,
spendingPassword
};
try {
const wallet: AdaWallet = await restoreWallet(this.config, { walletInitData });
Logger.debug('AdaApi::restoreWallet success', { wallet });
return _createWalletFromServerData(wallet);
} catch (error) {
Logger.error('AdaApi::restoreWallet error', { error });
if (error.message === 'WalletAlreadyExists') {
throw new WalletAlreadyRestoredError();
}
if (error.message === 'JSONValidationFailed') {
const validationError = get(error, 'diagnostic.validationError', '');
if (validationError.includes('Forbidden Mnemonic: an example Mnemonic has been submitted')) {
throw new ForbiddenMnemonicError();
}
}
throw new GenericApiError();
}
};
importWalletFromKey = async (
request: ImportWalletFromKeyRequest
): Promise<Wallet> => {
Logger.debug('AdaApi::importWalletFromKey called', { parameters: filterLogData(request) });
const { filePath, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
try {
const importedWallet: AdaWallet = await importWalletAsKey(
this.config, { filePath, spendingPassword }
);
Logger.debug('AdaApi::importWalletFromKey success', { importedWallet });
return _createWalletFromServerData(importedWallet);
} catch (error) {
Logger.error('AdaApi::importWalletFromKey error', { error });
if (error.message === 'WalletAlreadyExists') {
throw new WalletAlreadyImportedError();
}
throw new WalletFileImportError();
}
};
importWalletFromFile = async (
request: ImportWalletFromFileRequest
): Promise<Wallet> => {
Logger.debug('AdaApi::importWalletFromFile called', { parameters: filterLogData(request) });
const { filePath, spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
const isKeyFile = filePath.split('.').pop().toLowerCase() === 'key';
try {
const importedWallet: AdaWallet = isKeyFile ? (
await importWalletAsKey(this.config, { filePath, spendingPassword })
) : (
await importWalletAsJSON(this.config, filePath)
);
Logger.debug('AdaApi::importWalletFromFile success', { importedWallet });
return _createWalletFromServerData(importedWallet);
} catch (error) {
Logger.error('AdaApi::importWalletFromFile error', { error });
if (error.message === 'WalletAlreadyExists') {
throw new WalletAlreadyImportedError();
}
throw new WalletFileImportError();
}
};
redeemAda = async (
request: RedeemAdaParams
): Promise<WalletTransaction> => {
Logger.debug('AdaApi::redeemAda called', { parameters: filterLogData(request) });
const { spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
try {
const transaction: Transaction = await redeemAda(
this.config, { ...request, spendingPassword }
);
Logger.debug('AdaApi::redeemAda success', { transaction });
return _createTransactionFromServerData(transaction);
} catch (error) {
Logger.error('AdaApi::redeemAda error', { error });
if (error.message === 'CannotCreateAddress') {
throw new IncorrectSpendingPasswordError();
}
throw new RedeemAdaError();
}
};
redeemPaperVendedAda = async (
request: RedeemPaperVendedAdaParams
): Promise<WalletTransaction> => {
Logger.debug('AdaApi::redeemAdaPaperVend called', { parameters: filterLogData(request) });
const { spendingPassword: passwordString } = request;
const spendingPassword = passwordString ? encryptPassphrase(passwordString) : '';
try {
const transaction: Transaction = await redeemPaperVendedAda(
this.config, { ...request, spendingPassword }
);
Logger.debug('AdaApi::redeemAdaPaperVend success', { transaction });
return _createTransactionFromServerData(transaction);
} catch (error) {
Logger.error('AdaApi::redeemAdaPaperVend error', { error });
if (error.message === 'CannotCreateAddress') {
throw new IncorrectSpendingPasswordError();
}
throw new RedeemAdaError();
}
};
nextUpdate = async (): Promise<NodeSoftware | null> => {
Logger.debug('AdaApi::nextUpdate called');
try {
const nodeUpdate = await getNextNodeUpdate(this.config);
if (nodeUpdate && nodeUpdate.version) {
Logger.debug('AdaApi::nextUpdate success', { nodeUpdate });
return nodeUpdate;
}
Logger.debug('AdaApi::nextUpdate success: No Update Available');
} catch (error) {
Logger.error('AdaApi::nextUpdate error', { error });
throw new GenericApiError();
}
return null;
};
postponeUpdate = async (): Promise<void> => {
Logger.debug('AdaApi::postponeUpdate called');
try {
const response: Promise<any> = await postponeNodeUpdate(this.config);
Logger.debug('AdaApi::postponeUpdate success', { response });
} catch (error) {
Logger.error('AdaApi::postponeUpdate error', { error });
throw new GenericApiError();
}
};
applyUpdate = async (): Promise<void> => {
Logger.debug('AdaApi::applyUpdate called');
try {
await awaitUpdateChannel.send();
const response: Promise<any> = await applyNodeUpdate(this.config);
Logger.debug('AdaApi::applyUpdate success', { response });
} catch (error) {
Logger.error('AdaApi::applyUpdate error', { error });
throw new GenericApiError();
}
};
updateWallet = async (request: UpdateWalletRequest): Promise<Wallet> => {
Logger.debug('AdaApi::updateWallet called', { parameters: filterLogData(request) });
const { walletId, assuranceLevel, name } = request;
try {
const wallet: AdaWallet = await updateWallet(
this.config, { walletId, assuranceLevel, name }
);
Logger.debug('AdaApi::updateWallet success', { wallet });
return _createWalletFromServerData(wallet);
} catch (error) {
Logger.error('AdaApi::updateWallet error', { error });
throw new GenericApiError();
}
};
updateSpendingPassword = async (
request: UpdateSpendingPasswordRequest
): Promise<boolean> => {
Logger.debug('AdaApi::updateSpendingPassword called', { parameters: filterLogData(request) });
const { walletId, oldPassword, newPassword } = request;
try {
await changeSpendingPassword(this.config, { walletId, oldPassword, newPassword });
Logger.debug('AdaApi::updateSpendingPassword success');
return true;
} catch (error) {
Logger.error('AdaApi::updateSpendingPassword error', { error });
const errorMessage = get(error, 'diagnostic.msg', '');
if (errorMessage.includes('UpdateWalletPasswordOldPasswordMismatch')) {
throw new IncorrectSpendingPasswordError();
}
throw new GenericApiError();
}
};
exportWalletToFile = async (
request: ExportWalletToFileRequest
): Promise<[]> => {
const { walletId, filePath } = request;
Logger.debug('AdaApi::exportWalletToFile called', { parameters: filterLogData(request) });
try {
const response: Promise<[]> = await exportWalletAsJSON(
this.config, { walletId, filePath }
);
Logger.debug('AdaApi::exportWalletToFile success', { response });
return response;
} catch (error) {
Logger.error('AdaApi::exportWalletToFile error', { error });
throw new GenericApiError();
}
};
testReset = async (): Promise<void> => {
Logger.debug('AdaApi::testReset called');
try {
const response: Promise<void> = await resetWalletState(this.config);
Logger.debug('AdaApi::testReset success');
return response;
} catch (error) {
Logger.error('AdaApi::testReset error', { error });
throw new GenericApiError();
}
};
getNetworkStatus = async (
queryParams?: NodeQueryParams
): Promise<GetNetworkStatusResponse> => {
const isForceNTPCheck = !!queryParams;
const loggerText = `AdaApi::getNetworkStatus${isForceNTPCheck ? ' (FORCE-NTP-CHECK)' : ''}`;
Logger.debug(`${loggerText} called`);
try {
const status: NodeInfo = await getNodeInfo(this.config, queryParams);
Logger.debug(`${loggerText} success`, { status });
const {
blockchainHeight,
subscriptionStatus,
syncProgress,
localBlockchainHeight,
localTimeInformation,
} = status;
// extract relevant data before sending to NetworkStatusStore
return {
subscriptionStatus,
syncProgress: syncProgress.quantity,
blockchainHeight: get(blockchainHeight, 'quantity', 0),
localBlockchainHeight: localBlockchainHeight.quantity,
localTimeDifference: get(localTimeInformation, 'differenceFromNtpServer.quantity', null),
};
} catch (error) {
Logger.error(`${loggerText} error`, { error });
throw new GenericApiError(error);
}
};
setCardanoNodeFault = async (fault: FaultInjectionIpcRequest) => {
await cardanoFaultInjectionChannel.send(fault);
};
// No implementation here but can be overwritten
getLocalTimeDifference: Function;
setLocalTimeDifference: Function;
setNextUpdate: Function;
}
// ========== TRANSFORM SERVER DATA INTO FRONTEND MODELS =========
const _createWalletFromServerData = action(
'AdaApi::_createWalletFromServerData', (data: AdaWallet) => {
const {
id, balance, name, assuranceLevel,
hasSpendingPassword, spendingPasswordLastUpdate,
syncState,
} = data;
return new Wallet({
id,
amount: new BigNumber(balance).dividedBy(LOVELACES_PER_ADA),
name,
assurance: assuranceLevel,
hasPassword: hasSpendingPassword,
passwordUpdateDate: new Date(`${spendingPasswordLastUpdate}Z`),
syncState,
});
}
);
const _createAddressFromServerData = action(
'AdaApi::_createAddressFromServerData',
(address: Address) => new WalletAddress(address)
);
const _conditionToTxState = (condition: string) => {
switch (condition) {
case 'applying':
case 'creating': return 'pending';
case 'wontApply': return 'failed';
default: return 'ok';
// Others V0: CPtxInBlocks && CPtxNotTracked
// Others V1: "inNewestBlocks" "persisted" "creating"
}
};
const _createTransactionFromServerData = action(
'AdaApi::_createTransactionFromServerData', (data: Transaction) => {
const { id, direction, amount, confirmations, creationTime, inputs, outputs, status } = data;
return new WalletTransaction({
id,
title: direction === 'outgoing' ? 'Ada sent' : 'Ada received',
type: direction === 'outgoing' ? transactionTypes.EXPEND : transactionTypes.INCOME,
amount: new BigNumber(direction === 'outgoing' ? (amount * -1) : amount).dividedBy(LOVELACES_PER_ADA),
date: utcStringToDate(creationTime),
description: '',
numberOfConfirmations: Math.min(confirmations, MAX_TRANSACTION_CONFIRMATIONS + 1),
addresses: {
from: inputs.map(({ address }) => address),
to: outputs.map(({ address }) => address),
},
state: _conditionToTxState(status.tag),
});
}
);
const _createTransactionFeeFromServerData = action(
'AdaApi::_createTransactionFeeFromServerData', (data: TransactionFee) => (
new BigNumber(data.estimatedAmount).dividedBy(LOVELACES_PER_ADA)
)
);