All files / src/services TransactionsTracker.ts

99.55% Statements 225/226
96.36% Branches 53/55
100% Functions 86/86
99.51% Lines 207/208

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 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 66842x   42x                                                       42x   42x   42x 42x     42x 42x 42x                                                                         42x               42x 161x               42x       300x 136x     164x   164x 173x 169x       164x     42x                   147x 147x   147x 147x 18x 18x   18x 18x               18x 18x     129x       129x       147x     42x       15x   15x 28x 28x 24x   4x           15x     42x             9x   9x 20x   20x   24x 9x 9x     15x   5x       9x                         42x         129x         129x 4x     125x     42x                                             136x                   138x   138x 147x   147x         147x 147x             147x           147x 129x 125x 125x     129x       18x 3x 3x   3x     15x 15x 15x         15x 17x   15x 6x 6x   6x         9x     1x     9x   8x 14x 11x 2x         8x       8x 1x   1x     9x           42x     136x 136x 136x 136x         13x         136x                       42x     141x     145x   262x 262x           42x 271x   472x   256x 256x 297x 163x 163x         42x                                               141x 33x       141x   141x 1923x     141x   141x 29x     141x 111x     85x       128x   22x 22x     141x 37x 4x       4x     141x 30x 3x           141x 141x     33x   37x 37x   1x 1x     1x 1x   1x                 6x     24x 2x               10x       141x 74x 22x       141x 33x 21x   19x     141x     33x     37x 17x     37x                     19x                     72x 72x 37x 3x   34x   35x 16x     19x   72x 72x         141x     27x 30x     212x 62x     145x 262x       134x     370x 30x   340x 62x   278x 134x         2x     144x 144x 2x 3x     2x         370x           141x 141x 37x     141x                         116x 116x 116x 116x 116x 116x        
import { Cardano, ChainHistoryProvider } from '@cardano-sdk/core';
import { DocumentStore, OrderedCollectionStore } from '../persistence';
import {
  EMPTY,
  NEVER,
  Observable,
  Subject,
  combineLatest,
  concat,
  defaultIfEmpty,
  distinctUntilChanged,
  exhaustMap,
  filter,
  from,
  map,
  merge,
  mergeMap,
  mergeWith,
  of,
  partition,
  race,
  scan,
  share,
  startWith,
  switchMap,
  take,
  takeUntil,
  tap,
  withLatestFrom
} from 'rxjs';
import { FailedTx, OutgoingOnChainTx, OutgoingTx, TransactionFailure, TransactionsTracker, TxInFlight } from './types';
import { Logger } from 'ts-log';
import { Range, Shutdown, contextLogger } from '@cardano-sdk/util';
import { RetryBackoffConfig } from 'backoff-rxjs';
import { TrackerSubject } from '@cardano-sdk/util-rxjs';
import { distinctBlock, pollProvider, signedTxsEquals, transactionsEquals, txEquals, txInEquals } from './util';
 
import { WitnessedTx } from '@cardano-sdk/key-management';
import { newAndStoredMulticast } from './util/newAndStoredMulticast';
import chunk from 'lodash/chunk.js';
import sortBy from 'lodash/sortBy.js';
 
export interface TransactionsTrackerProps {
  chainHistoryProvider: ChainHistoryProvider;
  addresses$: Observable<Cardano.PaymentAddress[]>;
  tip$: Observable<Cardano.Tip>;
  retryBackoffConfig: RetryBackoffConfig;
  transactionsHistoryStore: OrderedCollectionStore<Cardano.HydratedTx>;
  inFlightTransactionsStore: DocumentStore<TxInFlight[]>;
  signedTransactionsStore: DocumentStore<WitnessedTx[]>;
  historicalTransactionsFetchLimit: number;
  newTransactions: {
    submitting$: Observable<OutgoingTx>;
    pending$: Observable<OutgoingTx>;
    failedToSubmit$: Observable<FailedTx>;
    signed$: Observable<WitnessedTx>;
  };
  failedFromReemitter$?: Observable<FailedTx>;
  logger: Logger;
}
 
