All files / src WebSocket.ts

4.71% Statements 13/276
0% Branches 0/110
0% Functions 0/52
5.08% Lines 12/236

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        17x                                     17x   17x 17x   17x                                                                                                                                                                             17x         17x                         17x       17x                   17x                             17x                                                                               17x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
// cSpell:ignore cardano sonarjs utxos
/* eslint-disable max-depth */
/* eslint-disable unicorn/prefer-add-event-listener */
 
import {
  Cardano,
  ChainHistoryProvider,
  EpochInfo,
  EraSummary,
  HealthCheckResponse,
  NetworkInfoProvider,
  Paginated,
  Provider,
  ProviderError,
  ProviderFailure,
  Serialization,
  StakeSummary,
  SupplySummary,
  TransactionsByAddressesArgs,
  UtxoByAddressesArgs,
  UtxoProvider,
  createSlotEpochInfoCalc
} from '@cardano-sdk/core';
import { HexBlob, fromSerializableObject, toSerializableObject } from '@cardano-sdk/util';
import { Logger } from 'ts-log';
import { Observable, ReplaySubject, Subject, filter, firstValueFrom, merge } from 'rxjs';
import WebSocket from 'isomorphic-ws';
 
const NOT_CONNECTED_ID = 'not-connected';
 
export type AsyncReturnType<F extends () => unknown> = F extends () => Promise<infer R> ? R : never;
 
export type MetadataDbModel = [string, HexBlob];
 
export type NetworkInfoMethods = Exclude<keyof NetworkInfoProvider, 'healthCheck'>;
export type NetworkInfoResponses = { [m in NetworkInfoMethods]: AsyncReturnType<NetworkInfoProvider[m]> };
 
export interface WSMessage {
  /** The addresses the client subscribes. */
  txsByAddresses?: { addresses: Cardano.PaymentAddress[]; lower: Cardano.BlockNo };
 
  /** The client id assigned by the server. */
  clientId?: string;
 
  /** The error on server while performing a request. */
  error?: Error;
 
  /** Latest value(s) for the `NetworkInfoProvider` methods.*/
  networkInfo?: Partial<NetworkInfoResponses>;
 
  /** The request id from client to server. */
  requestId?: number;
 
  /** This message is the response to the message with this id. */
  responseTo?: number;
 
  /** The server is still syncing. */
  syncing?: boolean;
 
  /** The transactions. */
  transactions?: Cardano.HydratedTx[];
 
  // When ChainHistoryProvider.transactionsByAddresses is called with blockRange.lowerBound set (i.e. wallet re-open),
  // this middleware doesn't know the full transaction history. To serve the UtxoProvider.utxoByAddresses it needs the
  // UTXOs from transactions before blockRange.lowerBound. Those partial transactions (transaction with only the UTXOs
  // without any other transaction detail) are loaded through this property.
  /** The partial transactions for UTXOs. */
  utxos?: Cardano.HydratedTx[];
}
 
type Txs = { [key: Cardano.TransactionId]: Cardano.HydratedTx };
 
type TxsByAddresses = Exclude<WSMessage['txsByAddresses'], undefined>;
 
type WSStatus = 'connecting' | 'connected' | 'idle' | 'stop';
 
type WSHandler = (error?: Error, message?: WSMessage) => void;
 
interface DeferredRequests {
  timeout?: NodeJS.Timeout;
  requests: { complete: (error?: Error) => void; txsByAddresses: TxsByAddresses }[];
}
 
export interface WsClientConfiguration {
  /** The interval in seconds between two heartbeat messages. Default 55". */
  heartbeatInterval?: number;
 
  /** The interval in seconds after which a request must timeout. Default 60". */
  requestTimeout?: number;
 
  /** The WebSocket server URL. */
  url: URL;
}
 
export interface WsClientDependencies {
  /** The `httpChainHistoryProvider`. */
  chainHistoryProvider: ChainHistoryProvider;
 
  /** The logger. */
  logger: Logger;
}
 
interface AddressStatus {
  lower: Cardano.BlockNo;
  status: 'synced' | 'syncing';
}
 
