All files / src/UtxoProvider BlockfrostUtxoProvider.ts

94.73% Statements 90/95
76.47% Branches 13/17
100% Functions 34/34
94.38% Lines 84/89

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 28619x 19x   19x 19x                           19x                                 24x 24x 24x       24x 24x 24x       5x 5x   5x 202x 202x 202x     5x       8x 16x 16x 16x     8x       6x         6x 6x       6x             2x         2x 2x         5x     2x               2x               8x     16x     8x             8x         8x                       8x 8x 8x 8x   8x                 8x 6x   8x             8x   2x     8x       11x   3x 5x       11x             8x 8x       8x   8x   8x         8x   8x   8x       8x           8x   8x   8x       217x   17x       200x       218x 218x   217x   17x 17x 17x     200x 200x     217x 200x     17x 17x                         11x   11x 3x       8x            
import { BlockfrostClient, BlockfrostProvider, BlockfrostToCore, fetchSequentially } from '../blockfrost';
import { Cardano, Serialization, UtxoByAddressesArgs, UtxoProvider, sortUtxoByTxIn } from '@cardano-sdk/core';
import { Logger } from 'ts-log';
import { createPaymentCredentialFilter, extractCredentials, minimizeCredentialSet } from '../credentialUtils';
import uniqBy from 'lodash/uniqBy.js';
import type { Cache } from '@cardano-sdk/util';
import type { Responses } from '@blockfrost/blockfrost-js';
 
interface BlockfrostUtxoProviderOptions {
  queryUtxosByCredentials?: boolean;
}
 
interface BlockfrostUtxoProviderDependencies {
  client: BlockfrostClient;
  cache: Cache<Cardano.Tx>;
  logger: Logger;
}
 
export class BlockfrostUtxoProvider extends BlockfrostProvider implements UtxoProvider {
  private readonly cache: Cache<Cardano.Tx>;
  // Feature flag to enable credential-based UTXO fetching (used in utxoByAddresses)
  protected readonly queryUtxosByCredentials: boolean;
 
  // Overload 1: Old signature (backward compatibility)
  constructor(dependencies: BlockfrostUtxoProviderDependencies);
 
  // Overload 2: New signature with options
  constructor(options: BlockfrostUtxoProviderOptions, dependencies: BlockfrostUtxoProviderDependencies);
 
  // Implementation signature
  constructor(
    optionsOrDependencies: BlockfrostUtxoProviderOptions | BlockfrostUtxoProviderDependencies,
    maybeDependencies?: BlockfrostUtxoProviderDependencies
  ) {
    // Detect which overload was used
    const isOldSignature = 'cache' in optionsOrDependencies;
    const options = isOldSignature ? {} : (optionsOrDependencies as BlockfrostUtxoProviderOptions);
    const dependencies = isOldSignature
      ? (optionsOrDependencies as BlockfrostUtxoProviderDependencies)
      : maybeDependencies!;
 
    super(dependencies.client, dependencies.logger);
    this.cache = dependencies.cache;
    this.queryUtxosByCredentials = options.queryUtxosByCredentials ?? false;
  }
 
  protected async fetchUtxos(addr: Cardano.PaymentAddress, paginationQueryString: string): Promise<Cardano.Utxo[]> {
    const queryString = `addresses/${addr.toString()}/utxos?${paginationQueryString}`;
    const utxos = await this.request<Responses['address_utxo_content']>(queryString);
 
    const utxoPromises = utxos.map((utxo) =>
      this.fetchDetailsFromCBOR(utxo.tx_hash).then((tx) => {
        const txOut = tx ? tx.body.outputs.find((output) => output.address === utxo.address) : undefined;
        return BlockfrostToCore.addressUtxoContent(addr.toString(), utxo, txOut);
      })
    );
    return Promise.all(utxoPromises);
  }
 
  private async processUtxoContents(utxoContents: Responses['address_utxo_content']): Promise<Cardano.Utxo[]> {
    const utxoPromises = utxoContents.map((utxo) =>
      this.fetchDetailsFromCBOR(utxo.tx_hash).then((tx) => {
        const txOut = tx ? tx.body.outputs.find((output) => output.address === utxo.address) : undefined;
        return BlockfrostToCore.addressUtxoContent(utxo.address, utxo, txOut);
      })
    );
    return Promise.all(utxoPromises);
  }
 
