Skip to content

Commit

Permalink
Merge pull request #5295 from leather-wallet/release/rate-limiter
Browse files Browse the repository at this point in the history
Release/rate limiter
  • Loading branch information
fbwoolf authored Apr 24, 2024
2 parents 69cc924 + b4d73f8 commit 36c0ae2
Show file tree
Hide file tree
Showing 93 changed files with 740 additions and 636 deletions.
39 changes: 39 additions & 0 deletions src/app/common/asset-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { MarketData } from '@shared/models/market.model';
import type { Money } from '@shared/models/money.model';

import { baseCurrencyAmountInQuote } from './money/calculate-money';
import { i18nFormatCurrency } from './money/format-money';
import { isMoneyGreaterThanZero } from './money/money.utils';

export function sortAssetsByName<T extends { name: string }[]>(assets: T) {
return assets
.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
})
.sort((a, b) => {
if (a.name === 'STX') return -1;
if (b.name !== 'STX') return 1;
return 0;
})
.sort((a, b) => {
if (a.name === 'BTC') return -1;
if (b.name !== 'BTC') return 1;
return 0;
});
}

export function migratePositiveAssetBalancesToTop<T extends { balance: Money }[]>(assets: T) {
const assetsWithPositiveBalance = assets.filter(asset => asset.balance.amount.isGreaterThan(0));
const assetsWithZeroBalance = assets.filter(asset => asset.balance.amount.isEqualTo(0));
return [...assetsWithPositiveBalance, ...assetsWithZeroBalance] as T;
}

