-
Notifications
You must be signed in to change notification settings - Fork 55
/
RewardsHistory.ts
59 lines (55 loc) · 2 KB
/
RewardsHistory.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
import { BigIntMath, Cardano, WalletProvider, util } from '@cardano-sdk/core';
import { Observable, distinctUntilChanged, map, of, switchMap } from 'rxjs';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TxWithEpoch } from './types';
import { coldObservableProvider } from '../util';
import { first } from 'lodash-es';
import { transactionHasAnyCertificate } from './transactionCertificates';
export const createRewardsHistoryProvider =
(
walletProvider: WalletProvider,
rewardAccountAddresses$: Observable<Cardano.RewardAccount[]>,
retryBackoffConfig: RetryBackoffConfig
) =>
(lowerBound: Cardano.Epoch | null) =>
lowerBound
? rewardAccountAddresses$.pipe(
switchMap((stakeAddresses) =>
coldObservableProvider(
() =>
walletProvider.rewardsHistory({
epochs: { lowerBound },
stakeAddresses
}),
retryBackoffConfig
)
)
)
: of([]);
export type RewardsHistoryProvider = ReturnType<typeof createRewardsHistoryProvider>;
const firstDelegationEpoch$ = (transactions$: Observable<TxWithEpoch[]>) =>
transactions$.pipe(
map((transactions) =>
first(
transactions.filter(({ tx }) => transactionHasAnyCertificate(tx, [Cardano.CertificateType.StakeDelegation]))
)
),
map((tx) => (util.isNotNil(tx) ? tx.epoch + 3 : null)),
distinctUntilChanged()
);
export const createRewardsHistoryTracker = (
transactions$: Observable<TxWithEpoch[]>,
rewardsHistoryProvider: RewardsHistoryProvider
) =>
firstDelegationEpoch$(transactions$).pipe(
switchMap((firstEpoch) => rewardsHistoryProvider(firstEpoch)),
map((all) => {
const lifetimeRewards = BigIntMath.sum(all.map(({ rewards }) => rewards));
return {
all,
avgReward: all.length > 0 ? lifetimeRewards / BigInt(all.length) : null,
lastReward: all.length > 0 ? all[all.length - 1] : null,
lifetimeRewards
};
})
);