All files / app/api api.ts

0% Statements 0/40
0% Branches 0/4
0% Functions 0/18
0% Lines 0/39

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                                                                                                                                                                                                                                                                                                                                                     
import packageJson from '../../package.json';
import { features } from '@constants/index';
import {
  AccountsApi,
  TransactionsApi,
  Configuration,
  SmartContractsApi,
  GetContractDataMapEntryRequest,
  Middleware,
  RequestContext,
} from '@stacks/blockchain-api-client';
import {
  Transaction,
  TransactionResults,
  MempoolTransaction,
  AddressBalanceResponse,
  CoreNodePoxResponse,
  CoreNodeInfoResponse,
  NetworkBlockTimesResponse,
  AddressTransactionsWithTransfersListResponse,
} from '@stacks/stacks-blockchain-api-types';
import axios from 'axios';
import urljoin from 'url-join';
 
const defaultHeaders = [
  { name: 'x-hiro-product', value: 'stacks-wallet-desktop' },
  { name: 'x-hiro-version', value: packageJson.version },
];
 
defaultHeaders.forEach(({ name, value }) => (axios.defaults.headers.common[name] = value));
export class Api {
  unanchoredMiddleware: Middleware = {
    pre: (context: RequestContext) => {
      const url = new URL(context.url);
      url.searchParams.set('unanchored', 'true');
      return Promise.resolve({
        init: context.init,
        url: url.toString(),
      });
    },
  };
  stacksApiConfig = new Configuration({
    basePath: this.baseUrl,
    headers: defaultHeaders.reduce((acc: Record<string, string>, hdr) => {
      acc[hdr.name] = hdr.value;
      return acc;
    }, {}),
    middleware: features.microblocks ? [this.unanchoredMiddleware] : [],
  });
 
  accountsApi = new AccountsApi(this.stacksApiConfig);
  transactionApi = new TransactionsApi(this.stacksApiConfig);
  smartContractsApi = new SmartContractsApi(this.stacksApiConfig);
 
  constructor(public baseUrl: string) {}
 
  async getAddressBalance(address: string) {
    return axios.get<AddressBalanceResponse>(
      urljoin(this.baseUrl, `/extended/v1/address/${address}/balances`),
      { params: { unanchored: true } }
    );
  }
 
  async getNonce(address: string) {
    const { data } = await axios.get(
      urljoin(this.baseUrl, `extended/v1/address/${address}/nonces`),
      { params: { unanchored: true } }
    );
    return data;
  }
 
  async getAddressTransactions(address: string) {
    return axios.get<TransactionResults>(
      urljoin(this.baseUrl, `/extended/v1/address/${address}/transactions`),
      {
        params: {
          limit: 50,
          unanchored: true,
        },
      }
    );
  }
 
  async getAddressTransactionsWithTransfers(address: string) {
    return axios.get<AddressTransactionsWithTransfersListResponse>(
      urljoin(this.baseUrl, `/extended/v1/address/${address}/transactions_with_transfers`),
      {
        params: {
          limit: 50,
          unanchored: true,
        },
      }
    );
  }
 
  async getTxDetails(txid: string) {
    return axios.get<Transaction | MempoolTransaction>(
      urljoin(this.baseUrl, `/extended/v1/tx/${txid}`)
    );
  }
 
  async getFaucetStx(address: string, stacking?: boolean) {
    return axios.post(
      urljoin(
        this.baseUrl,
        `/extended/v1/faucets/stx?address=${address}${stacking ? '&stacking=true' : ''}`
      )
    );
  }
 
  async getFeeRate() {
    return axios.get<string>(urljoin(this.baseUrl, `/v2/fees/transfer`));
  }
 
  async getPoxInfo() {
    return axios.get<CoreNodePoxResponse>(urljoin(this.baseUrl, `/v2/pox`));
  }
 
  async getNodeStatus() {
    return axios.get(urljoin(this.baseUrl, `/extended/v1/status`));
  }
 
  async getCoreDetails() {
    return axios.get<CoreNodeInfoResponse>(urljoin(this.baseUrl, `/v2/info`));
  }
 
  async getNetworkBlockTimes() {
    return axios.get<NetworkBlockTimesResponse>(
      urljoin(this.baseUrl, `/extended/v1/info/network_block_times`)
    );
  }
 
  async getContractDataMapEntry(args: GetContractDataMapEntryRequest) {
    return this.smartContractsApi.getContractDataMapEntry({ ...args, proof: 0 });
  }
 
  async getMempoolTransactions(address: string): Promise<MempoolTransaction[]> {
    const mempoolTxs = await axios.get(
      urljoin(this.baseUrl, `/extended/v1/tx/mempool?limit=50&address=${address}`),
      { params: { unanchored: true } }
    );
    return mempoolTxs.data.results;
  }
 
  async callReadOnly({
    contract,
    functionName,
    args,
  }: {
    contract: string;
    functionName: string;
    args: string[];
  }) {
    const [contractAddress, contractName] = contract.split('.');
    const url = urljoin(
      this.baseUrl,
      `/v2/contracts/call-read/${contractAddress}/${contractName}/${functionName}`
    );
    const body = {
      sender: 'ST384HBMC97973427QMM58NY2R9TTTN4M599XM5TD',
      arguments: args,
    };
    const response = await axios.post(url, body, {
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.data.result as string;
  }
}