  protected async fetchUtxosByPaymentCredential(credential: Cardano.PaymentCredential): Promise<Cardano.Utxo[]> {
    const utxoContents = await fetchSequentially<
      Responses['address_utxo_content'][0],
      Responses['address_utxo_content'][0]
    >({
      request: async (paginationQueryString) => {
        const queryString = `addresses/${credential}/utxos?${paginationQueryString}`;
        return this.request<Responses['address_utxo_content']>(queryString);
      }
    });
 
    return this.processUtxoContents(utxoContents);
  }
 
  protected async fetchUtxosByRewardAccount(
    rewardAccount: Cardano.RewardAccount,
    paymentCredentialFilter: (address: Cardano.PaymentAddress) => boolean
  ): Promise<Cardano.Utxo[]> {
    const utxoContents = await fetchSequentially<
      Responses['address_utxo_content'][0],
      Responses['address_utxo_content'][0]
    >({
      request: async (paginationQueryString) => {
        const queryString = `accounts/${rewardAccount}/utxos?${paginationQueryString}`;
        return this.request<Responses['address_utxo_content']>(queryString);
      }
    });
 
    // Filter UTXOs by payment credential before processing
    const filteredUtxos = utxoContents.filter((utxo) => paymentCredentialFilter(Cardano.PaymentAddress(utxo.address)));
 
    // Log debug message about filtering
    Iif (filteredUtxos.length < utxoContents.length) {
      this.logger.debug(
        `Filtered ${utxoContents.length - filteredUtxos.length} UTXO(s) from reward account query, kept ${
          filteredUtxos.length
        }`
      );
    }
 
    return this.processUtxoContents(filteredUtxos);
  }
 
  protected mergeAndDeduplicateUtxos(
    paymentUtxos: Cardano.Utxo[],
    rewardAccountUtxos: Cardano.Utxo[],
    skippedAddressUtxos: Cardano.Utxo[]
  ): Cardano.Utxo[] {
    const allUtxos = [...paymentUtxos, ...rewardAccountUtxos, ...skippedAddressUtxos];
 
    // Deduplicate by txId + index combination
    const deduplicated = uniqBy(allUtxos, (utxo: Cardano.Utxo) => `${utxo[0].txId}#${utxo[0].index}`);
 
    // Sort using sortUtxoByTxIn from core
    return deduplicated.sort(sortUtxoByTxIn);
  }
 
  private logSkippedAddresses(skippedAddresses: {
    byron: Cardano.PaymentAddress[];
    pointer: Cardano.PaymentAddress[];
  }): void {
    Iif (skippedAddresses.byron.length > 0) {
      this.logger.info(
        `Found ${skippedAddresses.byron.length} Byron address(es), falling back to per-address fetching`
      );
    }
    Iif (skippedAddresses.pointer.length > 0) {
      this.logger.info(
        `Found ${skippedAddresses.pointer.length} Pointer address(es), falling back to per-address fetching`
      );
    }
  }
 
  private logMinimizationStats(
    totalAddresses: number,
    minimized: { paymentCredentials: Map<unknown, unknown>; rewardAccounts: Map<unknown, unknown> },
    skippedAddresses: { byron: Cardano.PaymentAddress[]; pointer: Cardano.PaymentAddress[] }
  ): void {
    const paymentCredCount = minimized.paymentCredentials.size;
    const rewardAccountCount = minimized.rewardAccounts.size;
    const skippedCount = skippedAddresses.byron.length + skippedAddresses.pointer.length;
    const totalQueries = paymentCredCount + rewardAccountCount + skippedCount;
 
    this.logger.debug(
      `Minimized ${totalAddresses} address(es) to ${totalQueries} query/queries: ` +
        `${paymentCredCount} payment credential(s), ${rewardAccountCount} reward account(s), ${skippedCount} skipped address(es)`
    );
  }
 
  private async fetchAllByPaymentCredentials(
    credentials: Map<Cardano.PaymentCredential, Cardano.PaymentAddress[]>
  ): Promise<Cardano.Utxo[]> {
    const results = await Promise.all(
      [...credentials.keys()].map((credential) => this.fetchUtxosByPaymentCredential(credential))
    );
    return results.flat();
  }
 