export interface TransactionsTrackerInternals {
  transactionsSource$: Observable<Cardano.HydratedTx[]>;
  rollback$: Observable<Cardano.HydratedTx>;
}
 
export interface TransactionsTrackerInternalsProps {
  chainHistoryProvider: ChainHistoryProvider;
  addresses$: Observable<Cardano.PaymentAddress[]>;
  retryBackoffConfig: RetryBackoffConfig;
  tipBlockHeight$: Observable<Cardano.BlockNo>;
  store: OrderedCollectionStore<Cardano.HydratedTx>;
  historicalTransactionsFetchLimit: number;
  logger: Logger;
}
 
// Temporarily hardcoded. Will be replaced with ChainHistoryProvider 'maxPageSize' value once ADP-2249 is implemented
export const PAGE_SIZE = 25;
 
/**
 * Sorts the given HydratedTx by slot.
 *
 * @param lhs The left-hand side of the comparison operation.
 * @param rhs The left-hand side of the comparison operation.
 */
const compareTxOrder = (lhs: Cardano.HydratedTx, rhs: Cardano.HydratedTx) =>
  lhs.blockHeader.slot - rhs.blockHeader.slot || lhs.index - rhs.index;
 
/**
 * Deduplicates the given array of HydratedTx.
 *
 * @param arr The array of HydratedTx to deduplicate.
 * @param isEqual The equality function to use to determine if two HydratedTx are equal.
 */
const deduplicateSortedArray = (
  arr: Cardano.HydratedTx[],
  isEqual: (a: Cardano.HydratedTx, b: Cardano.HydratedTx) => boolean
) => {
  if (arr.length === 0) {
    return [];
  }
 
  const result = [arr[0]];
 
  for (let i = 1; i < arr.length; ++i) {
    if (!isEqual(arr[i], arr[i - 1])) {
      result.push(arr[i]);
    }
  }
 
  return result;
};
 
const allTransactionsByAddresses = async (
  chainHistoryProvider: ChainHistoryProvider,
  {
    addresses,
    filterBy
  }: {
    addresses: Cardano.PaymentAddress[];
    filterBy: { type: 'blockRange'; blockRange: Range<Cardano.BlockNo> } | { type: 'tip'; limit: number };
  }
): Promise<Cardano.HydratedTx[]> => {
  const addressesSubGroups = chunk(addresses, PAGE_SIZE);
  let response: Cardano.HydratedTx[] = [];
 
  for (const addressGroup of addressesSubGroups) {
    if (filterBy.type === 'blockRange') {
      let startAt = 0;
      let pageResults: Cardano.HydratedTx[] = [];
 
      do {
        pageResults = (
          await chainHistoryProvider.transactionsByAddresses({
            addresses: addressGroup,
            blockRange: filterBy.blockRange,
            pagination: { limit: PAGE_SIZE, startAt }
          })
        ).pageResults;
 
        startAt += PAGE_SIZE;
        response = [...response, ...pageResults];
      } while (pageResults.length >= PAGE_SIZE);
    } else {
      const txes = await chainHistoryProvider.transactionsByAddresses({
        addresses: addressGroup,
        pagination: { limit: filterBy.limit, order: 'desc', startAt: 0 }
      });
      response = [...response, ...txes.pageResults.reverse()];
    }
  }
 
  return deduplicateSortedArray(response.sort(compareTxOrder), txEquals);
};
 
const getLastTransactionsAtBlock = (
  transactions: Cardano.HydratedTx[],
  blockNo: Cardano.BlockNo
): Cardano.HydratedTx[] => {
  const txsFromSameBlock = [];
 
  for (let i = transactions.length - 1; i >= 0; --i) {
    const tx = transactions[i];
    if (tx.blockHeader.blockNo === blockNo) {
      txsFromSameBlock.push(tx);
    } else {
      break;
    }
  }
 
  // Since we are traversing the array in reverse to find the transactions for this block,
  // we must reverse the result.
  return txsFromSameBlock.reverse();
};
 
