All files / src/api utils.ts

72.88% Statements 86/118
17.64% Branches 6/34
78.94% Functions 30/38
73.39% Lines 80/109

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          21x   21x   21x                             21x                           21x                         21x       55x 55x 55x 26x 26x 6x       6x 3x   3x     55x               21x 20x     21x 17x     21x 82x     21x 2x     21x 4x     21x 2x     21x 10x     21x 18x     21x 4x     21x 8x     21x 5x     21x 2x     21x 8x     21x 2x     21x 2x     21x 2x     21x 2x     21x 2x     21x 2x     21x 10x     21x       21x 2x     21x 2x     21x 2x     21x 2x     21x       21x 53x 53x     21x       4x         4x             4x 4x     21x 2x       2x       2x 2x     21x                  
import {
  MempoolTransaction,
  Transaction,
  TransactionType,
} from '@stacks/stacks-blockchain-api-types';
import { fetchPrivate } from 'micro-stacks/common';
 
export const isNumber = (value: number | string): value is number => typeof value === 'number';
 
export function parseTxTypeStrings(values: string[]): TransactionType[] {
  return values.map(v => {
    switch (v) {
      case 'contract_call':
      case 'smart_contract':
      case 'token_transfer':
      case 'coinbase':
      case 'poison_microblock':
        return v;
      default:
        throw new Error(`Unexpected tx type: ${JSON.stringify(v)}`);
    }
  });
}
 
export const validateTxTypes = (typeQuery: TransactionType[] | TransactionType) => {
  let txTypeFilter: TransactionType[];
  if (Array.isArray(typeQuery)) {
    txTypeFilter = parseTxTypeStrings(typeQuery as string[]);
  } else if (typeof typeQuery === 'string') {
    txTypeFilter = parseTxTypeStrings([typeQuery]);
  } else if (typeQuery) {
    throw new Error(`Unexpected tx type query value: ${JSON.stringify(typeQuery)}`);
  } else {
    txTypeFilter = [];
  }
  return txTypeFilter;
};
 
export const generateQueryStringFromArray = <T>(key: string, values?: T[]) => {
  Iif (values?.length) {
    return `${values
      .map(
        (value, index) =>
          `${index > 0 ? encodeURIComponent(`${key}[]`) : ''}=${encodeURIComponent(
            value as unknown as string
          )}`
      )
      .join('&')}`;
  }
  return '';
};
export const generateUrl = <Value = unknown>(
  baseUrl: string,
  params: { [key: string]: string[] | string | number | boolean | undefined }
): string => {
  try {
    const url = new URL(baseUrl);
    Object.keys(params).forEach(key => {
      const value = params[key];
      if (!value) return;
      Iif (Array.isArray(value)) {
        Iif (value.length === 0) return;
        return url.searchParams.set(`${key}[]`, generateQueryStringFromArray<string>(key, value));
      }
      if (typeof value == 'boolean' || isNumber(value)) {
        return url.searchParams.set(key, String(value));
      } else {
        url.searchParams.set(key, value);
      }
    });
    return url.toString();
  } catch (e) {
    console.error('generateUrl');
    console.error(e);
    return baseUrl;
  }
};
 
export function v1Endpoint(url: string) {
  return `${url}/v1`;
}
 
export function v2Endpoint(url: string) {
  return `${url}/v2`;
}
 
export function extendedEndpoint(url: string) {
  return `${url}/extended/v1`;
}
 
export function statusEndpoint(url: string) {
  return `${extendedEndpoint(url)}/status`;
}
 
export function searchEndpoint(url: string) {
  return `${extendedEndpoint(url)}/search`;
}
 
export function feeRateEndpoint(url: string) {
  return `${extendedEndpoint(url)}/fee_rate`;
}
 
export function burnchainEndpoint(url: string) {
  return `${extendedEndpoint(url)}/burnchain`;
}
 
export function blockEndpoint(url: string) {
  return `${extendedEndpoint(url)}/block`;
}
 
export function contractEndpoint(url: string) {
  return `${extendedEndpoint(url)}/contract`;
}
 
export function tokensEndpoint(url: string) {
  return `${extendedEndpoint(url)}/tokens`;
}
 
export function contractsEndpoint(url: string) {
  return `${v2Endpoint(url)}/contracts`;
}
 
export function feesEndpoint(url: string) {
  return `${v2Endpoint(url)}/fees/transfers`;
}
 
export function microblockEndpoint(url: string) {
  return `${extendedEndpoint(url)}/microblock`;
}
 
export function stxFaucetEndpoint(url: string) {
  return `${extendedEndpoint(url)}/faucets/stx`;
}
 
export function btcFaucetEndpoint(url: string) {
  return `${extendedEndpoint(url)}/faucets/btc`;
}
 
export function stxSupplyEndpoint(url: string) {
  return `${extendedEndpoint(url)}/stx_supply`;
}
 
export function stxSupplyPlainEndpoint(url: string) {
  return `${extendedEndpoint(url)}/stx_supply/total/plain`;
}
 
export function stxSupplyCirculatingPlainEndpoint(url: string) {
  return `${extendedEndpoint(url)}/stx_supply/circulating/plain`;
}
 
export function stxSupplyLegacyFormatEndpoint(url: string) {
  return `${extendedEndpoint(url)}/stx_supply/legacy_format`;
}
 
export function addressEndpoint(url: string) {
  return `${extendedEndpoint(url)}/address`;
}
 
export function txEndpoint(url: string) {
  return `${extendedEndpoint(url)}/tx`;
}
 
export function infoEndpoint(url: string) {
  return `${v2Endpoint(url)}/info`;
}
 
export function poxEndpoint(url: string) {
  return `${v2Endpoint(url)}/pox`;
}
 
export function networkBlockTimesEndpoint(url: string) {
  return `${extendedEndpoint(url)}/info/network_block_times`;
}
 
export function networkBlockTimeEndpoint(url: string) {
  return `${extendedEndpoint(url)}/info/network_block_time`;
}
 
export function txMempoolEndpoint(url: string) {
  return `${txEndpoint(url)}/mempool`;
}
 
export async function fetchJson<T>(path: string) {
  const res = await fetchPrivate(path);
  return (await res.json()) as T;
}
 
export async function fetchJsonPost<T>(
  path: string,
  options: Omit<RequestInit, 'body'> & { body?: unknown } = {}
) {
  const requestHeaders = {
    'Content-Type': 'application/json; charset=utf-8',
    Accept: 'application/json',
  };
 
  const contents = options.body ? JSON.stringify(options.body) : undefined;
  const fetchOptions = {
    ...options,
    method: 'POST',
    body: contents,
    headers: requestHeaders,
  };
  const res = await fetchPrivate(path, fetchOptions);
  return (await res.json()) as T;
}
 
export async function fetchText<T>(path: string): Promise<string> {
  const requestHeaders = {
    Accept: 'text/plain',
  };
 
  const fetchOptions = {
    method: 'GET',
    headers: requestHeaders,
  };
  const res = await fetchPrivate(path, fetchOptions);
  return res.text();
}
 
export function getNextPageParam(options: { limit: number; offset: number; total: number }) {
  Iif (!options) return 0;
  const { limit, offset, total } = options;
  const sum = offset + limit;
  const delta = total - sum;
  const isAtEnd = delta === 0 || Math.sign(delta) === -1;
  Iif (Math.abs(delta) === sum || isAtEnd) return undefined;
  return sum;
}