-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathBaseWallet.ts
981 lines (895 loc) · 34.1 KB
/
BaseWallet.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
// cSpell:ignore coeff vkeys
/* eslint-disable unicorn/no-nested-ternary */
// eslint-disable-next-line import/no-extraneous-dependencies
import {
AddSignaturesProps,
Assets,
FinalizeTxProps,
HandleInfo,
ObservableWallet,
SignDataProps,
SyncStatus,
WalletAddress,
WalletNetworkInfoProvider,
isTxBodyWithHash
} from '../types';
import {
AddressDiscovery,
AddressTracker,
BalanceTracker,
ConnectionStatus,
ConnectionStatusTracker,
DelegationTracker,
DynamicChangeAddressResolver,
FailedTx,
Milliseconds,
OutgoingTx,
PersistentDocumentTrackerSubject,
PollingConfig,
SmartTxSubmitProvider,
TipTracker,
TrackedAssetProvider,
TrackedChainHistoryProvider,
TrackedRewardAccountInfoProvider,
TrackedRewardsProvider,
TrackedTxSubmitProvider,
TrackedUtxoProvider,
TrackedWalletNetworkInfoProvider,
TransactionFailure,
TransactionsTracker,
UtxoTracker,
WalletUtil,
combineInputResolvers,
createAddressTracker,
createAssetsTracker,
createBalanceTracker,
createDRepRegistrationTracker,
createDelegationTracker,
createHandlesTracker,
createInputResolver,
createProviderStatusTracker,
createSimpleConnectionStatusTracker,
createTransactionReemitter,
createTransactionsTracker,
createUtxoTracker,
createWalletUtil,
currentEpochTracker,
pollProvider
} from '../services';
import { AddressType, Bip32Account, GroupedAddress, WitnessedTx, Witnesser, util } from '@cardano-sdk/key-management';
import {
AssetProvider,
Cardano,
CardanoNodeUtil,
ChainHistoryProvider,
EpochInfo,
EraSummary,
HandleProvider,
OutsideOfValidityIntervalData,
ProviderError,
ProviderFailure,
RewardAccountInfoProvider,
RewardsProvider,
Serialization,
TxSubmissionError,
TxSubmissionErrorCode,
TxSubmitProvider,
UtxoProvider
} from '@cardano-sdk/core';
import { BehaviorObservable, TrackerSubject } from '@cardano-sdk/util-rxjs';
import {
BehaviorSubject,
EMPTY,
Observable,
Subject,
Subscription,
catchError,
defaultIfEmpty,
defer,
distinctUntilChanged,
filter,
firstValueFrom,
from,
map,
mergeMap,
of,
shareReplay,
switchMap,
take,
tap,
throwError
} from 'rxjs';
import { ChangeAddressResolver, InputSelector, roundRobinRandomImprove } from '@cardano-sdk/input-selection';
import { Cip30DataSignature } from '@cardano-sdk/dapp-connector';
import { Ed25519PublicKey, Ed25519PublicKeyHex } from '@cardano-sdk/crypto';
import {
GenericTxBuilder,
GreedyTxEvaluator,
InitializeTxProps,
InitializeTxResult,
InvalidConfigurationError,
TxBuilderDependencies,
initializeTx
} from '@cardano-sdk/tx-construction';
import { Logger } from 'ts-log';
import { PubStakeKeyAndStatus, createPublicStakeKeysTracker } from '../services/PublicStakeKeysTracker';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { Shutdown, contextLogger, deepEquals } from '@cardano-sdk/util';
import { WalletStores, createInMemoryWalletStores } from '../persistence';
import { getScriptAddress } from './internals';
import { onlyDistinctBlockRefetch } from '../services/DrepInfoTracker';
import isEqual from 'lodash/isEqual.js';
import uniq from 'lodash/uniq.js';
export interface BaseWalletProps {
readonly name: string;
readonly historicalTransactionsFetchLimit?: number;
readonly polling?: PollingConfig;
readonly retryBackoffConfig?: RetryBackoffConfig;
readonly maxAssetInfoCacheAge?: Milliseconds;
}
export enum PublicCredentialsManagerType {
SCRIPT_CREDENTIALS_MANAGER = 'SCRIPT_CREDENTIALS_MANAGER',
BIP32_CREDENTIALS_MANAGER = 'BIP32_CREDENTIALS_MANAGER'
}
export interface Bip32PublicCredentialsManager {
__type: PublicCredentialsManagerType.BIP32_CREDENTIALS_MANAGER;
bip32Account: Bip32Account;
addressDiscovery: AddressDiscovery;
}
export interface ScriptPublicCredentialsManager {
__type: PublicCredentialsManagerType.SCRIPT_CREDENTIALS_MANAGER;
paymentScript: Cardano.RequireAllOfScript | Cardano.RequireAnyOfScript | Cardano.RequireAtLeastScript;
stakingScript: Cardano.RequireAllOfScript | Cardano.RequireAnyOfScript | Cardano.RequireAtLeastScript;
}
export type PublicCredentialsManager = ScriptPublicCredentialsManager | Bip32PublicCredentialsManager;
export const isScriptPublicCredentialsManager = (
credManager: PublicCredentialsManager
): credManager is ScriptPublicCredentialsManager =>
credManager.__type === PublicCredentialsManagerType.SCRIPT_CREDENTIALS_MANAGER;
export const isBip32PublicCredentialsManager = (
credManager: PublicCredentialsManager
): credManager is Bip32PublicCredentialsManager => !isScriptPublicCredentialsManager(credManager);
/**
* Gets whether the given address has a transaction history.
*
* @param address The address to query.
* @param chainHistoryProvider The chain history provider where to fetch the history from.
*/
const addressHasTx = async (
address: Cardano.PaymentAddress,
chainHistoryProvider: ChainHistoryProvider
): Promise<boolean> => {
const txs = await chainHistoryProvider.transactionsByAddresses({
addresses: [address],
pagination: {
limit: 1,
startAt: 0
}
});
return txs.totalResultCount > 0;
};
export interface BaseWalletDependencies {
readonly witnesser: Witnesser;
readonly txSubmitProvider: TxSubmitProvider;
readonly assetProvider: AssetProvider;
readonly handleProvider?: HandleProvider;
readonly networkInfoProvider: WalletNetworkInfoProvider;
readonly utxoProvider: UtxoProvider;
readonly chainHistoryProvider: ChainHistoryProvider;
readonly rewardAccountInfoProvider: RewardAccountInfoProvider;
readonly rewardsProvider: RewardsProvider;
readonly inputSelector?: InputSelector;
readonly stores?: WalletStores;
readonly logger: Logger;
readonly connectionStatusTracker$?: ConnectionStatusTracker;
readonly publicCredentialsManager: PublicCredentialsManager;
readonly inputResolver?: Cardano.InputResolver;
/** control whether tip tracker should be polling */
readonly pollController$?: Observable<boolean>;
}
export interface SubmitTxOptions {
mightBeAlreadySubmitted?: boolean;
}
export const DEFAULT_POLLING_CONFIG = {
maxInterval: 5000 * 20,
maxIntervalMultiplier: 20,
pollInterval: 5000
};
// Adjust the number of slots to wait until a transaction is considered lost (send but not found on chain)
// Configured to 2.5 because on preprod/mainnet, blocks produced at more than 250 slots apart are very rare (1 per epoch or less).
// Ideally we should calculate this based on the activeSlotsCoeff and probability of a single block per epoch.
const BLOCK_SLOT_GAP_MULTIPLIER = 2.5;
const isOutgoingTx = (input: Cardano.Tx | Serialization.TxCBOR | OutgoingTx | WitnessedTx): input is OutgoingTx =>
typeof input === 'object' && 'cbor' in input;
const isTxCBOR = (input: Cardano.Tx | Serialization.TxCBOR | OutgoingTx | WitnessedTx): input is Serialization.TxCBOR =>
typeof input === 'string';
const isWitnessedTx = (input: Cardano.Tx | Serialization.TxCBOR | OutgoingTx | WitnessedTx): input is WitnessedTx =>
typeof input === 'object' && 'context' in input;
const processOutgoingTx = (input: Cardano.Tx | Serialization.TxCBOR | OutgoingTx | WitnessedTx): OutgoingTx => {
// TxCbor
if (isTxCBOR(input)) {
const tx = Serialization.Transaction.fromCbor(input);
return {
body: tx.toCore().body,
cbor: input,
// Do not re-serialize transaction body to compute transaction id
id: tx.getId()
};
}
// WitnessedTx
if (isWitnessedTx(input)) {
return {
body: input.tx.body,
cbor: input.cbor,
context: input.context,
// Do not re-serialize transaction body to compute transaction id
id: input.tx.id
};
}
// OutgoingTx (resubmitted)
if (isOutgoingTx(input)) {
return input;
}
return {
body: input.body,
cbor: Serialization.TxCBOR.serialize(input),
id: input.id
};
};
const getDRepKeyHash = async (dRepKey: Ed25519PublicKeyHex | undefined) =>
dRepKey ? (await Ed25519PublicKey.fromHex(dRepKey).hash()).hex() : undefined;
export class BaseWallet implements ObservableWallet {
#inputResolver: Cardano.InputResolver | undefined;
#inputSelector: InputSelector;
#logger: Logger;
#tip$: TipTracker;
#newTransactions = {
failedToSubmit$: new Subject<FailedTx>(),
pending$: new Subject<OutgoingTx>(),
signed$: new Subject<WitnessedTx>(),
submitting$: new Subject<OutgoingTx>()
};
#reemitSubscriptions: Subscription;
#failedFromReemitter$: Subject<FailedTx>;
#trackedTxSubmitProvider: TrackedTxSubmitProvider;
#addressTracker: AddressTracker;
#publicCredentialsManager: PublicCredentialsManager;
#submittingPromises: Partial<Record<Cardano.TransactionId, Promise<Cardano.TransactionId>>> = {};
#refetchRewardAccountInfo$ = new Subject<void>();
readonly witnesser: Witnesser;
readonly currentEpoch$: TrackerSubject<EpochInfo>;
readonly txSubmitProvider: TxSubmitProvider;
readonly utxoProvider: TrackedUtxoProvider;
readonly networkInfoProvider: TrackedWalletNetworkInfoProvider;
readonly rewardAccountInfoProvider: TrackedRewardAccountInfoProvider;
readonly assetProvider: TrackedAssetProvider;
readonly chainHistoryProvider: TrackedChainHistoryProvider;
readonly utxo: UtxoTracker;
readonly balance: BalanceTracker;
readonly transactions: TransactionsTracker & Shutdown;
readonly delegation: DelegationTracker & Shutdown;
readonly tip$: BehaviorObservable<Cardano.Tip>;
readonly eraSummaries$: TrackerSubject<EraSummary[]>;
readonly addresses$: Observable<GroupedAddress[]>;
readonly protocolParameters$: TrackerSubject<Cardano.ProtocolParameters>;
readonly genesisParameters$: TrackerSubject<Cardano.CompactGenesis>;
readonly assetInfo$: TrackerSubject<Assets>;
readonly syncStatus: SyncStatus;
readonly name: string;
readonly util: WalletUtil;
readonly rewardsProvider: TrackedRewardsProvider;
readonly handleProvider: HandleProvider;
readonly changeAddressResolver: ChangeAddressResolver;
readonly publicStakeKeys$: TrackerSubject<PubStakeKeyAndStatus[]>;
readonly governance: {
readonly isRegisteredAsDRep$: Observable<boolean>;
getPubDRepKey(): Promise<Ed25519PublicKeyHex | undefined>;
};
handles$: Observable<HandleInfo[]>;
// eslint-disable-next-line max-statements
constructor(
{
name,
historicalTransactionsFetchLimit = 10,
maxAssetInfoCacheAge,
polling: {
interval: pollInterval = DEFAULT_POLLING_CONFIG.pollInterval,
maxInterval = pollInterval * DEFAULT_POLLING_CONFIG.maxIntervalMultiplier,
consideredOutOfSyncAfter = 1000 * 60 * 3
} = {},
retryBackoffConfig = {
initialInterval: Math.min(pollInterval, 1000),
maxInterval
}
}: BaseWalletProps,
{
txSubmitProvider,
witnesser,
assetProvider,
handleProvider,
networkInfoProvider,
utxoProvider,
chainHistoryProvider,
rewardAccountInfoProvider,
rewardsProvider,
logger,
inputSelector,
publicCredentialsManager,
stores = createInMemoryWalletStores(),
connectionStatusTracker$ = createSimpleConnectionStatusTracker(),
inputResolver,
pollController$ = of(true)
}: BaseWalletDependencies
) {
this.#logger = contextLogger(logger, name);
this.#publicCredentialsManager = publicCredentialsManager;
this.#trackedTxSubmitProvider = new TrackedTxSubmitProvider(txSubmitProvider);
this.utxoProvider = new TrackedUtxoProvider(utxoProvider);
this.networkInfoProvider = new TrackedWalletNetworkInfoProvider(networkInfoProvider);
this.assetProvider = new TrackedAssetProvider(assetProvider);
this.handleProvider = handleProvider as HandleProvider;
this.chainHistoryProvider = new TrackedChainHistoryProvider(chainHistoryProvider);
this.rewardAccountInfoProvider = new TrackedRewardAccountInfoProvider(rewardAccountInfoProvider);
this.rewardsProvider = new TrackedRewardsProvider(rewardsProvider);
this.syncStatus = createProviderStatusTracker(
{
assetProvider: this.assetProvider,
chainHistoryProvider: this.chainHistoryProvider,
logger: contextLogger(this.#logger, 'syncStatus'),
networkInfoProvider: this.networkInfoProvider,
rewardAccountInfoProvider: this.rewardAccountInfoProvider,
rewardsProvider: this.rewardsProvider,
utxoProvider: this.utxoProvider
},
{ consideredOutOfSyncAfter }
);
this.witnesser = witnesser;
this.name = name;
const cancel$ = connectionStatusTracker$.pipe(
tap((status) => (status === ConnectionStatus.up ? 'Connection UP' : 'Connection DOWN')),
filter((status) => status === ConnectionStatus.down)
);
if (isBip32PublicCredentialsManager(this.#publicCredentialsManager)) {
this.#addressTracker = createAddressTracker({
addressDiscovery$: pollProvider({
cancel$,
logger: contextLogger(this.#logger, 'addressDiscovery$'),
retryBackoffConfig,
sample: () => {
const credManager = this.#publicCredentialsManager as Bip32PublicCredentialsManager;
return credManager.addressDiscovery.discover(credManager.bip32Account);
}
}).pipe(
take(1),
catchError((error) => {
this.#logger.error('Failed to complete the address discovery process', error);
throw error;
})
),
logger: this.#logger,
store: stores.addresses
});
this.addresses$ = this.#addressTracker.addresses$;
} else {
const credManager = this.#publicCredentialsManager as ScriptPublicCredentialsManager;
this.addresses$ = from(this.networkInfoProvider.genesisParameters()).pipe(
map(({ networkId }) => networkId),
distinctUntilChanged(),
map((networkId) => [getScriptAddress(credManager.paymentScript, credManager.stakingScript, networkId)])
);
}
this.#tip$ = this.tip$ = new TipTracker({
connectionStatus$: connectionStatusTracker$,
logger: contextLogger(this.#logger, 'tip$'),
maxPollInterval: maxInterval,
minPollInterval: pollInterval,
pollController$,
provider$: pollProvider({
cancel$,
logger: contextLogger(this.#logger, 'tip$'),
retryBackoffConfig,
sample: this.networkInfoProvider.ledgerTip
}),
store: stores.tip,
syncStatus: this.syncStatus
});
this.txSubmitProvider = new SmartTxSubmitProvider(
{ retryBackoffConfig },
{
connectionStatus$: connectionStatusTracker$,
tip$: this.tip$,
txSubmitProvider: this.#trackedTxSubmitProvider
}
);
// Era summaries
const eraSummariesTrigger = new BehaviorSubject<void>(void 0);
this.eraSummaries$ = new PersistentDocumentTrackerSubject(
pollProvider({
cancel$,
equals: deepEquals,
logger: contextLogger(this.#logger, 'eraSummaries$'),
retryBackoffConfig,
sample: this.networkInfoProvider.eraSummaries,
trigger$: eraSummariesTrigger.pipe(tap(() => 'Trigger request era summaries'))
}),
stores.eraSummaries
);
// Epoch tracker triggers the first eraSummaries fetch from eraSummariesTrigger
// Epoch changes also trigger refetch of eraSummaries
this.currentEpoch$ = currentEpochTracker(
this.tip$,
this.eraSummaries$.pipe(tap((es) => this.#logger.debug('Era summaries are', es)))
);
this.currentEpoch$.pipe(map(() => void 0)).subscribe(eraSummariesTrigger);
const epoch$ = this.currentEpoch$.pipe(
map((epoch) => epoch.epochNo),
tap((epoch) => this.#logger.debug(`Current epoch is ${epoch}`))
);
this.protocolParameters$ = new PersistentDocumentTrackerSubject(
pollProvider({
cancel$,
equals: isEqual,
logger: contextLogger(this.#logger, 'protocolParameters$'),
retryBackoffConfig,
sample: this.networkInfoProvider.protocolParameters,
trigger$: epoch$
}),
stores.protocolParameters
);
this.genesisParameters$ = new PersistentDocumentTrackerSubject(
pollProvider({
cancel$,
equals: isEqual,
logger: contextLogger(this.#logger, 'genesisParameters$'),
retryBackoffConfig,
sample: this.networkInfoProvider.genesisParameters,
trigger$: epoch$
}),
stores.genesisParameters
);
const addresses$ = this.addresses$.pipe(
map((addresses) => addresses.map((groupedAddress) => groupedAddress.address)),
distinctUntilChanged(deepEquals),
shareReplay(1)
);
this.#failedFromReemitter$ = new Subject<FailedTx>();
this.transactions = createTransactionsTracker({
addresses$,
chainHistoryProvider: this.chainHistoryProvider,
failedFromReemitter$: this.#failedFromReemitter$,
historicalTransactionsFetchLimit,
inFlightTransactionsStore: stores.inFlightTransactions,
logger: contextLogger(this.#logger, 'transactions'),
newTransactions: this.#newTransactions,
retryBackoffConfig,
signedTransactionsStore: stores.signedTransactions,
tip$: this.tip$,
transactionsHistoryStore: stores.transactions
});
const transactionsReemitter = createTransactionReemitter({
genesisParameters$: this.genesisParameters$,
logger: contextLogger(this.#logger, 'transactionsReemitter'),
maxInterval: maxInterval * BLOCK_SLOT_GAP_MULTIPLIER,
stores,
tipSlot$: this.tip$.pipe(map((tip) => tip.slot)),
transactions: this.transactions
});
this.#reemitSubscriptions = new Subscription();
this.#reemitSubscriptions.add(transactionsReemitter.failed$.subscribe(this.#failedFromReemitter$));
this.#reemitSubscriptions.add(
transactionsReemitter.reemit$
.pipe(
mergeMap((tx) => from(this.submitTx(tx, { mightBeAlreadySubmitted: true }))),
catchError((err) => {
this.#logger.error('Failed to resubmit transaction', err);
return EMPTY;
})
)
.subscribe()
);
this.utxo = createUtxoTracker({
addresses$,
history$: this.transactions.history$,
logger: contextLogger(this.#logger, 'utxo'),
retryBackoffConfig,
stores,
transactionsInFlight$: this.transactions.outgoing.inFlight$,
utxoProvider: this.utxoProvider
});
this.delegation = createDelegationTracker({
epoch$,
knownAddresses$: this.addresses$,
logger: contextLogger(this.#logger, 'delegation'),
protocolParameters$: this.protocolParameters$,
refetchRewardAccountInfo$: onlyDistinctBlockRefetch(this.#refetchRewardAccountInfo$, this.tip$),
retryBackoffConfig,
rewardAccountAddresses$: this.addresses$.pipe(
map((addresses) => uniq(addresses.map((groupedAddress) => groupedAddress.rewardAccount)))
),
rewardAccountInfoProvider: this.rewardAccountInfoProvider,
rewardsTracker: this.rewardsProvider,
stores,
transactionsTracker: this.transactions,
utxoTracker: this.utxo
});
this.#inputSelector = inputSelector
? inputSelector
: roundRobinRandomImprove({
changeAddressResolver: new DynamicChangeAddressResolver(
this.syncStatus.isSettled$.pipe(
filter((isSettled) => isSettled),
switchMap(() => this.addresses$)
),
this.delegation.distribution$,
() => firstValueFrom(this.delegation.portfolio$),
logger
)
});
this.publicStakeKeys$ = isBip32PublicCredentialsManager(this.#publicCredentialsManager)
? createPublicStakeKeysTracker({
addresses$: this.addresses$,
bip32Account: this.#publicCredentialsManager.bip32Account,
rewardAccounts$: this.delegation.rewardAccounts$
})
: new TrackerSubject(of(new Array<PubStakeKeyAndStatus>()));
this.balance = createBalanceTracker(this.protocolParameters$, this.utxo, this.delegation);
// TODO[LW-11929]: Implement `observe` method in DocumentStore interface.
const assetsCache$ = defer(() => stores.assets.get().pipe(defaultIfEmpty(new Map())));
this.assetInfo$ = new PersistentDocumentTrackerSubject(
createAssetsTracker({
assetProvider: this.assetProvider,
assetsCache$,
balanceTracker: this.balance,
logger: contextLogger(this.#logger, 'assets$'),
maxAssetInfoCacheAge,
retryBackoffConfig,
transactionsTracker: this.transactions
}),
stores.assets
);
this.handles$ = this.handleProvider
? this.initializeHandles(
new PersistentDocumentTrackerSubject(
pollProvider({
cancel$,
equals: isEqual,
logger: contextLogger(this.#logger, 'handles$'),
retryBackoffConfig,
sample: () => this.handleProvider.getPolicyIds()
}),
stores.policyIds
)
)
: throwError(() => new InvalidConfigurationError('BaseWallet is missing a "handleProvider"'));
this.util = createWalletUtil({
chainHistoryProvider: this.chainHistoryProvider,
protocolParameters$: this.protocolParameters$,
transactions: this.transactions,
utxo: this.utxo
});
if (inputResolver) {
this.util.resolveInput = inputResolver.resolveInput.bind(inputResolver);
}
const getPubDRepKey = async (): Promise<Ed25519PublicKeyHex | undefined> => {
if (isBip32PublicCredentialsManager(this.#publicCredentialsManager)) {
return (await this.#publicCredentialsManager.bip32Account.derivePublicKey(util.DREP_KEY_DERIVATION_PATH)).hex();
}
return undefined;
};
this.governance = {
getPubDRepKey,
isRegisteredAsDRep$: createDRepRegistrationTracker({
historyTransactions$: this.transactions.history$,
pubDRepKeyHash$: from(getPubDRepKey().then(getDRepKeyHash))
})
};
if (inputResolver) {
this.#inputResolver = combineInputResolvers(createInputResolver(this), inputResolver);
this.util.resolveInput = this.#inputResolver?.resolveInput.bind(this.#inputResolver);
}
this.#logger.debug('Created');
}
async getName(): Promise<string> {
return this.name;
}
async initializeTx(props: InitializeTxProps): Promise<InitializeTxResult> {
return initializeTx(props, this.getTxBuilderDependencies());
}
async finalizeTx({
tx,
bodyCbor,
signingOptions,
signingContext,
auxiliaryData,
isValid,
witness
}: FinalizeTxProps): Promise<Cardano.Tx> {
const knownAddresses = await firstValueFrom(this.addresses$);
const dRepPublicKey = await this.governance.getPubDRepKey();
const emptyWitness = { signatures: new Map() };
let transaction: Serialization.Transaction;
if (isTxBodyWithHash(tx)) {
// Reconstruct transaction from parts
transaction = new Serialization.Transaction(
bodyCbor ? Serialization.TransactionBody.fromCbor(bodyCbor) : Serialization.TransactionBody.fromCore(tx.body),
Serialization.TransactionWitnessSet.fromCore({ ...emptyWitness, ...witness }),
auxiliaryData ? Serialization.AuxiliaryData.fromCore(auxiliaryData) : undefined
);
if (isValid !== undefined) transaction.setIsValid(isValid);
} else {
// Transaction CBOR is available. Use as is.
transaction = Serialization.Transaction.fromCbor(tx);
}
const context = {
...signingContext,
dRepPublicKey,
knownAddresses,
txInKeyPathMap: await util.createTxInKeyPathMap(transaction.body().toCore(), knownAddresses, this.util)
};
const result = await this.witnesser.witness(transaction, context, signingOptions);
this.#newTransactions.signed$.next(result);
return result.tx;
}
private initializeHandles(handlePolicyIds$: Observable<Cardano.PolicyId[]>): Observable<HandleInfo[]> {
return createHandlesTracker({
assetInfo$: this.assetInfo$,
handlePolicyIds$,
handleProvider: this.handleProvider,
logger: contextLogger(this.#logger, 'handles$'),
utxo$: this.utxo.total$
});
}
createTxBuilder() {
return new GenericTxBuilder(this.getTxBuilderDependencies());
}
// eslint-disable-next-line complexity
async #submitTx(
outgoingTx: OutgoingTx,
{ mightBeAlreadySubmitted }: SubmitTxOptions = {}
): Promise<Cardano.TransactionId> {
this.#logger.debug(`Submitting transaction ${outgoingTx.id}`);
// TODO: Workaround while we resolve LW-12394
const { validityInterval } = outgoingTx.body;
if (validityInterval?.invalidHereafter) {
const slot = await firstValueFrom(this.tip$.pipe(map((tip) => tip.slot)));
if (slot >= validityInterval?.invalidHereafter) {
const data: OutsideOfValidityIntervalData = {
currentSlot: slot,
validityInterval: {
invalidBefore: validityInterval?.invalidBefore,
invalidHereafter: validityInterval?.invalidHereafter
}
};
throw new ProviderError(
ProviderFailure.BadRequest,
new TxSubmissionError(
TxSubmissionErrorCode.OutsideOfValidityInterval,
data,
'Not submitting transaction due to validity interval'
)
);
}
}
this.#newTransactions.submitting$.next(outgoingTx);
try {
await this.txSubmitProvider.submitTx({
context: outgoingTx.context,
signedTransaction: outgoingTx.cbor
});
const { slot: submittedAt } = await firstValueFrom(this.tip$);
this.#logger.debug(`Submitted transaction ${outgoingTx.id} at slot ${submittedAt}`);
this.#newTransactions.pending$.next(outgoingTx);
return outgoingTx.id;
} catch (error) {
if (
mightBeAlreadySubmitted &&
CardanoNodeUtil.isProviderError(error) &&
// Review: not sure if those 2 errors cover the original ones: there is no longer a CollectErrorsError or BadInputsError
((CardanoNodeUtil.isValueNotConservedError(error.innerError) &&
// error.innerError.data is not set by cardano submit api. It is only set when error is coming from Ogmios.
(!error.innerError?.data || error.innerError.data.produced.coins === 0n)) ||
// TODO: check if IncompleteWithdrawals available withdrawal amount === wallet's reward acc balance?
// Not sure what the 'Withdrawals' in error data is exactly: value being withdrawn, or reward acc balance
CardanoNodeUtil.isIncompleteWithdrawalsError(error.innerError) ||
CardanoNodeUtil.isUnknownOutputReferences(error.innerError) ||
CardanoNodeUtil.isCredentialAlreadyRegistered(error.innerError) ||
CardanoNodeUtil.isDrepAlreadyRegistered(error.innerError) ||
CardanoNodeUtil.isUnknownCredential(error.innerError) ||
CardanoNodeUtil.isDrepNotRegistered(error.innerError))
) {
this.#logger.debug(
`Transaction ${outgoingTx.id} failed with ${error.innerError}, but it appears to be already submitted...`
);
this.#newTransactions.pending$.next(outgoingTx);
return outgoingTx.id;
}
this.#newTransactions.failedToSubmit$.next({
error,
reason: TransactionFailure.FailedToSubmit,
...outgoingTx
});
throw error;
}
}
async submitTx(
input: Cardano.Tx | Serialization.TxCBOR | OutgoingTx | WitnessedTx,
options: SubmitTxOptions = {}
): Promise<Cardano.TransactionId> {
const outgoingTx = processOutgoingTx(input);
if (this.#submittingPromises[outgoingTx.id]) {
return this.#submittingPromises[outgoingTx.id]!;
}
return (this.#submittingPromises[outgoingTx.id] = (async () => {
try {
// Submit to provider only if it's either:
// - an internal re-submission. External re-submissions are ignored,
// because BaseWallet takes care of it internally.
// - is a new submission
if (options.mightBeAlreadySubmitted || !(await this.#isTxInFlight(outgoingTx.id))) {
await this.#submitTx(outgoingTx, options);
}
} finally {
delete this.#submittingPromises[outgoingTx.id];
}
return outgoingTx.id;
})());
}
sync() {
this.#tip$.sync();
}
shutdown() {
this.utxo.shutdown();
this.transactions.shutdown();
this.eraSummaries$.complete();
this.protocolParameters$.complete();
this.genesisParameters$.complete();
this.#tip$.complete();
this.#addressTracker?.shutdown();
this.assetProvider.stats.shutdown();
this.#trackedTxSubmitProvider.stats.shutdown();
this.networkInfoProvider.stats.shutdown();
this.utxoProvider.stats.shutdown();
this.rewardAccountInfoProvider.stats.shutdown();
this.rewardsProvider.stats.shutdown();
this.chainHistoryProvider.stats.shutdown();
this.currentEpoch$.complete();
this.delegation.shutdown();
this.assetInfo$.complete();
this.syncStatus.shutdown();
this.#newTransactions.failedToSubmit$.complete();
this.#newTransactions.pending$.complete();
this.#newTransactions.submitting$.complete();
this.#reemitSubscriptions.unsubscribe();
this.#failedFromReemitter$.complete();
this.publicStakeKeys$.complete();
this.#refetchRewardAccountInfo$.complete();
this.#logger.debug('Shutdown');
}
/**
* Sets the wallet input selector.
*
* @param selector The input selector to be used.
*/
setInputSelector(selector: InputSelector) {
this.#inputSelector = selector;
}
/** Gets the wallet input selector. */
getInputSelector() {
return this.#inputSelector;
}
async #isTxInFlight(txId: Cardano.TransactionId) {
const inFlightTxs = await firstValueFrom(this.transactions.outgoing.inFlight$);
return inFlightTxs.some((inFlight) => inFlight.id === txId);
}
/**
* Utility function that creates the TxBuilderDependencies based on the BaseWallet observables.
* All dependencies will wait until the wallet is settled before emitting.
*/
getTxBuilderDependencies(): TxBuilderDependencies {
return {
bip32Account: isBip32PublicCredentialsManager(this.#publicCredentialsManager)
? this.#publicCredentialsManager.bip32Account
: undefined,
handleProvider: this.handleProvider,
inputResolver: this.util,
inputSelector: this.#inputSelector,
logger: this.#logger,
outputValidator: this.util,
txBuilderProviders: {
addresses: {
add: (...newAddresses) => firstValueFrom(this.#addressTracker.addAddresses(newAddresses)),
get: () => firstValueFrom(this.addresses$)
},
genesisParameters: () => this.#firstValueFromSettled(this.genesisParameters$),
protocolParameters: () => this.#firstValueFromSettled(this.protocolParameters$),
rewardAccounts: () => {
this.#refetchRewardAccountInfo$.next();
return this.#firstValueFromSettled(this.delegation.rewardAccounts$);
},
tip: () => this.#firstValueFromSettled(this.tip$),
utxoAvailable: () => this.#firstValueFromSettled(this.utxo.available$)
},
txEvaluator: new GreedyTxEvaluator(() => this.#firstValueFromSettled(this.protocolParameters$)),
witnesser: this.witnesser
};
}
#firstValueFromSettled<T>(o$: Observable<T>): Promise<T> {
return firstValueFrom(
this.syncStatus.isSettled$.pipe(
filter((isSettled) => isSettled),
switchMap(() => o$)
)
);
}
async signData(props: SignDataProps): Promise<Cip30DataSignature> {
if (isBip32PublicCredentialsManager(this.#publicCredentialsManager)) {
return await this.witnesser.signData({
...props,
knownAddresses: await firstValueFrom(this.addresses$)
});
}
throw new Error('signData is not supported by script wallets');
}
async discoverAddresses(): Promise<GroupedAddress[]> {
if (isBip32PublicCredentialsManager(this.#publicCredentialsManager)) {
const addresses = await this.#publicCredentialsManager.addressDiscovery.discover(
this.#publicCredentialsManager.bip32Account
);
const knownAddresses = await firstValueFrom(this.addresses$);
const newAddresses = addresses.filter(
({ address }) => !knownAddresses.some((knownAddr) => knownAddr.address === address)
);
await firstValueFrom(this.#addressTracker.addAddresses(newAddresses));
return firstValueFrom(this.addresses$);
}
return firstValueFrom(this.addresses$);
}
async getNextUnusedAddress(): Promise<WalletAddress[]> {
const knownAddresses = await firstValueFrom(this.addresses$);
if (knownAddresses.length === 0) {
throw new Error('No known address found for this wallet');
}
if (isBip32PublicCredentialsManager(this.#publicCredentialsManager)) {
knownAddresses.sort((a, b) => b.index - a.index);
const latestAddress = knownAddresses[0];
let isEmpty = !(await addressHasTx(latestAddress.address, this.chainHistoryProvider));
if (isEmpty) return [latestAddress];
const newAddress = await this.#publicCredentialsManager.bip32Account.deriveAddress(
{ index: latestAddress.index + 1, type: AddressType.External },
0
);
await firstValueFrom(this.#addressTracker.addAddresses([newAddress]));
// Sanity check, make sure the newly generated address is also empty.
isEmpty = !(await addressHasTx(newAddress.address, this.chainHistoryProvider));
if (isEmpty) return [newAddress];
return await this.getNextUnusedAddress();
}
// Script wallet.
const isEmpty = !(await addressHasTx(knownAddresses[0].address, this.chainHistoryProvider));
return isEmpty ? [knownAddresses[0]] : [];
}
async addSignatures({ tx, sender }: AddSignaturesProps): Promise<Serialization.TxCBOR> {
const serializableTx = Serialization.Transaction.fromCbor(tx);
const auxiliaryData = serializableTx.auxiliaryData()?.toCore();
const body = serializableTx.body().toCore();
const hash = serializableTx.getId();
const witness = serializableTx.witnessSet().toCore();
const bodyCbor = serializableTx.body().toCbor();
const witnessedTx = await this.finalizeTx({
auxiliaryData,
bodyCbor,
signingContext: {
sender
},
tx: { body, hash },
witness
});
const coreWitness = witnessedTx.witness;
const witnessSet = serializableTx.witnessSet();
witnessSet.setVkeys(
Serialization.CborSet.fromCore([...coreWitness.signatures], Serialization.VkeyWitness.fromCore)
);
serializableTx.setWitnessSet(witnessSet);
return serializableTx.toCbor();
}
}