Skip to content

Commit

Permalink
refactor: remove hiro api client lib
Browse files Browse the repository at this point in the history
  • Loading branch information
fbwoolf committed Jun 7, 2024
1 parent ba0ab05 commit 4975417
Show file tree
Hide file tree
Showing 40 changed files with 390 additions and 628 deletions.
13 changes: 0 additions & 13 deletions packages/models/src/fees/stacks-fees.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,3 @@ export interface StacksFeeEstimate {
fee: Money;
feeRate: number;
}

export interface ApiFeeEstimation {
fee: number;
fee_rate: number;
}

export interface StacksTxFeeEstimation {
cost_scalar_change_by_byte: number;
estimated_cost: object;
estimated_cost_scalar: number;
estimations: ApiFeeEstimation[];
error?: string;
}
3 changes: 0 additions & 3 deletions packages/query/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export * from './src/common/market-data/vendors/coingecko-market-data.query';
export * from './src/common/remote-config/remote-config.query';
export * from './src/stacks/balance/account-balance.hooks';
export * from './src/stacks/balance/account-balance.query';
export * from './src/stacks/bns/bns.hooks';
export * from './src/stacks/bns/bns.query';
export * from './src/stacks/bns/bns.utils';
export * from './src/stacks/contract/contract.hooks';
Expand Down Expand Up @@ -74,9 +73,7 @@ export * from './src/stacks/transactions/transactions-by-id.query';
export * from './src/stacks/transactions/transactions-with-transfers.hooks';
export * from './src/stacks/transactions/transactions-with-transfers.query';
export * from './src/leather-query-provider';
export * from './types/account';
export * from './types/api-types';
export * from './types/contract-types';
export * from './types/inscription';
export * from './types/remote-config';
export * from './types/utxo';
3 changes: 1 addition & 2 deletions packages/query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,10 @@
"@scure/base": "1.1.6",
"@scure/bip32": "1.4.0",
"@scure/btc-signer": "1.3.2",
"@stacks/blockchain-api-client": "6.3.4",
"@stacks/stacks-blockchain-api-types": "6.3.4",
"@stacks/common": "6.13.0",
"@stacks/connect": "7.4.0",
"@stacks/rpc-client": "1.0.3",
"@stacks/stacks-blockchain-api-types": "6.3.4",
"@stacks/transactions": "6.15.0",
"@tanstack/query-sync-storage-persister": "4.35.7",
"@tanstack/react-query": "4.35.7",
Expand Down
7 changes: 4 additions & 3 deletions packages/query/src/common/alex-sdk/alex-sdk.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useCallback } from 'react';

import { Currency, type TokenInfo } from 'alex-sdk';
import { AlexSDK } from 'alex-sdk';
import BigNumber from 'bignumber.js';

import { MarketData, Money, createMarketData, createMarketPair } from '@leather-wallet/models';
import {
convertAmountToFractionalUnit,
Expand All @@ -8,9 +12,6 @@ import {
isDefined,
sortAssetsByName,
} from '@leather-wallet/utils';
import { Currency, type TokenInfo } from 'alex-sdk';
import { AlexSDK } from 'alex-sdk';
import BigNumber from 'bignumber.js';

import { useStxAvailableUnlockedBalance } from '../../stacks/balance/account-balance.hooks';
import { useTransferableSip10Tokens } from '../../stacks/sip10/sip10-tokens.hooks';
Expand Down
7 changes: 7 additions & 0 deletions packages/query/src/hiro-rate-limiter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import PQueue from 'p-queue';

import { HIRO_API_BASE_URL_TESTNET } from '@leather-wallet/models';

import { useCurrentNetworkState } from './leather-query-provider';

const hiroStacksMainnetApiLimiter = new PQueue({
Expand All @@ -25,3 +27,8 @@ export function useHiroApiRateLimiter(): PQueue {
return hiroStacksTestnetApiLimiter;
}
}

export function getHiroApiRateLimiter(url: string): PQueue {
if (url.includes(HIRO_API_BASE_URL_TESTNET)) return hiroStacksTestnetApiLimiter;
return hiroStacksMainnetApiLimiter;
}
10 changes: 5 additions & 5 deletions packages/query/src/stacks/balance/account-balance.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import BigNumber from 'bignumber.js';

import type { Money, StxCryptoAssetBalance } from '@leather-wallet/models';
import { createMoney, subtractMoney, sumMoney } from '@leather-wallet/utils';
import BigNumber from 'bignumber.js';

import {
type AccountBalanceStxKeys,
type AddressBalanceResponse,
AccountBalanceStxKeys,
AddressBalanceResponse,
accountBalanceStxKeys,
} from '../../../types/account';
} from '../hiro-api-types';
import {
useMempoolTxsInboundBalance,
useMempoolTxsOutboundBalance,
Expand Down Expand Up @@ -48,7 +49,6 @@ export function useStxCryptoAssetBalance(address: string) {
});
}

