Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 | 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 102x 102x 102x 102x 103x 105x 103x 103x 102x 43x 43x 141x 124x 22x 22x 102x 102x 102x 131x 43x 159x 22x 43x 126x 3x 3x 43x 43x 123x 124x 125x 123x 43x 127x 182x 182x 182x 152x 182x 12x 182x 182x 182x 182x 43x 123x 123x 122x 102x 204x 204x 102x 43x 129x 129x 145x 137x 239x 33x 137x 17x 138x 386x 431x 164x 386x 275x 111x 111x 111x 109x 211x 43x 125x 124x 124x 124x 387x 129x 5x 43x 129x 144x 144x 144x 13x 144x 16x 43x 127x 43x 123x 123x 43x 128x 129x 141x 43x 125x 130x 138x 125x 164x 125x 152x 4x 156x 43x 43x 123x 204x 204x 43x 122x 123x | /* eslint-disable unicorn/no-nested-ternary */ import * as Crypto from '@cardano-sdk/crypto'; import { BigIntMath, deepEquals, isNotNil } from '@cardano-sdk/util'; import { Cardano, DRepInfo, RewardsProvider, StakePoolProvider } from '@cardano-sdk/core'; import { EMPTY, Observable, combineLatest, concat, distinctUntilChanged, filter, map, merge, mergeMap, of, pairwise, startWith, switchMap, tap } from 'rxjs'; import { KeyValueStore } from '../../persistence'; import { Logger } from 'ts-log'; import { OutgoingOnChainTx, TxInFlight } from '../types'; import { PAGE_SIZE } from '../TransactionsTracker'; import { RetryBackoffConfig } from 'backoff-rxjs'; import { TrackedStakePoolProvider } from '../ProviderTracker'; import { TxWithEpoch } from './types'; import { drepsToDelegatees, drepsToDrepIds } from '../DrepInfoTracker'; import { lastStakeKeyCertOfType } from './transactionCertificates'; import { pollProvider } from '../util'; import findLast from 'lodash/findLast.js'; import isEqual from 'lodash/isEqual.js'; import uniq from 'lodash/uniq.js'; const allStakePoolsByPoolIds = async ( stakePoolProvider: StakePoolProvider, { poolIds }: { poolIds: Cardano.PoolId[] } ): Promise<Cardano.StakePool[]> => { let startAt = 0; let response: Cardano.StakePool[] = []; let pageResults: Cardano.StakePool[] = []; do { pageResults = ( await stakePoolProvider.queryStakePools({ filters: { identifier: { values: poolIds.map((poolId) => ({ id: poolId })) } }, pagination: { limit: PAGE_SIZE, startAt } }) ).pageResults; startAt += PAGE_SIZE; response = [...response, ...pageResults]; } while (pageResults.length === PAGE_SIZE); return response; }; export const createQueryStakePoolsProvider = ( stakePoolProvider: TrackedStakePoolProvider, store: KeyValueStore<Cardano.PoolId, Cardano.StakePool>, retryBackoffConfig: RetryBackoffConfig, logger: Logger ) => (poolIds: Cardano.PoolId[]) => { if (poolIds.length === 0) { stakePoolProvider.setStatInitialized(stakePoolProvider.stats.queryStakePools$); return of([]); } return merge( store.getValues(poolIds), pollProvider({ logger, retryBackoffConfig, sample: () => allStakePoolsByPoolIds(stakePoolProvider, { poolIds }) }).pipe( tap((pageResults) => { for (const stakePool of pageResults) { store.setValue(stakePool.id, stakePool); } }) ) ); }; export type ObservableStakePoolProvider = ReturnType<typeof createQueryStakePoolsProvider>; const getWithdrawalQuantity = ( withdrawals: Cardano.HydratedTxBody['withdrawals'], rewardAccount?: Cardano.RewardAccount ): Cardano.Lovelace => BigIntMath.sum( withdrawals?.map(({ quantity, stakeAddress }) => (stakeAddress === rewardAccount ? quantity : 0n)) || [] ); export const fetchRewardsTrigger$ = ( epoch$: Observable<Cardano.EpochNo>, txOnChain$: Observable<OutgoingOnChainTx>, rewardAccount: Cardano.RewardAccount ) => merge( // Reload every epoch and after every tx that has withdrawals for this reward account epoch$, txOnChain$.pipe( map(({ body: { withdrawals } }) => getWithdrawalQuantity(withdrawals, rewardAccount)), filter((withdrawalQty) => withdrawalQty > 0n) ) ); export const createRewardsProvider = ( epoch$: Observable<Cardano.EpochNo>, txOnChain$: Observable<OutgoingOnChainTx>, rewardsProvider: RewardsProvider, retryBackoffConfig: RetryBackoffConfig, logger: Logger // eslint-disable-next-line max-params ) => (rewardAccounts: Cardano.RewardAccount[], equals = isEqual): Observable<Cardano.Lovelace[]> => combineLatest( rewardAccounts.map((rewardAccount) => pollProvider({ equals, logger, retryBackoffConfig, sample: () => rewardsProvider.rewardAccountBalance({ rewardAccount }), trigger$: fetchRewardsTrigger$(epoch$, txOnChain$, rewardAccount) }) ) ); export type ObservableRewardsProvider = ReturnType<typeof createRewardsProvider>; const getAccountsCredentialStatus = (addresses: Cardano.RewardAccount[]) => ([transactions, transactionsInFlight]: [TxWithEpoch[], TxInFlight[]]) => { const certificatesInFlight = transactionsInFlight.map(({ body: { certificates } }) => certificates || []); return addresses.map((address) => { const regCert = lastStakeKeyCertOfType( transactions.map( ({ tx: { body: { certificates } } }) => certificates || [] ), Cardano.StakeRegistrationCertificateTypes, address ); let deposit: Cardano.Lovelace | undefined; if (regCert && Cardano.isCertType(regCert, Cardano.PostConwayStakeRegistrationCertificateTypes)) { deposit = regCert.deposit; } const isRegistering = !!lastStakeKeyCertOfType( certificatesInFlight, Cardano.StakeRegistrationCertificateTypes, address ); const isUnregistering = !!lastStakeKeyCertOfType( certificatesInFlight, [Cardano.CertificateType.StakeDeregistration, Cardano.CertificateType.Unregistration], address ); const credentialStatus = isRegistering ? Cardano.StakeCredentialStatus.Registering : isUnregistering ? Cardano.StakeCredentialStatus.Unregistering : regCert ? Cardano.StakeCredentialStatus.Registered : Cardano.StakeCredentialStatus.Unregistered; return { ...(credentialStatus === Cardano.StakeCredentialStatus.Registered && { deposit }), credentialStatus }; }); }; const accountCertificateTransactions = ( transactions$: Observable<TxWithEpoch[]>, rewardAccount: Cardano.RewardAccount ) => { const stakeKeyHash = Cardano.RewardAccount.toHash(rewardAccount); return transactions$.pipe( map((transactions) => transactions .map(({ tx, epoch }) => ({ certificates: (tx.body.certificates || []) .map((cert) => Cardano.isCertType(cert, [ ...Cardano.RegAndDeregCertificateTypes, ...Cardano.StakeDelegationCertificateTypes ]) ? cert : null ) .filter(isNotNil) .filter((cert) => (cert.stakeCredential.hash as unknown as Crypto.Ed25519KeyHashHex) === stakeKeyHash), epoch })) .filter(({ certificates }) => certificates.length > 0) ), distinctUntilChanged((a, b) => isEqual(a, b)) ); }; const accountDRepCertificateTransactions = ( transactions$: Observable<TxWithEpoch[]>, rewardAccount: Cardano.RewardAccount ) => { const stakeKeyHash = Cardano.RewardAccount.toHash(rewardAccount); return transactions$.pipe( map((transactions) => transactions .map(({ tx, epoch }) => ({ certificates: (tx.body.certificates || []) .map((cert) => Cardano.isCertType(cert, [ ...Cardano.VoteDelegationCredentialCertificateTypes, Cardano.CertificateType.StakeDeregistration, Cardano.CertificateType.Unregistration ]) ? cert : null ) .filter(isNotNil) .filter((cert) => (cert.stakeCredential.hash as unknown as Crypto.Ed25519KeyHashHex) === stakeKeyHash), epoch })) .filter(({ certificates }) => certificates.length > 0) ), distinctUntilChanged((a, b) => isEqual(a, b)) ); }; type ObservableType<O> = O extends Observable<infer T> ? T : unknown; type TransactionsCertificates = ObservableType<ReturnType<typeof accountCertificateTransactions>>; type TransactionsDRepCertificates = ObservableType<ReturnType<typeof accountDRepCertificateTransactions>>; /** * Check if the stake key was registered and is delegated, and return the pool ID. * A stake key is considered delegated 3 epochs after the certificate was sent. * * @returns * - the stake pool ID that is delegated to at the given epoch. * - undefined if the stake key was not registered. * Returns the stake pool ID that is delegated to at the given epoch. * If the stake key was not registered, it returns undefined. */ export const getStakePoolIdAtEpoch = (transactions: TransactionsCertificates) => (atEpoch: Cardano.EpochNo) => { const certificatesUpToEpoch = transactions .filter(({ epoch }) => epoch < atEpoch - 2) .map(({ certificates }) => certificates); if (!lastStakeKeyCertOfType(certificatesUpToEpoch, Cardano.StakeRegistrationCertificateTypes)) { return; } const delegationTxCertificates = findLast(certificatesUpToEpoch, (certs) => Cardano.includesAnyCertificate(certs, Cardano.StakeDelegationCertificateTypes) ); if (!delegationTxCertificates) return; return findLast( delegationTxCertificates .map((cert) => (Cardano.isCertType(cert, Cardano.StakeDelegationCertificateTypes) ? cert : null)) .filter(isNotNil) )?.poolId; }; export const createDelegateeTracker = ( stakePoolProvider: ObservableStakePoolProvider, epoch$: Observable<Cardano.EpochNo>, certificates$: Observable<TransactionsCertificates> ): Observable<Cardano.Delegatee | undefined> => combineLatest([certificates$, epoch$]).pipe( switchMap(([transactions, lastEpoch]) => { const stakePoolIds = [ Cardano.EpochNo(lastEpoch + 1), Cardano.EpochNo(lastEpoch + 2), Cardano.EpochNo(lastEpoch + 3) ].map(getStakePoolIdAtEpoch(transactions)); const uniqStakePoolIds = uniq(stakePoolIds.filter(isNotNil)); return stakePoolProvider(uniqStakePoolIds).pipe( map((stakePools) => stakePoolIds.map((poolId) => stakePools.find((pool) => pool.id === poolId) || undefined)), map(([currentEpoch, nextEpoch, nextNextEpoch]) => ({ currentEpoch, nextEpoch, nextNextEpoch })) ); }), distinctUntilChanged((a, b) => isEqual(a, b)) ); export const createDRepDelegateeTracker = ( certificates$: Observable<TransactionsDRepCertificates> ): Observable<Cardano.DelegateRepresentative | undefined> => certificates$.pipe( switchMap((certs) => { const sortedCerts = [...certs].sort((a, b) => a.epoch - b.epoch); const mostRecent = sortedCerts.pop()?.certificates.pop(); let dRep: Cardano.DelegateRepresentative | undefined; // Certificates at this point are pre filtered, they are either vote delegation kind or stake key de-registration kind. // If the most recent is not a de-registration, emit found dRep. if ( mostRecent && !Cardano.isCertType(mostRecent, [ Cardano.CertificateType.StakeDeregistration, Cardano.CertificateType.Unregistration ]) ) { dRep = mostRecent.dRep; } return of(dRep); }), distinctUntilChanged((a, b) => isEqual(a, b)) ); export const addressCredentialStatuses = ( addresses: Cardano.RewardAccount[], transactions$: Observable<TxWithEpoch[]>, transactionsInFlight$: Observable<TxInFlight[]> ) => combineLatest([transactions$, transactionsInFlight$]).pipe( map(getAccountsCredentialStatus(addresses)), distinctUntilChanged(deepEquals) ); export const addressDelegatees = ( addresses: Cardano.RewardAccount[], transactions$: Observable<TxWithEpoch[]>, stakePoolProvider: ObservableStakePoolProvider, epoch$: Observable<Cardano.EpochNo> ) => combineLatest( addresses.map((address) => createDelegateeTracker(stakePoolProvider, epoch$, accountCertificateTransactions(transactions$, address)) ) ); export const addressDRepDelegatees = ( addresses: Cardano.RewardAccount[], transactions$: Observable<TxWithEpoch[]>, drepInfo$: (drepIds: Cardano.DRepID[]) => Observable<DRepInfo[]> ) => combineLatest( addresses.map((address) => createDRepDelegateeTracker(accountDRepCertificateTransactions(transactions$, address))) ).pipe(switchMap((dreps) => drepInfo$(drepsToDrepIds(dreps)).pipe(map(drepsToDelegatees(dreps))))); export const addressRewards = ( rewardAccounts: Cardano.RewardAccount[], transactionsInFlight$: Observable<TxInFlight[]>, rewardsProvider: ObservableRewardsProvider, balancesStore: KeyValueStore<Cardano.RewardAccount, Cardano.Lovelace> ): Observable<Cardano.Lovelace[]> => { // Allow identical rewards$ emits to fix corner case. // Epoch change can trigger rewards fetch before tx is detected as confirmed: // rewards$: 'a-b---b' b:{a-tx.rewards} <-- allow 'b' to emitted twice // withdrawalsInFlight$: 'x---y--' x:[tx], y:[] // combineLatest: 'm-n---p' m:{a-tx.rewards}, n:{b-tx.rewards}, p:{b} const rewards$ = concat( balancesStore.getValues(rewardAccounts), rewardsProvider(rewardAccounts, () => false /* allow identical emits */).pipe( tap((balances) => { for (const [i, rewardAccount] of rewardAccounts.entries()) { balancesStore.setValue(rewardAccount, balances[i]); } }) ) ); const withdrawalsInFlight$ = transactionsInFlight$.pipe( map((txs) => txs.flatMap(({ body: { withdrawals } }) => withdrawals).filter(isNotNil)), distinctUntilChanged(deepEquals) ); return combineLatest([rewards$, withdrawalsInFlight$]).pipe( startWith([[] as bigint[], [] as Cardano.Withdrawal[]] as const), pairwise(), mergeMap(([[_, prevWithdrawalsInFlight], [totalRewards, withdrawalsInFlight]]) => { // Either rewards$ or withdrawalsInFlight$ can change. // If the change was on withdrawalsInFlight$ AND it's size is smaller (which means a withdrawal tx was confirmed), // then we expect rewards$ to also emit, as it's balance must change after such transaction. // This is coupled with implementation of `rewardsProvider` observable, as it assumes that // rewards re-fetch is triggered by transaction confirmation, therefore must happen AFTER it. if (prevWithdrawalsInFlight.length > withdrawalsInFlight.length) { return EMPTY; } return of(totalRewards.map((total, i) => total - getWithdrawalQuantity(withdrawalsInFlight, rewardAccounts[i]))); }), distinctUntilChanged(deepEquals) ); }; export const toRewardAccounts = (addresses: Cardano.RewardAccount[]) => ([statuses, delegatees, dReps, rewards]: [ { credentialStatus: Cardano.StakeCredentialStatus; deposit?: Cardano.Lovelace }[], (Cardano.Delegatee | undefined)[], (Cardano.DRepDelegatee | undefined)[], Cardano.Lovelace[] ]) => addresses.map( (address, i): Cardano.RewardAccountInfo => ({ address, credentialStatus: statuses[i].credentialStatus, dRepDelegatee: dReps[i], delegatee: delegatees[i], deposit: statuses[i].deposit, rewardBalance: rewards[i] }) ); export const createRewardAccountsTracker = ({ drepInfo$, rewardAccountAddresses$, stakePoolProvider, rewardsProvider, epoch$, balancesStore, transactions$, transactionsInFlight$ }: { drepInfo$: (drepIds: Cardano.DRepID[]) => Observable<DRepInfo[]>; rewardAccountAddresses$: Observable<Cardano.RewardAccount[]>; stakePoolProvider: ObservableStakePoolProvider; rewardsProvider: ObservableRewardsProvider; balancesStore: KeyValueStore<Cardano.RewardAccount, Cardano.Lovelace>; epoch$: Observable<Cardano.EpochNo>; transactions$: Observable<TxWithEpoch[]>; transactionsInFlight$: Observable<TxInFlight[]>; }) => rewardAccountAddresses$.pipe( switchMap((rewardAccounts) => combineLatest([ addressCredentialStatuses(rewardAccounts, transactions$, transactionsInFlight$), addressDelegatees(rewardAccounts, transactions$, stakePoolProvider, epoch$), addressDRepDelegatees(rewardAccounts, transactions$, drepInfo$), addressRewards(rewardAccounts, transactionsInFlight$, rewardsProvider, balancesStore) ]).pipe(map(toRewardAccounts(rewardAccounts))) ) ); |