Skip to content

Commit

Permalink
WIP: subtract fees from max client balance
Browse files Browse the repository at this point in the history
  • Loading branch information
ovitrif committed Feb 19, 2024
1 parent d08cc67 commit 96475f9
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 10 deletions.
20 changes: 17 additions & 3 deletions src/components/Percentage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ import { CoinsIcon, SavingsIcon } from '../styles/icons';

type PercentageProps = {
value: number;
isMax?: boolean;
type: 'spending' | 'savings';
style?: StyleProp<ViewStyle>;
};

const Percentage = ({ value, type, style }: PercentageProps): ReactElement => (
const Percentage = ({
value,
isMax = false,
type,
style,
}: PercentageProps): ReactElement => (
<View style={[styles.root, style]}>
{type === 'spending' ? (
<CoinsIcon color="purple" height={26} width={26} />
Expand All @@ -18,8 +24,16 @@ const Percentage = ({ value, type, style }: PercentageProps): ReactElement => (
)}

<Headline lineHeight="40px" style={styles.text}>
{value}
<Text01S>%</Text01S>
{isMax ? (
<>
Max
<Text01S />
</>
) : (
<>
{value} <Text01S>%</Text01S>
</>
)}
</Headline>
</View>
);
Expand Down
45 changes: 40 additions & 5 deletions src/screens/Lightning/QuickSetup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ import {
setupOnChainTransaction,
} from '../../store/actions/wallet';
import {
getMaxChannelClientBalance,
refreshBlocktankInfo,
startChannelPurchase,
} from '../../store/utils/blocktank';
import { showToast } from '../../utils/notifications';
import { convertToSats } from '../../utils/conversion';
import { getFiatDisplayValues } from '../../utils/displayValues';
import { LIGHTNING_DIFF } from '../../utils/wallet/constants';
import {
LIGHTNING_DIFF,
SPENDING_LIMIT_MAX,
} from '../../utils/wallet/constants';
import type { LightningScreenProps } from '../../navigation/types';
import {
selectedNetworkSelector,
Expand Down Expand Up @@ -76,7 +80,7 @@ const QuickSetup = ({
}, []),
);

const spendingAmount = useMemo((): number => {
let spendingAmount = useMemo((): number => {
return convertToSats(textFieldValue, conversionUnit);
}, [textFieldValue, conversionUnit]);

Expand All @@ -93,6 +97,10 @@ const QuickSetup = ({
return fiatWhole;
}, [lnSetup.btSpendingLimitBalanced]);

const isHighBalance = useMemo((): boolean => {
return spendingAmount > lnSetup.slider.maxValue * SPENDING_LIMIT_MAX;
}, [spendingAmount, lnSetup.slider.maxValue]);

const setDefaultClientBalance = useCallback(() => {
const value = lnSetup.defaultClientBalance;
const result = getNumberPadText(value, denomination, unit);
Expand Down Expand Up @@ -141,10 +149,33 @@ const QuickSetup = ({
Math.round(spendingAmount + spendingAmount * LIGHTNING_DIFF),
minUsableLspBalance,
);

// if the spendingAmount is set to max we calculate fees and subtract
// them from the final clientBalance passed to BT's createOrder api.
// TODO: should move this to an `useEffect`
let clientBalanceSat = spendingAmount;
const isMax = spendingAmount >= lnSetup.slider.maxValue;
if (isMax) {
const estimate = await getMaxChannelClientBalance({
lspBalance,
spendingAmount,
channelExpiryWeeks: DEFAULT_CHANNEL_DURATION,
lspNodeId: blocktankInfo.nodes[0].pubkey,
turboChannel:
spendingAmount <= blocktankInfo.options.max0ConfClientBalanceSat,
});
if (!estimate.isErr()) {
clientBalanceSat = estimate.value;
// TEMP hack, should be properly done
// eslint-disable-next-line react-hooks/exhaustive-deps
spendingAmount = clientBalanceSat;
}
}

const purchaseResponse = await startChannelPurchase({
selectedNetwork,
selectedWallet,
clientBalanceSat: spendingAmount!,
clientBalanceSat: clientBalanceSat!,
lspBalanceSat: lspBalance,
channelExpiry: DEFAULT_CHANNEL_DURATION,
lspNodeId: blocktankInfo.nodes[0].pubkey,
Expand Down Expand Up @@ -214,6 +245,7 @@ const QuickSetup = ({
<View style={styles.percentages}>
<Percentage
value={lnSetup.percentage.spendings}
isMax={isHighBalance}
type="spending"
/>
<Percentage value={lnSetup.percentage.savings} type="savings" />
Expand All @@ -234,13 +266,16 @@ const QuickSetup = ({
</AnimatedView>
)}

{spendingAmount >= lnSetup.spendableBalance && (
{isHighBalance && (
<AnimatedView
style={styles.note}
entering={FadeIn}
exiting={FadeOut}
testID="QuickSetupReserveNote">
<Text02S color="gray1">{t('note_reserve_limit')}</Text02S>
<Text02S color="gray1">
{'The fees to setup and connect you to Lightning will be subtracted from your spending balance. \n' +
'You will see the final amount before confirming.'}
</Text02S>
</AnimatedView>
)}

Expand Down
46 changes: 46 additions & 0 deletions src/store/utils/blocktank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import * as blocktank from '../../utils/blocktank';
import {
createOrder,
estimateOrderFee,
getBlocktankInfo,
getCJitEntry,
getMin0ConfTxFee,
Expand Down Expand Up @@ -214,6 +215,51 @@ export const refreshBlocktankInfo = async (): Promise<Result<string>> => {
return err('Unable to update Blocktank info.');
};

export const getMaxChannelClientBalance = async ({
lspBalance,
spendingAmount,
channelExpiryWeeks,
lspNodeId,
turboChannel,
}: {
lspBalance: number;
spendingAmount: number;
channelExpiryWeeks: number;
lspNodeId: string;
turboChannel: boolean;
}): Promise<Result<number>> => {
// 1. estimating bt order fee
const estimateRes = await estimateOrderFee({
lspBalanceSat: lspBalance,
channelExpiryWeeks: channelExpiryWeeks,
options: {
clientBalanceSat: spendingAmount,
couponCode: 'bitkit',
lspNodeId,
turboChannel,
},
});

if (estimateRes.isErr()) {
return estimateRes;
}

// 2. subtracting bt order fee from client balance
const channelOpenFeeEstimate = estimateRes.value;
let clientBalanceSat = spendingAmount - channelOpenFeeEstimate;

// 3. estimating tx fee
let { fast: satsPerByte } = getFeesStore().onchain;
let transactionFeeEstimate = getTotalFee({ satsPerByte });
console.log('transactionFeeEstimate:', transactionFeeEstimate);

// 4. subtracting tx fee from client balance
clientBalanceSat = clientBalanceSat - transactionFeeEstimate;
console.log('maxOrderClientBalance:', clientBalanceSat);

return ok(clientBalanceSat);
};

/**
* Attempts to start the purchase of a Blocktank channel.
*
Expand Down
5 changes: 3 additions & 2 deletions src/utils/wallet/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ export const CHUNK_LIMIT = 15;
//How much of the users funds we allow to be used for Lightning.
export const SPENDING_LIMIT_RATIO = 1;

export const SPENDING_LIMIT_MAX = 0.8;

export const LIGHTNING_DIFF = 0.01;

// TODO remote; temp to make it easier for testing 100% cap
export const LIGHTNING_DEFAULT_SLIDER = 1;
export const LIGHTNING_DEFAULT_SLIDER = 0.8;

export const TRANSACTION_DEFAULTS = {
recommendedBaseFee: 256, // Total recommended tx base fee in sats
Expand Down

0 comments on commit 96475f9

Please sign in to comment.