// useCurrentStxAvailableUnlockedBalance
export function useStxAvailableUnlockedBalance(address: string) {
return useStxCryptoAssetBalance(address).data?.unlockedBalance ?? createMoney(0, 'STX');
}
Expand Down
22 changes: 2 additions & 20 deletions packages/query/src/stacks/balance/account-balance.query.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { useQuery } from '@tanstack/react-query';

import { AddressBalanceResponse } from '../../../types/account';
import { useHiroApiRateLimiter } from '../../hiro-rate-limiter';
import { useCurrentNetworkState } from '../../leather-query-provider';
import { AppUseQueryConfig } from '../../query-config';
import { StacksClient, useStacksClient } from '../stacks-client';
Expand All @@ -15,17 +13,7 @@ const balanceQueryOptions = {
} as const;

function fetchAccountBalance(client: StacksClient, signal?: AbortSignal) {
return async (principal: string) => {
// Coercing type with client-side one that's more accurate
return client.accountsApi.getAccountBalance(
{
principal,
},
{
signal,
}
) as Promise<AddressBalanceResponse>;
};
return async (address: string) => client.getAccountBalance(address, signal);
}

type FetchAccountBalanceResp = Awaited<ReturnType<ReturnType<typeof fetchAccountBalance>>>;
Expand All @@ -35,18 +23,12 @@ export function useStacksAccountBalanceQuery<T extends unknown = FetchAccountBal
options?: AppUseQueryConfig<FetchAccountBalanceResp, T>
) {
const client = useStacksClient();
const limiter = useHiroApiRateLimiter();
const network = useCurrentNetworkState();

return useQuery({
enabled: !!address,
queryKey: ['get-address-stx-balance', address, network.id],
queryFn: async ({ signal }) => {
return limiter.add(() => fetchAccountBalance(client, signal)(address), {
signal,
throwOnTimeout: true,
});
},
queryFn: async ({ signal }) => fetchAccountBalance(client, signal)(address),
...balanceQueryOptions,
...options,
});
Expand Down
7 changes: 0 additions & 7 deletions packages/query/src/stacks/bns/bns.hooks.ts

This file was deleted.

37 changes: 5 additions & 32 deletions packages/query/src/stacks/bns/bns.query.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { BnsNamesOwnByAddressResponse } from '@stacks/stacks-blockchain-api-types';
import { useQuery } from '@tanstack/react-query';

import { useHiroApiRateLimiter } from '../../hiro-rate-limiter';
import { useCurrentNetworkState } from '../../leather-query-provider';
import { AppUseQueryConfig } from '../../query-config';
import { QueryPrefixes } from '../../query-prefixes';
import { StacksClient, useStacksClient } from '../stacks-client';
import { useStacksClient } from '../stacks-client';
import { fetchNamesForAddress } from './bns.utils';

const staleTime = 24 * 60 * 60 * 1000; // 24 hours
Expand All @@ -18,43 +17,17 @@ const bnsQueryOptions = {
refetchOnReconnect: false,
} as const;

type BnsNameFetcher = (address: string) => Promise<BnsNamesOwnByAddressResponse>;

interface GetBnsNameFetcherFactoryArgs {
client: StacksClient;
isTestnet: boolean;
signal?: AbortSignal;
}

function getBnsNameFetcherFactory({
client,
isTestnet,
signal,
}: GetBnsNameFetcherFactoryArgs): BnsNameFetcher {
return async (address: string) => {
return fetchNamesForAddress({ client, address, isTestnet, signal });
};
}

type BnsNameFetcherResp = Awaited<ReturnType<ReturnType<typeof getBnsNameFetcherFactory>>>;

export function useGetBnsNamesOwnedByAddress<T extends unknown = BnsNameFetcherResp>(
export function useGetBnsNamesOwnedByAddressQuery<T extends unknown = BnsNamesOwnByAddressResponse>(
address: string,
options?: AppUseQueryConfig<BnsNameFetcherResp, T>
options?: AppUseQueryConfig<BnsNamesOwnByAddressResponse, T>
) {
const client = useStacksClient();
const limiter = useHiroApiRateLimiter();
const { isTestnet } = useCurrentNetworkState();

return useQuery({
enabled: address !== '',
queryKey: [QueryPrefixes.BnsNamesByAddress, address],
queryFn: async ({ signal }) => {
return limiter.add(() => fetchNamesForAddress({ client, address, isTestnet, signal }), {
signal,
priority: 2,
throwOnTimeout: true,
});
},
queryFn: async ({ signal }) => fetchNamesForAddress({ client, address, isTestnet, signal }),
...bnsQueryOptions,
...options,
});
Expand Down
31 changes: 15 additions & 16 deletions packages/query/src/stacks/bns/bns.utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { parseZoneFile } from '@fungible-systems/zone-file';
import { isString, isUndefined } from '@leather-wallet/utils';
import { asciiToBytes, bytesToAscii } from '@stacks/common';
import { BnsNamesOwnByAddressResponse } from '@stacks/stacks-blockchain-api-types';
import {
Expand All @@ -17,6 +16,8 @@ import {
} from '@stacks/transactions';
import { principalToString } from '@stacks/transactions/dist/esm/clarity/types/principalCV';

import { isString, isUndefined } from '@leather-wallet/utils';

import { StacksClient } from '../stacks-client';

const bnsContractConsts = {
Expand All @@ -33,18 +34,16 @@ async function fetchBnsxName(
try {
const addressCV = standardPrincipalCV(address);
const addressHex = cvToHex(addressCV);
const res = await client.smartContractsApi.callReadOnlyFunction(
{
...bnsContractConsts,
functionName: 'get-primary-name',
tip: 'latest',
readOnlyFunctionArgs: {
sender: address,
arguments: [addressHex],
},
const res = await client.callReadOnlyFunction({
...bnsContractConsts,
functionName: 'get-primary-name',
tip: 'latest',
readOnlyFunctionArgs: {
sender: address,
arguments: [addressHex],
},
{ signal }
);
signal,
});
if (!res.okay || !res.result) return null;
const { result } = res;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
Expand Down Expand Up @@ -79,7 +78,7 @@ async function fetchBnsxOwner(client: StacksClient, fqn: string): Promise<string
namespace: bufferCV(asciiToBytes(namespace)),
});

const res = await client.smartContractsApi.callReadOnlyFunction({
const res = await client.callReadOnlyFunction({
...bnsContractConsts,
functionName: 'get-name-properties',
tip: 'latest',
Expand Down Expand Up @@ -118,7 +117,7 @@ export async function fetchNamesForAddress({
signal,
}: FetchNamesForAddressArgs): Promise<BnsNamesOwnByAddressResponse> {
const fetchFromApi = async () => {
return client.namesApi.getNamesOwnedByAddress({ address, blockchain: 'stacks' }, { signal });
return client.getNamesOwnedByAddress(address, signal);
};
if (isTestnet) {
return fetchFromApi();
Expand All @@ -144,7 +143,7 @@ export async function fetchNamesForAddress({
*/
export async function fetchNameOwner(client: StacksClient, name: string, isTestnet: boolean) {
const fetchFromApi = async () => {
const res = await client.namesApi.getNameInfo({ name });
const res = await client.getNameInfo(name);
if (isUndefined(res.address)) return null;
if (!isString(res.address) || res.address.length === 0) return null;
return res.address;
Expand All @@ -169,7 +168,7 @@ export async function fetchBtcNameOwner(
name: string
): Promise<string | null> {
try {
const nameResponse = await client.namesApi.getNameInfo({ name });
const nameResponse = await client.getNameInfo(name);
const zonefile = parseZoneFile(nameResponse.zonefile);
if (!zonefile.txt) return null;
const btcRecord = zonefile.txt.find(record => record.name === '_btc._addr');
Expand Down
4 changes: 2 additions & 2 deletions packages/query/src/stacks/contract/contract.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { ContractCallPayload, TransactionPayload } from '@stacks/connect';
import type { ContractInterfaceFunction } from '@stacks/rpc-client';

import { useGetContractInterface } from './contract.query';
import { useGetContractInterfaceQuery } from './contract.query';

export function useContractInterface(transactionRequest: ContractCallPayload | null) {
return useGetContractInterface(transactionRequest).data;
return useGetContractInterfaceQuery(transactionRequest).data;
}

export function useContractFunction(transactionRequest: TransactionPayload | null) {
Expand Down
18 changes: 3 additions & 15 deletions packages/query/src/stacks/contract/contract.query.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,16 @@
import { type ContractCallPayload, TransactionTypes } from '@stacks/connect';
import { useQuery } from '@tanstack/react-query';

import type { ContractInterfaceResponseWithFunctions } from '../../../types/contract-types';
import { useHiroApiRateLimiter } from '../../hiro-rate-limiter';
import { useStacksClient } from '../stacks-client';

export function useGetContractInterface(transactionRequest: ContractCallPayload | null) {
const { smartContractsApi } = useStacksClient();
const limiter = useHiroApiRateLimiter();
export function useGetContractInterfaceQuery(transactionRequest: ContractCallPayload | null) {
const client = useStacksClient();

async function fetchContractInterface() {
if (!transactionRequest || transactionRequest?.txType !== TransactionTypes.ContractCall) return;
const contractAddress = transactionRequest.contractAddress;
const contractName = transactionRequest.contractName;
return limiter.add(
() =>
smartContractsApi.getContractInterface({
contractAddress,
contractName,
}) as unknown as Promise<ContractInterfaceResponseWithFunctions>,
{
throwOnTimeout: true,
}
);
return client.getContractInterface(contractAddress, contractName);
}

return useQuery({
Expand Down
16 changes: 6 additions & 10 deletions packages/query/src/stacks/fees/fees.hooks.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import { useMemo } from 'react';

import {
FeeCalculationTypes,
Fees,
Money,
StacksFeeEstimate,
StacksTxFeeEstimation,
} from '@leather-wallet/models';
import { createMoney } from '@leather-wallet/utils';
import { StacksTransaction } from '@stacks/transactions';

import { FeeCalculationTypes, Fees, Money, StacksFeeEstimate } from '@leather-wallet/models';
import { createMoney } from '@leather-wallet/utils';

import {
useConfigFeeEstimationsMaxEnabled,
useConfigFeeEstimationsMaxValues,
useConfigFeeEstimationsMinEnabled,
useConfigFeeEstimationsMinValues,
} from '../../common/remote-config/remote-config.query';
import { StacksTxFeeEstimation } from '../hiro-api-types';
import { useGetStacksTransactionFeeEstimationQuery } from './fees.query';
import {
defaultFeesMaxValuesAsMoney,
Expand Down Expand Up @@ -56,7 +52,7 @@ function parseStacksTxFeeEstimationResponse({
minValues,
txByteLength,
}: ParseStacksTxFeeEstimationResponseArgs): Fees {
if (!!feeEstimation.error) return defaultStacksFees;
if (feeEstimation.error) return defaultStacksFees;
if (txByteLength && feeEstimationQueryFailedSilently(feeEstimation)) {
return {
blockchain: 'stacks',
Expand All @@ -72,7 +68,7 @@ function parseStacksTxFeeEstimationResponse({
};
});

if (feeEstimation.estimations && feeEstimation.estimations.length) {
if (feeEstimation.estimations?.length) {
const feeEstimationsWithCappedValues = getFeeEstimationsWithCappedValues(
stacksFeeEstimates,
maxValues,
Expand Down
Loading

0 comments on commit 4975417

Please sign in to comment.