interface EpochRollover {
  epochInfo: EpochInfo;
  eraSummaries: EraSummary[];
  ledgerTip: Cardano.Tip;
  lovelaceSupply: SupplySummary;
  protocolParameters: Cardano.ProtocolParameters;
}
 
const deserializeDatum = (tx: Cardano.HydratedTx) => {
  for (const output of tx.body.outputs)
    Iif (output.datum) output.datum = Serialization.PlutusData.fromCbor(output.datum as unknown as HexBlob).toCore();
};
 
const deserializeMetadata = (tx: Cardano.HydratedTx) => {
  Iif (tx.auxiliaryData)
    tx.auxiliaryData = {
      blob: new Map(
        (tx.auxiliaryData as unknown as MetadataDbModel[]).map((metadata) => {
          const bKey = BigInt(metadata[0]);
 
          return [bKey, Serialization.GeneralTransactionMetadata.fromCbor(metadata[1]).toCore().get(bKey)!] as const;
        })
      )
    };
};
 
const isEventError = (error: unknown): error is { error: Error } =>
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  typeof error === 'object' && !!error && (error as any).error instanceof Error;
 
export const isTxRelevant = (
  { body: { collaterals, collateralReturn, inputs, outputs }, inputSource }: Cardano.HydratedTx,
  addresses: Cardano.PaymentAddress[]
) =>
  inputSource === Cardano.InputSource.inputs
    ? inputs.some((input) => addresses.includes(input.address)) ||
      outputs.some((output) => addresses.includes(output.address))
    : collaterals!.some((input) => addresses.includes(input.address)) ||
      (collateralReturn && addresses.includes(collateralReturn.address));
 
const removeRolledBackTxs = (txs: Txs, blockNo: Cardano.BlockNo) => {
  let id: Cardano.TransactionId;
 
  for (id in txs) Iif (txs[id].blockHeader.blockNo > blockNo) delete txs[id];
};
 
interface EmitHealthOptions {
  notRecoverable?: boolean;
  overwrite?: boolean;
}
 
interface WSHealthCheckResponse extends HealthCheckResponse {
  notRecoverable?: boolean;
}
 
export class WsProvider implements Provider {
  /** Emits the health state. */
  public health$: Observable<WSHealthCheckResponse>;
 
  private healthSubject$: ReplaySubject<WSHealthCheckResponse>;
  private notRecoverable?: boolean;
  private reason?: string;
 
  constructor() {
    this.health$ = this.healthSubject$ = new ReplaySubject<WSHealthCheckResponse>(1);
    this.healthSubject$.next({ ok: false, reason: 'starting' });
  }
 
  protected emitHealth(reason?: string | HealthCheckResponse, { notRecoverable, overwrite }: EmitHealthOptions = {}) {
    Iif (this.notRecoverable) return;
 
    Iif (!reason) {
      this.reason = undefined;
 
      return this.healthSubject$.next({ ok: true });
    }
 
    Iif (notRecoverable) this.notRecoverable = true;
 
    let result: WSHealthCheckResponse;
 
    if (typeof reason === 'string') {
      Iif (overwrite || !this.reason) this.reason = reason;
 
      result = { notRecoverable: this.notRecoverable, ok: false, reason: this.reason };
    } else result = reason;
 
    this.healthSubject$.next(result);
  }
 
  public healthCheck() {
    return firstValueFrom(this.health$);
  }
}
 
export class CardanoWsClient extends WsProvider {
  /** The client id, assigned by the server. */
  clientId = NOT_CONNECTED_ID;
 
  /** Emits on epoch rollover. */
  epoch$: Observable<EpochRollover>;
 
  /** The `Observable` form of `NetworkInfoProvider`. */
  networkInfo: {
    [m in `${NetworkInfoMethods}$`]: Observable<
      AsyncReturnType<NetworkInfoProvider[m extends `${infer o}$` ? o : never]>
    >;
  };
 
  /** WebSocket based `ChainHistoryProvider` implementation. */
  chainHistoryProvider: ChainHistoryProvider;
 
  /** WebSocket based `NetworkInfoProvider` implementation. */
  networkInfoProvider: NetworkInfoProvider;
 