  private async fetchAllByRewardAccounts(
    rewardAccounts: Map<Cardano.RewardAccount, Cardano.PaymentAddress[]>,
    paymentCredentialFilter: (address: Cardano.PaymentAddress) => boolean
  ): Promise<Cardano.Utxo[]> {
    const results = await Promise.all(
      [...rewardAccounts.keys()].map((rewardAccount) =>
        this.fetchUtxosByRewardAccount(rewardAccount, paymentCredentialFilter)
      )
    );
    return results.flat();
  }
 
  private async fetchUtxosForAddresses(addresses: Cardano.PaymentAddress[]): Promise<Cardano.Utxo[]> {
    const results = await Promise.all(
      addresses.map((address) =>
        fetchSequentially<Cardano.Utxo, Cardano.Utxo>({
          request: async (paginationQueryString) => await this.fetchUtxos(address, paginationQueryString)
        })
      )
    );
    return results.flat();
  }
 
  private async fetchSkippedAddresses(skippedAddresses: {
    byron: Cardano.PaymentAddress[];
    pointer: Cardano.PaymentAddress[];
  }): Promise<Cardano.Utxo[]> {
    const allSkippedAddresses = [...skippedAddresses.byron, ...skippedAddresses.pointer];
    return this.fetchUtxosForAddresses(allSkippedAddresses);
  }
 
  private async fetchUtxosByCredentials(addresses: Cardano.PaymentAddress[]): Promise<Cardano.Utxo[]> {
    const addressGroups = extractCredentials(addresses);
 
    this.logSkippedAddresses(addressGroups.skippedAddresses);
 
    const minimized = minimizeCredentialSet({
      paymentCredentials: addressGroups.paymentCredentials,
      rewardAccounts: addressGroups.rewardAccounts
    });
 
    this.logMinimizationStats(addresses.length, minimized, addressGroups.skippedAddresses);
 
    const paymentCredentialFilter = createPaymentCredentialFilter(addresses);
 
    this.logger.debug(
      `Fetching UTXOs for ${minimized.paymentCredentials.size} payment credential(s) and ${minimized.rewardAccounts.size} reward account(s)`
    );
 
    const [paymentUtxos, rewardAccountUtxos, skippedAddressUtxos] = await Promise.all([
      this.fetchAllByPaymentCredentials(minimized.paymentCredentials),
      this.fetchAllByRewardAccounts(minimized.rewardAccounts, paymentCredentialFilter),
      this.fetchSkippedAddresses(addressGroups.skippedAddresses)
    ]);
 
    const result = this.mergeAndDeduplicateUtxos(paymentUtxos, rewardAccountUtxos, skippedAddressUtxos);
 
    this.logger.debug(`Merged results: ${result.length} UTXO(s)`);
 
    return result;
  }
 
  async fetchCBOR(hash: string): Promise<string> {
    return this.request<Responses['tx_content_cbor']>(`txs/${hash}/cbor`)
      .then((response) => {
        if (response.cbor) return response.cbor;
        throw new Error('CBOR is null');
      })
      .catch((_error) => {
        throw new Error('CBOR fetch failed');
      });
  }
  protected async fetchDetailsFromCBOR(hash: string) {
    const cached = await this.cache.get(hash);
    if (cached) return cached;
 
    const result = await this.fetchCBOR(hash)
      .then((cbor) => {
        const tx = Serialization.Transaction.fromCbor(Serialization.TxCBOR(cbor)).toCore();
        this.logger.debug('Fetched details from CBOR for tx', hash);
        return tx;
      })
      .catch((error) => {
        this.logger.warn('Failed to fetch details from CBOR for tx', hash, error);
        return null;
      });
 
    if (!result) {
      return null;
    }
 
    void this.cache.set(hash, result);
    return result;
  }
 
  /**
   * Retrieves UTXOs for the given addresses.
   *
   * Important assumption: All addresses provided must be addresses where the caller
   * controls the payment credential. When queryUtxosByCredentials is enabled, this
   * provider queries by reward accounts (stake addresses) and filters results to only
   * include UTXOs with payment credentials extracted from the input addresses. UTXOs
   * with payment credentials not present in the input will be excluded.
   */
  public async utxoByAddresses({ addresses }: UtxoByAddressesArgs): Promise<Cardano.Utxo[]> {
    try {
      // If feature flag is disabled, use original implementation
      if (!this.queryUtxosByCredentials) {
        return this.fetchUtxosForAddresses(addresses);
      }
 
      // Use credential-based fetching
      return await this.fetchUtxosByCredentials(addresses);
    } catch (error) {
      throw this.toProviderError(error);
    }
  }
}