-
Notifications
You must be signed in to change notification settings - Fork 55
/
SingleAddressWallet.ts
271 lines (264 loc) · 9.17 KB
/
SingleAddressWallet.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
import { AddressType, GroupedAddress, KeyAgent } from './KeyManagement';
import {
AssetProvider,
BigIntMath,
Cardano,
NetworkInfo,
ProtocolParametersRequiredByWallet,
StakePoolSearchProvider,
WalletProvider,
coreToCsl
} from '@cardano-sdk/core';
import { Assets, InitializeTxResult } from '.';
import {
Balance,
BehaviorObservable,
DelegationTracker,
FailedTx,
PollingConfig,
SyncableIntervalTrackerSubject,
TrackerSubject,
TransactionFailure,
TransactionalTracker,
TransactionsTracker,
coldObservableProvider,
createAssetsTracker,
createBalanceTracker,
createDelegationTracker,
createTransactionsTracker,
createUtxoTracker,
distinctBlock,
distinctEpoch
} from './services';
import { InitializeTxProps, InitializeTxPropsValidationResult, MinimumCoinQuantity, Wallet } from './types';
import {
InputSelector,
computeMinimumCoinQuantity,
defaultSelectionConstraints,
roundRobinRandomImprove
} from '@cardano-sdk/cip2';
import { Logger, dummyLogger } from 'ts-log';
import { Observable, Subject, combineLatest, firstValueFrom, lastValueFrom, map, take } from 'rxjs';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TxInternals, computeImplicitCoin, createTransactionInternals, ensureValidityInterval } from './Transaction';
import { isEqual } from 'lodash-es';
export interface SingleAddressWalletProps {
readonly name: string;
readonly polling?: PollingConfig;
readonly address?: GroupedAddress;
readonly retryBackoffConfig?: RetryBackoffConfig;
}
export interface SingleAddressWalletDependencies {
readonly keyAgent: KeyAgent;
readonly walletProvider: WalletProvider;
readonly stakePoolSearchProvider: StakePoolSearchProvider;
readonly assetProvider: AssetProvider;
readonly inputSelector?: InputSelector;
readonly logger?: Logger;
}
export class SingleAddressWallet implements Wallet {
#inputSelector: InputSelector;
#keyAgent: KeyAgent;
#walletProvider: WalletProvider;
#logger: Logger;
#tip$: SyncableIntervalTrackerSubject<Cardano.Tip>;
#newTransactions = {
failedToSubmit$: new Subject<FailedTx>(),
pending$: new Subject<Cardano.NewTxAlonzo>(),
submitting$: new Subject<Cardano.NewTxAlonzo>()
};
utxo: TransactionalTracker<Cardano.Utxo[]>;
balance: TransactionalTracker<Balance>;
transactions: TransactionsTracker;
delegation: DelegationTracker;
tip$: BehaviorObservable<Cardano.Tip>;
networkInfo$: TrackerSubject<NetworkInfo>;
addresses$: TrackerSubject<GroupedAddress[]>;
protocolParameters$: TrackerSubject<ProtocolParametersRequiredByWallet>;
genesisParameters$: TrackerSubject<Cardano.CompactGenesis>;
assets$: TrackerSubject<Assets>;
name: string;
constructor(
{
name,
polling: { interval: pollInterval = 15_000, maxInterval = 15_000 * 10 } = {},
address,
retryBackoffConfig = {
initialInterval: Math.min(pollInterval, 1000),
maxInterval
}
}: SingleAddressWalletProps,
{
walletProvider,
stakePoolSearchProvider,
keyAgent,
assetProvider,
logger = dummyLogger,
inputSelector = roundRobinRandomImprove()
}: SingleAddressWalletDependencies
) {
this.#logger = logger;
this.#inputSelector = inputSelector;
this.#walletProvider = walletProvider;
this.#keyAgent = keyAgent;
this.addresses$ = new TrackerSubject<GroupedAddress[]>(this.#initializeAddress(address));
this.name = name;
this.#tip$ = this.tip$ = new SyncableIntervalTrackerSubject({
pollInterval,
provider$: coldObservableProvider(walletProvider.ledgerTip, retryBackoffConfig)
});
const tipBlockHeight$ = distinctBlock(this.tip$);
this.networkInfo$ = new TrackerSubject(
coldObservableProvider(walletProvider.networkInfo, retryBackoffConfig, tipBlockHeight$, isEqual)
);
const epoch$ = distinctEpoch(this.networkInfo$);
this.protocolParameters$ = new TrackerSubject(
coldObservableProvider(walletProvider.currentWalletProtocolParameters, retryBackoffConfig, epoch$, isEqual)
);
this.genesisParameters$ = new TrackerSubject(
coldObservableProvider(walletProvider.genesisParameters, retryBackoffConfig, epoch$, isEqual)
);
const addresses$ = this.addresses$.pipe(
map((addresses) => addresses.map((groupedAddress) => groupedAddress.address))
);
this.transactions = createTransactionsTracker({
addresses$,
newTransactions: this.#newTransactions,
retryBackoffConfig,
tip$: this.tip$,
walletProvider
});
this.utxo = createUtxoTracker({
addresses$,
retryBackoffConfig,
tipBlockHeight$,
transactionsInFlight$: this.transactions.outgoing.inFlight$,
walletProvider
});
this.delegation = createDelegationTracker({
epoch$,
retryBackoffConfig,
rewardAccountAddresses$: this.addresses$.pipe(
map((addresses) => addresses.map((groupedAddress) => groupedAddress.rewardAccount))
),
stakePoolSearchProvider,
transactionsTracker: this.transactions,
walletProvider
});
this.balance = createBalanceTracker(this.protocolParameters$, this.utxo, this.delegation);
this.assets$ = new TrackerSubject(
createAssetsTracker({
assetProvider,
balanceTracker: this.balance,
retryBackoffConfig
})
);
}
async validateInitializeTxProps(props: InitializeTxProps): Promise<InitializeTxPropsValidationResult> {
const { coinsPerUtxoWord } = await firstValueFrom(this.protocolParameters$);
const minimumCoinQuantities = new Map<Cardano.TxOut, MinimumCoinQuantity>();
for (const output of props.outputs || []) {
const minimumCoin = BigInt(computeMinimumCoinQuantity(coinsPerUtxoWord)(output.value.assets));
minimumCoinQuantities.set(output, {
coinMissing: BigIntMath.max([minimumCoin - output.value.coins, 0n])!,
minimumCoin
});
}
return { minimumCoinQuantities };
}
async initializeTx(props: InitializeTxProps): Promise<InitializeTxResult> {
const { constraints, utxo, implicitCoin, validityInterval, changeAddress } = await this.#prepareTx(props);
const { selection: inputSelection } = await this.#inputSelector.select({
constraints,
implicitCoin,
outputs: props.outputs || new Set(),
utxo: new Set(utxo)
});
const { body, hash } = await createTransactionInternals({
certificates: props.certificates,
changeAddress,
inputSelection,
validityInterval,
withdrawals: props.withdrawals
});
return { body, hash, inputSelection };
}
async finalizeTx(tx: TxInternals, auxiliaryData?: Cardano.AuxiliaryData): Promise<Cardano.NewTxAlonzo> {
const signatures = await this.#keyAgent.signTransaction(tx);
return {
auxiliaryData,
body: tx.body,
id: tx.hash,
// TODO: add support for the rest of the witness properties
witness: { signatures }
};
}
async submitTx(tx: Cardano.NewTxAlonzo): Promise<void> {
this.#newTransactions.submitting$.next(tx);
try {
await this.#walletProvider.submitTx(coreToCsl.tx(tx).to_bytes());
this.#newTransactions.pending$.next(tx);
} catch (error) {
this.#newTransactions.failedToSubmit$.next({
error: error as Cardano.TxSubmissionError,
reason: TransactionFailure.FailedToSubmit,
tx
});
throw error;
}
}
sync() {
this.#tip$.sync();
}
shutdown() {
this.balance.shutdown();
this.utxo.shutdown();
this.transactions.shutdown();
this.networkInfo$.complete();
this.protocolParameters$.complete();
this.genesisParameters$.complete();
this.#tip$.complete();
this.addresses$.complete();
}
#prepareTx(props: InitializeTxProps) {
return lastValueFrom(
combineLatest([this.tip$, this.utxo.available$, this.protocolParameters$, this.addresses$]).pipe(
take(1),
map(([tip, utxo, protocolParameters, [{ address: changeAddress }]]) => {
const validityInterval = ensureValidityInterval(tip.slot, props.options?.validityInterval);
const constraints = defaultSelectionConstraints({
buildTx: async (inputSelection) => {
this.#logger.debug('Building TX for selection constraints', inputSelection);
const txInternals = await createTransactionInternals({
certificates: props.certificates,
changeAddress,
inputSelection,
validityInterval,
withdrawals: props.withdrawals
});
return coreToCsl.tx(await this.finalizeTx(txInternals));
},
protocolParameters
});
const implicitCoin = computeImplicitCoin(protocolParameters, props);
return { changeAddress, constraints, implicitCoin, utxo, validityInterval };
})
)
);
}
#initializeAddress(existingAddress?: GroupedAddress): Observable<GroupedAddress[]> {
return new Observable((observer) => {
if (existingAddress) {
observer.next([existingAddress]);
return;
}
this.#keyAgent
.deriveAddress({
index: 0,
type: AddressType.External
})
.then((newAddress) => observer.next([newAddress]))
.catch(observer.error);
});
}
}