  /** WebSocket based `UtxoProvider` implementation. */
  utxoProvider: UtxoProvider;
 
  private addresses: { [key: Cardano.PaymentAddress]: AddressStatus } = {};
  private closePromise: Promise<void>;
  private closeResolver: () => void;
  private deferredRequests: DeferredRequests = { requests: [] };
  private epochSubject$: Subject<EpochRollover>;
  private handlers = new Map<number, WSHandler>();
  private heartbeatInterval: number;
  private heartbeatTimeout: NodeJS.Timeout | undefined;
  private logger: Logger;
  private requestId = 0;
  private status: WSStatus = 'idle';
  private transactions: Txs = {};
  private url: URL;
  private utxos: Txs = {};
  private ws: WebSocket;
 
  private networkInfoSubjects = {} as {
    [m in `${NetworkInfoMethods}$`]: ReplaySubject<
      AsyncReturnType<NetworkInfoProvider[m extends `${infer o}$` ? o : never]>
    >;
  };
 
  constructor(deps: WsClientDependencies, cfg: WsClientConfiguration) {
    super();
 
    this.epoch$ = this.epochSubject$ = new Subject<EpochRollover>();
    this.heartbeatInterval = (cfg.heartbeatInterval || 55) * 1000;
    this.logger = deps.logger;
    this.url = cfg.url;
 
    this.closePromise = new Promise((resolve) => {
      this.closeResolver = resolve;
    });
 
    this.networkInfoSubjects = {
      eraSummaries$: new ReplaySubject<EraSummary[]>(1),
      genesisParameters$: new ReplaySubject<Cardano.CompactGenesis>(1),
      ledgerTip$: new ReplaySubject<Cardano.Tip>(1),
      lovelaceSupply$: new ReplaySubject<SupplySummary>(1),
      protocolParameters$: new ReplaySubject<Cardano.ProtocolParameters>(1),
      stake$: new ReplaySubject<StakeSummary>(1)
    };
    this.networkInfo = this.networkInfoSubjects;
 
    this.chainHistoryProvider = {
      blocksByHashes: (args) => deps.chainHistoryProvider.blocksByHashes(args),
      healthCheck: () => this.healthCheck(),
      transactionsByAddresses: (args) => this.transactionsByAddresses(args),
      transactionsByHashes: (args) => deps.chainHistoryProvider.transactionsByHashes(args)
    };
 
    this.networkInfoProvider = {
      eraSummaries: this.createNetworkInfoProviderMethod('eraSummaries'),
      genesisParameters: this.createNetworkInfoProviderMethod('genesisParameters'),
      healthCheck: () => this.healthCheck(),
      ledgerTip: this.createNetworkInfoProviderMethod('ledgerTip'),
      lovelaceSupply: this.createNetworkInfoProviderMethod('lovelaceSupply'),
      protocolParameters: this.createNetworkInfoProviderMethod('protocolParameters'),
      stake: this.createNetworkInfoProviderMethod('stake')
    };
 
    this.utxoProvider = {
      healthCheck: () => this.healthCheck(),
      utxoByAddresses: (args) => this.utxoByAddresses(args)
    };
 
    this.connect();
  }
 
  private createNetworkInfoProviderMethod<M extends NetworkInfoMethods>(method: M) {
    return async (): Promise<AsyncReturnType<NetworkInfoProvider[M]>> => {
      this.logger.debug(`CardanoWsClient.${method} called`);
 
      // Take the first value from the method's observable or the first not ok health check not due to the provider is still starting
      const value = await firstValueFrom(
        merge(
          this.health$.pipe(filter(({ ok, reason }) => !ok && reason !== 'starting')),
          this.networkInfo[`${method}$`]
        )
      );
 
      // If the value was an error different from starting, throw it, otherwise it is a return value for the method
      Iif ('ok' in value && 'reason' in value && value.ok === false) {
        this.logger.error(`CardanoWsClient.${method} error`, value.reason);
 
        throw new ProviderError(ProviderFailure.ConnectionFailure, undefined, value.reason);
      }
 
      this.logger.debug(`CardanoWsClient.${method} response:`, toSerializableObject(value));
 
      return value as AsyncReturnType<NetworkInfoProvider[M]>;
    };
  }
 