export const revertLastBlock = (
  localTransactions: Cardano.HydratedTx[],
  blockNo: Cardano.BlockNo,
  rollback$: Subject<Cardano.HydratedTx>,
  newTransactions: Cardano.HydratedTx[],
  logger: Logger
) => {
  const result = [...localTransactions];
 
  while (result.length > 0) {
    const lastKnownTx = result[result.length - 1];
 
    if (lastKnownTx.blockHeader.blockNo === blockNo) {
      // only emit if the tx is also not present in the new transactions to be added
      if (newTransactions.findIndex((tx) => tx.id === lastKnownTx.id) === -1) {
        logger.debug(`Transaction ${lastKnownTx.id} was rolled back`);
        rollback$.next(lastKnownTx);
      }
 
      result.pop();
    } else {
      break;
    }
  }
 
  return deduplicateSortedArray(result, txEquals);
};
 
/**
 * Fetches the last `historicalTransactionsFetchLimit` transactions for a set of addresses.
 * If there is a single address, it returns the most recent ones up to `historicalTransactionsFetchLimit`. If there
 * are more than one address, it returns all transaction from all addresses, one month back from the most recent transaction.
 *
 * @param {ChainHistoryProvider} chainHistoryProvider - The chain history provider used to fetch transaction history.
 * @param {Cardano.PaymentAddress[]} addresses - A list of Cardano payment addresses to fetch transactions for.
 * @param {number} historicalTransactionsFetchLimit - The maximum number of transactions to fetch in the initial pass.
 * @returns {Promise<Cardano.HydratedTx[]>} A promise that resolves to a list of hydrated transactions from the given addresses.
 */
const fetchInitialTransactions = async (
  chainHistoryProvider: ChainHistoryProvider,
  addresses: Cardano.PaymentAddress[],
  historicalTransactionsFetchLimit: number
): Promise<Cardano.HydratedTx[]> => {
  const transactions = await allTransactionsByAddresses(chainHistoryProvider, {
    addresses,
    filterBy: { limit: historicalTransactionsFetchLimit, type: 'tip' }
  });
 
  if (transactions.length === 0) {
    return [];
  }
  // allTransactionsByAddresses returns in `asc` order
  return transactions.slice(-1 * historicalTransactionsFetchLimit);
};
 
