Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release/rate limiter #5295

Merged
merged 12 commits into from
Apr 24, 2024
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
4 changes: 2 additions & 2 deletions src/app/common/hooks/balance/btc/use-btc-balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ 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,
Expand Down
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
6 changes: 3 additions & 3 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,8 +16,8 @@ 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);
Expand Down
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]
);
}
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.

Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '@app/common/transactions/bitcoin/coinselect/local-coin-selection';
import { useCurrentNativeSegwitUtxos } from '@app/query/bitcoin/address/utxos-by-address.hooks';
import { useCurrentNativeSegwitAddressBalance } 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 const MAX_FEE_RATE_MULTIPLIER = 50;

Expand All @@ -25,7 +25,7 @@ interface UseBitcoinCustomFeeArgs {
export function useBitcoinCustomFee({ amount, isSendingMax, recipient }: UseBitcoinCustomFeeArgs) {
const { balance } = useCurrentNativeSegwitAddressBalance();
const { data: utxos = [] } = useCurrentNativeSegwitUtxos();
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');

return useCallback(
(feeRate: number) => {
Expand Down Expand Up @@ -67,7 +67,7 @@ export function useBitcoinCustomFeeMultipleRecipients({
}: UseBitcoinCustomFeeArgsMultipleRecipients) {
const { balance } = useCurrentNativeSegwitAddressBalance();
const { data: utxos = [] } = useCurrentNativeSegwitUtxos();
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');

return useCallback(
(feeRate: number) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '@app/common/transactions/bitcoin/coinselect/local-coin-selection';
import { UtxoResponseItem } from '@app/query/bitcoin/bitcoin-client';
import { useAverageBitcoinFeeRates } from '@app/query/bitcoin/fees/fee-estimates.hooks';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';

import { FeesListItem } from './bitcoin-fees-list';

Expand Down Expand Up @@ -41,7 +41,7 @@ export function useBitcoinFeesListMultipleRecipients({
recipients,
utxos,
}: UseBitcoinFeesListArgs) {
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');
const { data: feeRates, isLoading } = useAverageBitcoinFeeRates();

const feesList: FeesListItem[] = useMemo(() => {
Expand Down
4 changes: 2 additions & 2 deletions src/app/components/bitcoin-fees-list/use-bitcoin-fees-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import { useCurrentNativeSegwitAddressBalance } from '@app/query/bitcoin/balance/btc-native-segwit-balance.hooks';
import { UtxoResponseItem } from '@app/query/bitcoin/bitcoin-client';
import { useAverageBitcoinFeeRates } from '@app/query/bitcoin/fees/fee-estimates.hooks';
import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { useCryptoCurrencyMarketDataMeanAverage } from '@app/query/common/market-data/market-data.hooks';

import { FeesListItem } from './bitcoin-fees-list';

Expand Down Expand Up @@ -44,7 +44,7 @@ export function useBitcoinFeesList({
utxos,
}: UseBitcoinFeesListArgs) {
const { balance } = useCurrentNativeSegwitAddressBalance();
const btcMarketData = useCryptoCurrencyMarketData('BTC');
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');
const { data: feeRates, isLoading } = useAverageBitcoinFeeRates();

const feesList: FeesListItem[] = useMemo(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import BigNumber from 'bignumber.js';
import { styled } from 'leather-styles/jsx';

import { createMoney } from '@shared/models/money.model';

import { convertAssetBalanceToFiat } from '@app/common/asset-utils';
import { formatBalance } from '@app/common/format-balance';
import { convertAmountToBaseUnit } from '@app/common/money/calculate-money';
import { Brc20Token } from '@app/query/bitcoin/bitcoin-client';
import { Brc20AvatarIcon } from '@app/ui/components/avatar/brc20-avatar-icon';
import { ItemLayout } from '@app/ui/components/item-layout/item-layout';
Expand All @@ -14,8 +15,11 @@ interface Brc20TokenAssetItemLayoutProps {
onClick?(): void;
}
export function Brc20TokenAssetItemLayout({ onClick, token }: Brc20TokenAssetItemLayoutProps) {
const balance = createMoney(Number(token.overall_balance), token.ticker, 0).amount.toString();
const formattedBalance = formatBalance(balance);
const balanceAsString = token.balance?.amount.toString();
const formattedBalance = formatBalance(
convertAmountToBaseUnit(token.balance ?? new BigNumber(0)).toString()
);
const balanceAsFiat = convertAssetBalanceToFiat(token);

return (
<Pressable onClick={onClick} my="space.02">
Expand All @@ -26,14 +30,15 @@ export function Brc20TokenAssetItemLayout({ onClick, token }: Brc20TokenAssetIte
titleRight={
<BasicTooltip
asChild
label={formattedBalance.isAbbreviated ? balance : undefined}
label={formattedBalance?.isAbbreviated ? balanceAsString : undefined}
side="left"
>
<styled.span data-testid={token.ticker} textStyle="label.02">
{formattedBalance.value}
</styled.span>
</BasicTooltip>
}
captionRight={balanceAsFiat}
/>
</Pressable>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export function Brc20TokenAssetList({ brc20Tokens, variant }: Brc20TokenAssetLis
variant === 'send' && btcCryptoCurrencyAssetBalance.balance.amount.isGreaterThan(0);

function navigateToBrc20SendForm(token: Brc20Token) {
const { ticker, available_balance, decimals, holderAddress } = token;
const { ticker, balance, holderAddress, marketData } = token;
navigate(RouteUrls.SendBrc20SendForm.replace(':ticker', ticker), {
state: { balance: available_balance, ticker, decimals, holderAddress },
state: { balance, ticker, holderAddress, marketData },
});
}

Expand Down
Loading
Loading