  // eslint-disable-next-line sonarjs/cognitive-complexity
  private connect() {
    Iif (this.status !== 'stop') this.status = 'connecting';
 
    const ws = (this.ws = new WebSocket(this.url));
 
    // eslint-disable-next-line sonarjs/cognitive-complexity, complexity, max-statements
    ws.onmessage = (event) => {
      try {
        Iif (typeof event.data !== 'string') throw new Error('Unexpected data from WebSocket ');
 
        const message = fromSerializableObject<WSMessage>(JSON.parse(event.data));
        const { clientId, networkInfo, responseTo, syncing, transactions, utxos } = message;
 
        Iif (clientId) {
          this.logger.info(`Connected with clientId ${(this.clientId = clientId)}`);
 
          if (syncing) this.emitHealth('Server is still syncing', { overwrite: true });
          else this.emitHealth();
        }
 
        Iif (transactions)
          for (const tx of transactions) {
            deserializeDatum(tx);
            deserializeMetadata(tx);
            this.transactions[tx.id] = tx;
            delete this.utxos[tx.id];
 
            this.logger.debug('CardanoWsClient got tx', tx.id, tx.blockHeader);
          }
 
        Iif (utxos)
          for (const tx of utxos)
            Iif (!this.transactions[tx.id]) {
              deserializeDatum(tx);
              this.utxos[tx.id] = tx;
            }
 
        // Handle networkInfo as last one
        Iif (networkInfo) {
          const { eraSummaries, genesisParameters, ledgerTip, lovelaceSupply, protocolParameters, stake } = networkInfo;
 
          Iif (eraSummaries) this.networkInfoSubjects.eraSummaries$.next(eraSummaries);
          Iif (genesisParameters) this.networkInfoSubjects.genesisParameters$.next(genesisParameters);
          Iif (lovelaceSupply) this.networkInfoSubjects.lovelaceSupply$.next(lovelaceSupply);
          Iif (protocolParameters) this.networkInfoSubjects.protocolParameters$.next(protocolParameters);
          Iif (stake) this.networkInfoSubjects.stake$.next(stake);
 
          // Emit ledgerTip as last one
          Iif (ledgerTip) {
            this.logger.debug('CardanoWsClient got tip', ledgerTip);
 
            removeRolledBackTxs(this.transactions, ledgerTip.blockNo);
            removeRolledBackTxs(this.utxos, ledgerTip.blockNo);
 
            this.networkInfoSubjects.ledgerTip$.next(ledgerTip);
          }
 
          // If it is an epoch rollover, emit it
          Iif (eraSummaries && ledgerTip && lovelaceSupply && protocolParameters && !clientId) {
            const epochInfo = createSlotEpochInfoCalc(eraSummaries)(ledgerTip.slot);
 
            this.epochSubject$.next({ epochInfo, eraSummaries, ledgerTip, lovelaceSupply, protocolParameters });
          }
        }
 
        Iif (responseTo) {
          const handler = this.handlers.get(responseTo);
 
          this.logger.debug('CardanoWsClient response', responseTo);
 
          Iif (handler) {
            const { error } = message;
 
            this.handlers.delete(responseTo);
            error ? handler(error) : handler(undefined, message);
          }
        }
      } catch (error) {
        this.logger.error(error, 'While parsing message', event.data, this.clientId);
      }
    };
 
    ws.onclose = () => {
      this.logger.info('WebSocket client connection closed', this.clientId);
 
      Iif (this.heartbeatTimeout) {
        clearInterval(this.heartbeatTimeout);
        this.heartbeatTimeout = undefined;
      }
 
      this.clientId = NOT_CONNECTED_ID;
 
      if (this.status === 'stop') this.closeResolver();
      else {
        this.status = 'idle';
        const timeout = setTimeout(() => this.connect(), 1000);
        Iif (typeof timeout.unref === 'function') timeout.unref();
      }
 
      this.emitHealth('closed');
    };
 
    ws.onerror = (error: unknown) => {
      const err =
        error instanceof Error
          ? error
          : isEventError(error)
          ? error.error
          : new Error(`Unknown error: ${JSON.stringify(error)}`);
 
      this.logger.error(err, 'Async error from WebSocket client', this.clientId);
      ws.close();
      this.emitHealth(err.message, { overwrite: true });
 
      for (const handler of this.handlers.values()) handler(err);
      this.handlers.clear();
      this.addresses = {};
      this.transactions = {};
    };
 
    ws.onopen = () => {
      Iif (this.status !== 'stop') this.status = 'connected';
      this.heartbeat();
    };
  }
 