const findIntersectionAndUpdateTxStore = ({
  chainHistoryProvider,
  historicalTransactionsFetchLimit,
  logger,
  store,
  retryBackoffConfig,
  tipBlockHeight$,
  rollback$,
  localTransactions,
  addresses
}: Pick<
  TransactionsTrackerInternalsProps,
  | 'chainHistoryProvider'
  | 'logger'
  | 'store'
  | 'retryBackoffConfig'
  | 'tipBlockHeight$'
  | 'historicalTransactionsFetchLimit'
> & {
  localTransactions: Cardano.HydratedTx[];
  rollback$: Subject<Cardano.HydratedTx>;
  addresses: Cardano.PaymentAddress[];
}) =>
  pollProvider({
    // Do not re-fetch transactions twice on load when tipBlockHeight$ loads from storage first
    // It should also help when using poor internet connection.
    // Caveat is that local transactions might get out of date...
    combinator: exhaustMap,
    equals: transactionsEquals,
    logger,
    retryBackoffConfig,
    // eslint-disable-next-line sonarjs/cognitive-complexity,complexity, max-statements
    sample: async () => {
      let rollbackOcurred = false;
      // eslint-disable-next-line no-constant-condition
      while (true) {
        const lastStoredTransaction: Cardano.HydratedTx | undefined = localTransactions[localTransactions.length - 1];
 
        lastStoredTransaction &&
          logger.debug(
            `Last stored tx: ${lastStoredTransaction?.id} block:${lastStoredTransaction?.blockHeader.blockNo}`
          );
 
        const lowerBound = lastStoredTransaction?.blockHeader.blockNo;
        const newTransactions = await (lowerBound === undefined
          ? fetchInitialTransactions(chainHistoryProvider, addresses, historicalTransactionsFetchLimit)
          : allTransactionsByAddresses(chainHistoryProvider, {
              addresses,
              filterBy: { blockRange: { lowerBound }, type: 'blockRange' }
            }));
 
        logger.debug(
          `chainHistoryProvider returned ${newTransactions.length} transactions`,
          lowerBound !== undefined && `since block ${lowerBound}`
        );
 
        // Fetching transactions from scratch, nothing else to do here.
        if (lowerBound === undefined) {
          if (newTransactions.length > 0) {
            localTransactions = newTransactions;
            store.setAll(newTransactions);
          }
 
          return newTransactions;
        }
 
        // If no transactions found from that block range, it means the last known block has been rolled back.
        if (newTransactions.length === 0) {
          localTransactions = revertLastBlock(localTransactions, lowerBound, rollback$, newTransactions, logger);
          rollbackOcurred = true;
 
          continue;
        }
 
        const localTxsFromSameBlock = getLastTransactionsAtBlock(localTransactions, lowerBound);
        const firstSegmentOfNewTransactions = newTransactions.slice(0, localTxsFromSameBlock.length);
        const hasSameLength = localTxsFromSameBlock.length === firstSegmentOfNewTransactions.length;
 
        // The first segment of new transaction should match exactly (same txs and same order) our last know TXs. Otherwise
        // roll them back and re-apply in new order.
        const sameTxAndOrder =
          hasSameLength &&
          localTxsFromSameBlock.every((tx, index) => tx.id === firstSegmentOfNewTransactions[index].id);
 
        if (!sameTxAndOrder) {
          localTransactions = revertLastBlock(localTransactions, lowerBound, rollback$, newTransactions, logger);
          rollbackOcurred = true;
 
          continue;
        }
 
        // No rollbacks, if they overlap 100% do nothing, otherwise add the difference.
        const areTransactionsSame =
          newTransactions.length === localTxsFromSameBlock.length &&
          localTxsFromSameBlock.every(
            (tx, index) =>
              tx.id === newTransactions[index].id && tx.blockHeader.slot === newTransactions[index].blockHeader.slot
          );
 
        if (!areTransactionsSame) {
          // deduplication takes local tx first, but it's possible that the only change is the block header
          for (const localTx of localTxsFromSameBlock) {
            const newTx = newTransactions.find((tx) => tx.id === localTx.id);
            if (newTx?.blockHeader && newTx.blockHeader.slot !== localTx.blockHeader.slot) {
              localTx.blockHeader = newTx.blockHeader;
            }
          }
          // Skip overlapping transactions to avoid duplicates.
          // Limit # of stored transactions to last `historicalTransactionsFetchLimit`
          localTransactions = deduplicateSortedArray(
            [...localTransactions, ...newTransactions.slice(localTxsFromSameBlock.length)],
            txEquals
          ).slice(-1 * historicalTransactionsFetchLimit);
          store.setAll(localTransactions);
        } else if (rollbackOcurred) {
          // This case handles rollbacks without new additions
          store.setAll(localTransactions);
        }
 
        return localTransactions;
      }
    },
    trigger$: tipBlockHeight$
  });
 
