Skip to content

Commit

Permalink
feat: added query for bitcoin contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
Polybius93 committed Dec 14, 2023
1 parent 4b97c5c commit 408ce03
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 32 deletions.
11 changes: 9 additions & 2 deletions src/app/common/hooks/use-bitcoin-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { useCurrentNetwork } from '@app/store/networks/networks.selectors';
import { initialSearchParams } from '../initial-search-params';
import { i18nFormatCurrency } from '../money/format-money';
import { satToBtc } from '../money/unit-conversion';
import { useConvertCryptoCurrencyToFiatAmount } from './use-convert-to-fiat-amount';
import { useDefaultRequestParams } from './use-default-request-search-params';

export interface SimplifiedBitcoinContract {
Expand Down Expand Up @@ -60,6 +61,7 @@ export function useBitcoinContracts() {
const defaultParams = useDefaultRequestParams();
const bitcoinMarketData = useCryptoCurrencyMarketData('BTC');
const calculateFiatValue = useCalculateBitcoinFiatValue();

const bitcoinAccountDetails = useCurrentAccountNativeSegwitIndexZeroSigner();
const currentIndex = useCurrentAccountIndex();
const nativeSegwitPrivateKeychain = useNativeSegwitAccountBuilder()?.(currentIndex);
Expand Down Expand Up @@ -209,13 +211,15 @@ export function useBitcoinContracts() {
async function getAllSignedBitcoinContracts(): Promise<BitcoinContractListItem[] | undefined> {
const bitcoinContractInterface = await getBitcoinContractInterface();

console.log('bitcoinContractInterface', bitcoinContractInterface?.get_options())
if (!bitcoinContractInterface) return;

const bitcoinContracts = await bitcoinContractInterface.get_contracts();
const signedBitcoinContracts = bitcoinContracts.filter(
(bitcoinContract: BitcoinContractListItem) => bitcoinContract.state === 'Signed'
);

console.log('signedBitcoinContracts', signedBitcoinContracts)
return signedBitcoinContracts;
}

Expand All @@ -236,17 +240,20 @@ export function useBitcoinContracts() {
};
}

async function sumBitcoinContractCollateralAmounts(): Promise<Money | undefined> {
async function sumBitcoinContractCollateralAmounts(): Promise<Money> {
console.log('sumBitcoinContractCollateralAmounts')
let bitcoinContractsCollateralSum = 0;
const bitcoinContracts = await getAllSignedBitcoinContracts();
if (!bitcoinContracts) return;
if (!bitcoinContracts) return createMoneyFromDecimal(0, 'BTC');

bitcoinContracts.forEach((bitcoinContract: BitcoinContractListItem) => {
bitcoinContractsCollateralSum += parseInt(bitcoinContract.acceptorCollateral);
});
const bitcoinContractCollateralSumMoney = createMoneyFromDecimal(
satToBtc(bitcoinContractsCollateralSum),
'BTC'
);

return bitcoinContractCollateralSumMoney;
}

Expand Down
2 changes: 2 additions & 0 deletions src/app/common/money/calculate-money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { formatMoney } from './format-money';
import { isMoney } from './is-money';

export function baseCurrencyAmountInQuote(quantity: Money, { pair, price }: MarketData) {
console.log(quantity, pair, price)
if (quantity.symbol !== pair.base)
throw new Error(
`Cannot calculate value of ${formatMoney(quantity)} with market pair of ${formatMarketPair(
Expand Down Expand Up @@ -41,6 +42,7 @@ export function convertToMoneyTypeWithDefaultOfZero(

// ts-unused-exports:disable-next-line
export function convertAmountToBaseUnit(num: Money | BigNumber, decimals?: number) {
console.log(num, decimals)
if (isMoney(num)) return num.amount.shiftedBy(-num.decimals);
if (!isNumber(decimals)) throw new Error('Must define decimal of given currency');
return num.shiftedBy(-decimals);
Expand Down
1 change: 1 addition & 0 deletions src/app/common/money/format-money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export function formatMoneyPadded({ amount, symbol, decimals }: Money) {
}

export function i18nFormatCurrency(quantity: Money, locale = 'en-US') {
console.log(quantity)
if (quantity.symbol !== 'USD') throw new Error('Cannot format non-USD amounts');
const currencyFormatter = new Intl.NumberFormat(locale, { style: 'currency', currency: 'USD' });

Expand Down
Original file line number Diff line number Diff line change
@@ -1,51 +1,32 @@
import { useState } from 'react';
import { useAsync } from 'react-async-hook';
import { useNavigate } from 'react-router-dom';

import { Money, createMoneyFromDecimal } from '@shared/models/money.model';
import { RouteUrls } from '@shared/route-urls';

import { useBitcoinContracts } from '@app/common/hooks/use-bitcoin-contracts';
import { i18nFormatCurrency } from '@app/common/money/format-money';
import { useCalculateBitcoinFiatValue } from '@app/query/common/market-data/market-data.hooks';
import { useBitcoinContractsBalanceQuery } from '@app/query/stacks/balance/bitcoin-contracts-balance.query';
import { BitcoinContractIcon } from '@app/ui/components/icons/bitcoin-contract-icon';

import { useCryptoCurrencyMarketData } from '@app/query/common/market-data/market-data.hooks';
import { createMoney } from '@shared/models/money.model';
import { BitcoinContractEntryPointLayout } from './bitcoin-contract-entry-point-layout';

interface BitcoinContractEntryPointProps {
btcAddress: string;
}
export function BitcoinContractEntryPoint({ btcAddress }: BitcoinContractEntryPointProps) {
export function BitcoinContractEntryPoint() {
const navigate = useNavigate();
const { sumBitcoinContractCollateralAmounts } = useBitcoinContracts();
const [isLoading, setIsLoading] = useState(true);
const calculateFiatValue = useCalculateBitcoinFiatValue();
const [bitcoinContractSum, setBitcoinContractSum] = useState<Money>(
createMoneyFromDecimal(0, 'BTC')
);

useAsync(async () => {
setIsLoading(true);
const currentBitcoinContractSum = await sumBitcoinContractCollateralAmounts();
if (!currentBitcoinContractSum) return;
setBitcoinContractSum(currentBitcoinContractSum);
setIsLoading(false);
}, [btcAddress]);

const { data: bitcoinContactsBalance, isLoading, refetch } = useBitcoinContractsBalanceQuery();


function onClick() {
navigate(RouteUrls.BitcoinContractList);
}

return (
!bitcoinContractSum.amount.isZero() && (
<BitcoinContractEntryPointLayout
isLoading={isLoading}
balance={bitcoinContractSum}
caption={bitcoinContractSum.symbol}
balance={bitcoinContactsBalance ? bitcoinContactsBalance : createMoney(0, 'BTC')}
caption={bitcoinContactsBalance ? bitcoinContactsBalance.symbol : 'BTC'}
icon={<BitcoinContractIcon />}
usdBalance={i18nFormatCurrency(calculateFiatValue(bitcoinContractSum))}
// usdBalance={btcUsdBalance}
onClick={onClick}
/>
)
);
}
3 changes: 2 additions & 1 deletion src/app/features/asset-list/asset-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { useCurrentAccountNativeSegwitAddressIndexZero } from '@app/store/accoun
import { useCurrentNetwork } from '@app/store/networks/networks.selectors';
import { BtcIcon } from '@app/ui/components/icons/btc-icon';

import { useBitcoinContractsBalance } from '@app/query/stacks/balance/bitcoin-contracts-balance.query';
import { Collectibles } from '../collectibles/collectibles';
import { PendingBrc20TransferList } from '../pending-brc-20-transfers/pending-brc-20-transfers';
import { BitcoinFungibleTokenAssetList } from './components/bitcoin-fungible-tokens-asset-list';
Expand Down Expand Up @@ -57,7 +58,7 @@ export function AssetsList() {
{/* Temporary duplication during Ledger Bitcoin feature dev */}
{['testnet', 'regtest'].includes(network.chain.bitcoin.bitcoinNetwork) &&
whenWallet({
software: <BitcoinContractEntryPoint btcAddress={btcAddress} />,
software: <BitcoinContractEntryPoint />,
ledger: null,
})}

Expand Down
26 changes: 26 additions & 0 deletions src/app/query/stacks/balance/bitcoin-contracts-balance.query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { UseQueryResult, useQuery } from '@tanstack/react-query';

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

import { useBitcoinContracts } from '@app/common/hooks/use-bitcoin-contracts';
import { useCurrentNetwork } from '@app/store/networks/networks.selectors';

const staleTime = 1 * 60 * 1000;

const balanceQueryOptions = {
staleTime,
keepPreviousData: false,
refetchOnMount: true,
} as const;

export function useBitcoinContractsBalanceQuery(): UseQueryResult<Money> {
const { sumBitcoinContractCollateralAmounts } = useBitcoinContracts();
const currentNetwork = useCurrentNetwork();

return useQuery({
queryKey: ['sum-bitcoin-contract-collateral-amounts', currentNetwork.id],
queryFn: sumBitcoinContractCollateralAmounts,
enabled: !!currentNetwork,
...balanceQueryOptions,
});
}

0 comments on commit 408ce03

Please sign in to comment.