  private heartbeat() {
    Iif (this.heartbeatTimeout) clearInterval(this.heartbeatTimeout);
 
    this.heartbeatTimeout = setTimeout(() => {
      try {
        this.request({});
      } catch (error) {
        this.logger.error(error, 'Error while refreshing heartbeat', this.clientId);
      }
    }, this.heartbeatInterval);
    Iif (typeof this.heartbeatTimeout.unref === 'function') this.heartbeatTimeout.unref();
  }
 
  /** Closes the WebSocket connection. */
  close() {
    this.status = 'stop';
    this.ws.close();
 
    return this.closePromise;
  }
 
  /**
   * Sends a request through WS to server.
   *
   * @param request the request.
   * @returns `true` is sent, otherwise `false`.
   */
  private request(request: WSMessage, handler?: WSHandler) {
    Iif (this.status !== 'connected') return false;
 
    // Heartbeat messages do not expect a response, so they neither need a requestId, ...
    Iif (Object.keys(request).length > 0)
      // ... otherwise add requestId
      request = { ...request, requestId: ++this.requestId };
 
    this.logger.debug('CardanoWsClient request', request);
    this.ws.send(JSON.stringify(request));
    this.heartbeat();
 
    Iif (request.requestId && handler) this.handlers.set(request.requestId, handler);
 
    return true;
  }
 
  private transactionsByAddresses(args: TransactionsByAddressesArgs) {
    const { addresses, blockRange, pagination } = args;
 
    // eslint-disable-next-line sonarjs/cognitive-complexity
    return new Promise<Paginated<Cardano.HydratedTx>>((resolve, reject) => {
      const lower = blockRange?.lowerBound || (0 as Cardano.BlockNo);
      const upper = blockRange?.upperBound || Number.POSITIVE_INFINITY;
      const requestAddresses: Cardano.PaymentAddress[] = [];
      const request = { addresses: requestAddresses, lower };
 
      this.logger.debug('CardanoWsClient.transactionsByAddresses called', args);
 
      const complete = (error?: Error): void => {
        Iif (error) {
          for (const address of requestAddresses) delete this.addresses[address];
          this.logger.error('CardanoWsClient.transactionsByAddresses error', args, error);
 
          return reject(error);
        }
 
        const transactions = Object.values(this.transactions)
          .filter(({ blockHeader: { blockNo } }) => lower <= blockNo && blockNo <= upper)
          .filter((tx) => isTxRelevant(tx, addresses))
          .sort((a, b) => a.blockHeader.blockNo - b.blockHeader.blockNo || a.index - b.index);
 
        const first = pagination?.startAt || 0;
        const last = first + (pagination?.limit || Number.POSITIVE_INFINITY);
 
        const pageResults = transactions.filter((_, i) => first <= i && i < last);
        const result = { pageResults, totalResultCount: transactions.length };
 
        this.logger.debug('CardanoWsClient.transactionsByAddresses response', args, toSerializableObject(result));
 
        resolve(result);
      };
 
      // Check which addresses require sync
      for (const address of addresses) {
        const status = this.addresses[address];
        let toSend = false;
 
        if (status) {
          Iif (status.status === 'syncing')
            return complete(new ProviderError(ProviderFailure.Conflict, null, `${address} still loading`));
          Iif (lower < status.lower) toSend = true;
        } else toSend = true;
 
        Iif (toSend) {
          requestAddresses.push(address);
          this.addresses[address] = { lower, status: 'syncing' };
        }
      }
 
      firstValueFrom(this.health$.pipe(filter(({ reason }) => reason !== 'starting')))
        .then(({ ok, reason }) => {
          Iif (!ok) return complete(new ProviderError(ProviderFailure.ConnectionFailure, undefined, reason));
 
          // If no addresses need to be synced, just run complete
          Iif (requestAddresses.length === 0) return complete();
 
          this.deferRequest(request, (error) => {
            Iif (error) return complete(new ProviderError(ProviderFailure.ConnectionFailure, error, error.message));
 
            for (const address of requestAddresses) this.addresses[address].status = 'synced';
 
            complete();
          });
        })
        // This should actually never happen
        .catch(complete);
    });
  }
 