export const createAddressTransactionsProvider = (
  props: TransactionsTrackerInternalsProps
): TransactionsTrackerInternals => {
  const { addresses$, store, logger } = props;
  const rollback$ = new Subject<Cardano.HydratedTx>();
  const storedTransactions$ = store.getAll().pipe(share());
  return {
    rollback$: rollback$.asObservable(),
    transactionsSource$: concat(
      storedTransactions$.pipe(
        tap((storedTransactions) =>
          logger.debug(`Stored history transactions count: ${storedTransactions?.length || 0}`)
        )
      ),
      combineLatest([addresses$, storedTransactions$.pipe(defaultIfEmpty([] as Cardano.HydratedTx[]))]).pipe(
        switchMap(([addresses, storedTransactions]) =>
          findIntersectionAndUpdateTxStore({
            addresses,
            localTransactions: deduplicateSortedArray([...storedTransactions].sort(compareTxOrder), txEquals),
            rollback$,
            ...props
          })
        )
      )
    )
  };
};
 
const createHistoricalTransactionsTrackerSubject = (
  transactions$: Observable<Cardano.HydratedTx[]>
): TrackerSubject<Cardano.HydratedTx[]> =>
  new TrackerSubject(
    transactions$.pipe(
      map((transactions) =>
        sortBy(
          transactions,
          ({ blockHeader: { blockNo } }) => blockNo,
          ({ index }) => index
        )
      )
    )
  );
 
export const newTransactions$ = <T extends Pick<Cardano.Tx, 'id'>>(transactions$: Observable<T[]>) =>
  transactions$.pipe(
    take(1),
    map((transactions) => transactions.map(({ id }) => id)),
    mergeMap((initialTransactionIds) => {
      const ignoredTransactionIds: Cardano.TransactionId[] = [...initialTransactionIds];
      return transactions$.pipe(
        map((transactions) => transactions.filter(({ id }) => !ignoredTransactionIds.includes(id))),
        tap((newTransactions) => ignoredTransactionIds.push(...newTransactions.map(({ id }) => id))),
        mergeMap((newTransactions) => concat(...newTransactions.map((tx) => of(tx))))
      );
    })
  );
 