export function convertAssetBalanceToFiat<
T extends { balance: Money | null; marketData: MarketData | null },
>(asset: T) {
if (!asset.marketData || !asset.balance || !isMoneyGreaterThanZero(asset.marketData.price))
return '';
return i18nFormatCurrency(baseCurrencyAmountInQuote(asset.balance, asset.marketData));
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { StacksFungibleTokenAsset } from '@shared/models/crypto-asset.model';
import { createMoney } from '@shared/models/money.model';

import {
isFtNameLikeStx,
Expand Down Expand Up @@ -32,7 +31,7 @@ describe(isTransferableStacksFungibleTokenAsset.name, () => {
canTransfer: true,
hasMemo: true,
imageCanonicalUri: '',
price: createMoney(0, 'USD'),
marketData: null,
symbol: 'CAT',
};
expect(isTransferableStacksFungibleTokenAsset(asset)).toBeTruthy();
Expand All @@ -49,7 +48,7 @@ describe(isTransferableStacksFungibleTokenAsset.name, () => {
canTransfer: true,
hasMemo: true,
imageCanonicalUri: '',
price: createMoney(0, 'USD'),
marketData: null,
symbol: 'CAT',
};
expect(isTransferableStacksFungibleTokenAsset(asset)).toBeTruthy();
Expand Down
25 changes: 13 additions & 12 deletions src/app/common/hooks/account/use-account-names.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import { isUndefined } from '@shared/utils';

import { parseIfValidPunycode } from '@app/common/utils';
import { getAutogeneratedAccountDisplayName } from '@app/common/utils/get-account-display-name';
import {
useCurrentAccountNames,
useGetAccountNamesByAddressQuery,
} from '@app/query/stacks/bns/bns.hooks';
import { useCurrentAccountNames } from '@app/query/stacks/bns/bns.hooks';
import { useGetBnsNamesOwnedByAddress } from '@app/query/stacks/bns/bns.query';
import { useCurrentStacksAccount } from '@app/store/accounts/blockchain/stacks/stacks-account.hooks';

export function useCurrentAccountDisplayName() {
Expand All @@ -23,12 +21,15 @@ export function useCurrentAccountDisplayName() {
}

export function useAccountDisplayName({ address, index }: { index: number; address: string }) {
const { data: names = [], isLoading } = useGetAccountNamesByAddressQuery(address);
return useMemo(() => {
const name = names[0] || getAutogeneratedAccountDisplayName(index);
return {
name,
isLoading,
};
}, [names, index, isLoading]);
const query = useGetBnsNamesOwnedByAddress(address, {
select: resp => {
const names = resp.names ?? [];
return names[0] || getAutogeneratedAccountDisplayName(index);
},
});

return {
...query,
data: query.data || getAutogeneratedAccountDisplayName(index),
};
}
8 changes: 5 additions & 3 deletions src/app/common/hooks/balance/btc/use-btc-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { baseCurrencyAmountInQuote } from '@app/common/money/calculate-money';
import { i18nFormatCurrency } from '@app/common/money/format-money';
import { createBitcoinCryptoCurrencyAssetTypeWrapper } from '@app/query/bitcoin/address/address.utils';
import { useNativeSegwitBalance } from '@app/query/bitcoin/balance/btc-native-segwit-balance.hooks';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';

export function useBtcAssetBalance(btcAddress: string) {
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');
const {
btcBalance: btcAssetBalance,
isLoading,
isFetching,
isInitialLoading,
} = useNativeSegwitBalance(btcAddress);

Expand All @@ -28,8 +29,9 @@ export function useBtcAssetBalance(btcAddress: string) {
baseCurrencyAmountInQuote(btcAssetBalance.balance, btcMarketData)
),
isLoading,
isFetching,
isInitialLoading,
}),
[btcAddress, btcAssetBalance, btcMarketData, isLoading, isInitialLoading]
[btcAddress, btcAssetBalance, btcMarketData, isLoading, isInitialLoading, isFetching]
);
}
4 changes: 2 additions & 2 deletions src/app/common/hooks/balance/stx/use-stx-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { isDefined } from '@shared/utils';

import { baseCurrencyAmountInQuote, subtractMoney } from '@app/common/money/calculate-money';
import { i18nFormatCurrency } from '@app/common/money/format-money';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';
import { createStacksCryptoCurrencyAssetTypeWrapper } from '@app/query/stacks/balance/stacks-ft-balances.utils';
import { useCurrentStacksAccountBalances } from '@app/query/stacks/balance/stx-balance.hooks';
import { useCurrentAccountMempoolTransactionsBalance } from '@app/query/stacks/mempool/mempool.hooks';
Expand All @@ -15,7 +15,7 @@ export function useStxBalance() {
const totalBalance = stxBalanceQuery.data?.stx.balance;
const unlockedStxBalance = stxBalanceQuery.data?.stx.unlockedStx;

const stxMarketData = useCryptoCurrencyMarketData('STX');
const stxMarketData = useCryptoCurrencyMarketDataMeanAverage('STX');
const pendingTxsBalance = useCurrentAccountMempoolTransactionsBalance();

const stxEffectiveBalance = isDefined(totalBalance)
Expand Down
17 changes: 13 additions & 4 deletions src/app/common/hooks/balance/use-total-balance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createMoney } from '@shared/models/money.model';

import { baseCurrencyAmountInQuote } from '@app/common/money/calculate-money';
import { i18nFormatCurrency } from '@app/common/money/format-money';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';
import { useStacksAccountBalances } from '@app/query/stacks/balance/stx-balance.hooks';

import { useBtcAssetBalance } from './btc/use-btc-balance';
Expand All @@ -16,17 +16,23 @@ interface UseTotalBalanceArgs {

export function useTotalBalance({ btcAddress, stxAddress }: UseTotalBalanceArgs) {
// get market data
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const stxMarketData = useCryptoCurrencyMarketData('STX');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');
const stxMarketData = useCryptoCurrencyMarketDataMeanAverage('STX');

// get stx balance
const { data: balances, isLoading, isInitialLoading } = useStacksAccountBalances(stxAddress);
const {
data: balances,
isLoading,
isInitialLoading,
isFetching: isFetchingStacksBalance,
} = useStacksAccountBalances(stxAddress);
const stxBalance = balances ? balances.stx.balance : createMoney(0, 'STX');

// get btc balance
const {
btcAvailableAssetBalance,
isLoading: isLoadingBtcBalance,
isFetching: isFetchingBtcBalance,
isInitialLoading: isInititalLoadingBtcBalance,
} = useBtcAssetBalance(btcAddress);

Expand All @@ -44,6 +50,7 @@ export function useTotalBalance({ btcAddress, stxAddress }: UseTotalBalanceArgs)
),
isLoading: isLoading || isLoadingBtcBalance,
isInitialLoading: isInitialLoading || isInititalLoadingBtcBalance,
isFetching: isFetchingStacksBalance || isFetchingBtcBalance,
};
}, [
btcAvailableAssetBalance.balance,
Expand All @@ -54,5 +61,7 @@ export function useTotalBalance({ btcAddress, stxAddress }: UseTotalBalanceArgs)
stxBalance,
isLoading,
isLoadingBtcBalance,
isFetchingStacksBalance,
isFetchingBtcBalance,
]);
}
38 changes: 0 additions & 38 deletions src/app/common/hooks/use-alex-sdk.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/app/common/hooks/use-bitcoin-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { makeRpcErrorResponse, makeRpcSuccessResponse } from '@shared/rpc/rpc-me
import { sendAcceptedBitcoinContractOfferToProtocolWallet } from '@app/query/bitcoin/contract/send-accepted-bitcoin-contract-offer';
import {
useCalculateBitcoinFiatValue,
useCryptoCurrencyMarketData,
useCryptoCurrencyMarketDataMeanAverage,
} from '@app/query/common/market-data/market-data.hooks';
import { useCurrentAccountIndex } from '@app/store/accounts/account';
import {
Expand Down Expand Up @@ -57,7 +57,7 @@ export interface BitcoinContractOfferDetails {
export function useBitcoinContracts() {
const navigate = useNavigate();
const defaultParams = useDefaultRequestParams();
const bitcoinMarketData = useCryptoCurrencyMarketData('BTC');
const bitcoinMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');
const calculateFiatValue = useCalculateBitcoinFiatValue();

const bitcoinAccountDetails = useCurrentAccountNativeSegwitIndexZeroSigner();
Expand Down
11 changes: 0 additions & 11 deletions src/app/common/hooks/use-brc20-tokens.ts

This file was deleted.

21 changes: 4 additions & 17 deletions src/app/common/hooks/use-convert-to-fiat-amount.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,17 @@
import { useCallback, useMemo } from 'react';
import { useCallback } from 'react';

import { CryptoCurrencies } from '@shared/models/currencies.model';
import { createMarketData, createMarketPair } from '@shared/models/market.model';
import type { Money } from '@shared/models/money.model';
import { type Money } from '@shared/models/money.model';

import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';

import { baseCurrencyAmountInQuote } from '../money/calculate-money';

export function useConvertCryptoCurrencyToFiatAmount(currency: CryptoCurrencies) {
const cryptoCurrencyMarketData = useCryptoCurrencyMarketData(currency);
const cryptoCurrencyMarketData = useCryptoCurrencyMarketDataMeanAverage(currency);

return useCallback(
(value: Money) => baseCurrencyAmountInQuote(value, cryptoCurrencyMarketData),
[cryptoCurrencyMarketData]
);
}

export function useConvertAlexSdkCurrencyToFiatAmount(currency: CryptoCurrencies, price: Money) {
const alexCurrencyMarketData = useMemo(
() => createMarketData(createMarketPair(currency, 'USD'), price),
[currency, price]
);

return useCallback(
(value: Money) => baseCurrencyAmountInQuote(value, alexCurrencyMarketData),
[alexCurrencyMarketData]
);
}
23 changes: 23 additions & 0 deletions src/app/common/hooks/use-media-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect, useState } from 'react';

import { BreakpointToken, token } from 'leather-styles/tokens';

function useMediaQuery(query: string) {
const [matches, setMatches] = useState(false);

useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
window.addEventListener('resize', listener);
return () => window.removeEventListener('resize', listener);
}, [matches, query]);

return matches;
}