  private deferRequest(txsByAddresses: TxsByAddresses, complete: (error?: Error) => void) {
    const { requests, timeout } = this.deferredRequests;
 
    Iif (timeout) clearTimeout(timeout);
 
    requests.push({ complete, txsByAddresses });
 
    this.deferredRequests.timeout = setTimeout(() => {
      this.deferredRequests = { requests: [] };
      this.request(
        {
          txsByAddresses: requests.reduce(
            (prev, { txsByAddresses: { addresses, lower } }) => ({
              addresses: [...prev.addresses, ...addresses],
              lower: prev.lower < lower ? prev.lower : lower
            }),
            { addresses: [], lower: Number.POSITIVE_INFINITY as Cardano.BlockNo } as TxsByAddresses
          )
        },
        // eslint-disable-next-line @typescript-eslint/no-shadow, unicorn/no-array-for-each
        (error) => requests.forEach(({ complete }) => complete(error))
      );
    }, 3);
  }
 
  // eslint-disable-next-line sonarjs/cognitive-complexity, complexity
  private utxoByAddresses({ addresses }: UtxoByAddressesArgs) {
    this.logger.debug('CardanoWsClient.utxoByAddresses called', addresses);
 
    for (const address of addresses) {
      const status = this.addresses[address];
      let details: string;
 
      Iif (!status) {
        this.logger.error('CardanoWsClient.utxoByAddresses error', (details = `${address} not loaded`));
 
        return Promise.reject(new ProviderError(ProviderFailure.NotImplemented, null, details));
      }
 
      Iif (status.status === 'syncing') {
        this.logger.error('CardanoWsClient.utxoByAddresses error', (details = `${address} still loading`));
 
        return Promise.reject(new ProviderError(ProviderFailure.Conflict, null, details));
      }
    }
 
    const result: [Cardano.HydratedTxIn, Cardano.TxOut][] = [];
    const transactions = [...Object.values(this.utxos), ...Object.values(this.transactions)]
      .filter((tx) => isTxRelevant(tx, addresses))
      .sort((a, b) => a.blockHeader.blockNo - b.blockHeader.blockNo || a.index - b.index);
 
    for (let txOutIdx = 0; txOutIdx < transactions.length; ++txOutIdx) {
      const txOut = transactions[txOutIdx];
 
      for (let txOutOutIdx = 0; txOutOutIdx < txOut.body.outputs.length; ++txOutOutIdx) {
        const txOutput = txOut.body.outputs[txOutOutIdx];
 
        Iif (addresses.includes(txOutput.address)) {
          let unspent = true;
 
          for (let txInIdx = txOutIdx + 1; txInIdx < transactions.length && unspent; ++txInIdx) {
            const txIn = transactions[txInIdx];
 
            for (let txInInIdx = 0; txInInIdx < txIn.body.inputs.length && unspent; ++txInInIdx) {
              const txInput = txIn.body.inputs[txInInIdx];
 
              Iif (txInput.txId === txOut.id && txInput.index === txOutOutIdx) unspent = false;
            }
          }
 
          Iif (unspent) result.push([{ address: txOutput.address, index: txOutOutIdx, txId: txOut.id }, txOutput]);
        }
      }
    }
 
    this.logger.debug('CardanoWsClient.utxoByAddresses response', toSerializableObject(result));
 
    return Promise.resolve(result);
  }
}