export const createTransactionsTracker = (
  {
    tip$,
    chainHistoryProvider,
    addresses$,
    historicalTransactionsFetchLimit,
    newTransactions: { submitting$: newSubmitting$, pending$, signed$: newSigned$, failedToSubmit$ },
    retryBackoffConfig,
    transactionsHistoryStore: transactionsStore,
    inFlightTransactionsStore: newTransactionsStore,
    signedTransactionsStore,
    logger,
    failedFromReemitter$
  }: TransactionsTrackerProps,
  { transactionsSource$: txSource$, rollback$ }: TransactionsTrackerInternals = createAddressTransactionsProvider({
    addresses$,
    chainHistoryProvider,
    historicalTransactionsFetchLimit,
    logger: contextLogger(logger, 'AddressTransactionsProvider'),
    retryBackoffConfig,
    store: transactionsStore,
    tipBlockHeight$: distinctBlock(tip$)
  })
): TransactionsTracker & Shutdown => {
  const submitting$ = newSubmitting$.pipe(
    tap((newSubmitting) => logger.debug(`Got new submitting transaction: ${newSubmitting.id}`)),
    share()
  );
 
  const transactionsSource$ = new TrackerSubject(txSource$);
 
  const historicalTransactions$ = createHistoricalTransactionsTrackerSubject(transactionsSource$).pipe(
    tap((transactions) => logger.debug(`History transactions count: ${transactions?.length || 0}`))
  );
 
  const new$ = newTransactions$(historicalTransactions$).pipe(share());
 
  const [onChainNewTxPhase2Failed$, onChainNewTxSuccess$] = partition(new$, (tx) =>
    Cardano.util.isPhase2ValidationErrTx(tx)
  );
 
  const txOnChain$ = (evt: OutgoingTx): Observable<OutgoingOnChainTx> =>
    merge(
      historicalTransactions$.pipe(
        take(1),
        mergeMap((txs) => from(txs))
      ),
      onChainNewTxSuccess$
    ).pipe(
      filter((historyTx) => historyTx.id === evt.id),
      take(1),
      map((historyTx) => ({ ...evt, slot: historyTx.blockHeader.slot })),
      tap(({ slot }) => logger.debug(`Transaction ${evt.id} is on-chain in slot ${slot}`))
    );
 
  const submittingOrPreviouslySubmitted$ = newAndStoredMulticast<TxInFlight, Cardano.TransactionId>({
    groupByFn: ({ id }) => id,
    logStringfn: (transactions) => `Store contains ${transactions?.length} in flight transactions`,
    logger,
    new$: submitting$,
    stored$: newTransactionsStore.get(),
    storedFilterfn: ({ submittedAt }) => !!submittedAt
  });
 
  const newSignedOrPreviouslySigned$ = newAndStoredMulticast<WitnessedTx, Cardano.TransactionId>({
    groupByFn: ({ tx }) => tx.id,
    logStringfn: (WitnessedTxs) => `Store contains ${WitnessedTxs?.length} signed transactions`,
    logger,
    new$: newSigned$,
    stored$: signedTransactionsStore.get()
  });
 
  const failed$ = new Subject<FailedTx>();
  const failedSubscription = submittingOrPreviouslySubmitted$
    .pipe(
      mergeMap((group$) =>
        group$.pipe(
          switchMap((tx) => {
            const invalidHereafter = tx.body.validityInterval?.invalidHereafter;
            return race(
              onChainNewTxPhase2Failed$.pipe(
                filter((failedTx) => failedTx.id === tx.id),
                map((): FailedTx => ({ reason: TransactionFailure.Phase2Validation, ...tx }))
              ),
              rollback$.pipe(
                map((rolledBackTx) => rolledBackTx.id),
                filter((rolledBackTxId) => tx.body.inputs.some(({ txId }) => txId === rolledBackTxId)),
                map(
                  (rolledBackTxId): FailedTx => ({
                    error: new Error(
                      `Invalid inputs due to rolled back tx (${rolledBackTxId}}). Try to rebuild and resubmit.`
                    ),
                    reason: TransactionFailure.InvalidTransaction,
                    ...tx
                  })
                )
              ),
              failedToSubmit$.pipe(filter((failed) => failed.id === tx.id)),
              invalidHereafter
                ? tip$.pipe(
                    filter(({ slot }) => slot > invalidHereafter),
                    map(() => ({ reason: TransactionFailure.Timeout, ...tx }))
                  )
                : NEVER
            ).pipe(take(1), takeUntil(txOnChain$(tx)));
          })
        )
      ),
      mergeWith(failedFromReemitter$ || EMPTY),
      tap(({ id, reason }) => logger.debug(`Transaction ${id} failed`, reason))
    )
    .subscribe(failed$);
 
  const txFailed$ = (tx: OutgoingTx) =>
    failed$.pipe(
      filter((failed) => failed.id === tx.id),
      take(1)
    );
 
  const txPending$ = (tx: OutgoingTx) =>
    pending$.pipe(
      filter((pending) => pending.id === tx.id),
      withLatestFrom(tip$),
      map(([_, { slot }]) => ({ submittedAt: slot, ...tx }))
    );
 
  const inFlight$ = new TrackerSubject<TxInFlight[]>(
    submittingOrPreviouslySubmitted$.pipe(
      mergeMap((group$) =>
        group$.pipe(
          // Only keep 1 (latest) inner observable per tx id.
          switchMap((tx) => {
            const done$ = race(txOnChain$(tx), txFailed$(tx)).pipe(
              map(() => ({ op: 'remove' as const, tx })),
              share()
            );
            return merge(
              of({ op: 'add' as const, tx }),
              done$,
              tx.submittedAt
                ? EMPTY
                : // NOTE: current implementation might incorrectly update 'submittedAt'
                  // if transaction was attempted to resubmit and appeared to be already submitted.
                  // This property currently does not necessarily correspond to
                  // time when transaction got into a mempool - it works more like 'lastAttemptToSubmitAt',
                  // which isn't necessarily bad as it might prevent frequent resubmissions in some cases
                  txPending$(tx).pipe(
                    map((pendingTx) => ({
                      op: 'submitted' as const,
                      tx: pendingTx
                    })),
                    takeUntil(done$)
                  )
            );
          })
        )
      ),
      scan((inFlight, props) => {
        const idx = inFlight.findIndex((txInFlight) => txInFlight.id === props.tx.id);
        if (props.op === 'add') {
          if (idx >= 0) {
            return [...inFlight.slice(0, idx), props.tx, ...inFlight.slice(idx + 1)];
          }
          return [...inFlight, props.tx];
        }
        if (props.op === 'remove') {
          return [...inFlight.slice(0, idx), ...inFlight.slice(idx + 1)];
        }
        // props.op === 'submitted'
        return [...inFlight.slice(0, idx), props.tx, ...inFlight.slice(idx + 1)];
      }, [] as TxInFlight[]),
      tap((inFlight) => newTransactionsStore.set(inFlight)),
      tap((inFlight) => logger.debug(`${inFlight.length} in flight transactions`)),
      startWith([])
    )
  );
 
  const signed$ = new TrackerSubject<WitnessedTx[]>(
    merge(
      newSignedOrPreviouslySigned$.pipe(
        mergeMap((WitnessedTx$) => WitnessedTx$),
        map((witnessedTx) => ({ op: 'add' as const, witnessedTx }))
      ),
      inFlight$.pipe(
        mergeMap((txs) => txs),
        map((tx) => ({ id: tx.id, op: 'remove' as const }))
      ),
      historicalTransactions$.pipe(
        map((txs) => ({
          inputs: txs.flatMap((tx) => tx.body.inputs.map((inputs) => inputs)),
          op: 'check_inputs' as const
        }))
      ),
      tip$.pipe(map(({ slot }) => ({ op: 'check_interval' as const, slot })))
    ).pipe(
      scan((signed, action) => {
        if (action.op === 'add') {
          return [...signed, action.witnessedTx];
        }
        if (action.op === 'remove') {
          return signed.filter(({ tx }) => tx.id !== action.id);
        }
        if (action.op === 'check_interval') {
          return signed.filter(
            ({
              tx: {
                body: { validityInterval: { invalidHereafter } = {} }
              }
            }) => invalidHereafter && invalidHereafter > action.slot
          );
        }
        if (action.op === 'check_inputs') {
          return signed.filter(({ tx }) => {
            const anyUtxoIsUsed = tx.body.inputs.some((WitnessedTxInput) =>
              action.inputs.some((historicalInput) => txInEquals(WitnessedTxInput, historicalInput))
            );
 
            return !anyUtxoIsUsed;
          });
        }
        return signed;
      }, [] as WitnessedTx[]),
      tap((signed) => signedTransactionsStore.set(signed)),
      startWith([]),
      distinctUntilChanged(signedTxsEquals)
    )
  );
 
  const onChain$ = new Subject<OutgoingOnChainTx>();
  const onChainSubscription = submittingOrPreviouslySubmitted$
    .pipe(mergeMap((group$) => group$.pipe(switchMap((tx) => txOnChain$(tx).pipe(takeUntil(txFailed$(tx)))))))
    .subscribe(onChain$);
 
  return {
    history$: historicalTransactions$,
    new$,
    outgoing: {
      failed$,
      inFlight$,
      onChain$,
      pending$,
      signed$,
      submitting$
    },
    rollback$,
    shutdown: () => {
      inFlight$.complete();
      onChainSubscription.unsubscribe();
      onChain$.complete();
      failedSubscription.unsubscribe();
      failed$.complete();
      logger.debug('Shutdown');
    }
  };
};