export function useViewportMinWidth(viewport: BreakpointToken) {
return useMediaQuery(`(min-width: ${token(`breakpoints.${viewport}`)})`);
}
5 changes: 2 additions & 3 deletions src/app/common/money/calculate-money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { isNumber } from '@shared/utils';

import { initBigNumber, sumNumbers } from '../math/helpers';
import { formatMoney } from './format-money';
import { isMoney } from './is-money';
import { isMoney } from './money.utils';

export function baseCurrencyAmountInQuote(quantity: Money, { pair, price }: MarketData) {
if (quantity.symbol !== pair.base)
if (quantity.symbol.toLowerCase() !== pair.base.toLowerCase())
throw new Error(
`Cannot calculate value of ${formatMoney(quantity)} with market pair of ${formatMarketPair(
pair
Expand Down Expand Up @@ -39,7 +39,6 @@ export function convertToMoneyTypeWithDefaultOfZero(
return createMoney(initBigNumber(num ?? 0), symbol.toUpperCase(), decimals);
}

// ts-unused-exports:disable-next-line
export function convertAmountToBaseUnit(num: Money | BigNumber, decimals?: number) {
if (isMoney(num)) return num.amount.shiftedBy(-num.decimals);
if (!isNumber(decimals)) throw new Error('Must define decimal of given currency');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import BigNumber from 'bignumber.js';

import { Money } from '@shared/models/money.model';
import { isObject } from '@shared/utils';

export function isMoney(val: unknown): val is Money {
if (!isObject(val)) return false;
return 'amount' in val && 'symbol' in val && 'decimals' in val;
}

export function isMoneyGreaterThanZero(money: Money) {
if (!BigNumber.isBigNumber(money.amount)) return;
return !(money.amount.isNaN() || money.amount.isZero());
}
23 changes: 0 additions & 23 deletions src/app/common/utils/sort-assets-by-symbol.ts

This file was deleted.

Loading

0 comments on commit 36c0ae2

Please sign in to comment.