Skip to content

Commit

Permalink
frontend: update 'My portfolio' with Lightning account
Browse files Browse the repository at this point in the history
This commit adds functionality to display Lightning account
in 'My portfolio' in cases where it is active but not associated
with a connected or remembered wallet, or when all mainnet
accounts in the connected wallet are disabled.

The total coins table is updated to include the Lightning account
Hide chart, percentage change and filters in my portfolio if
only lightning account is displayed.
  • Loading branch information
strmci committed Oct 4, 2024
1 parent fa48ff6 commit c23771e
Show file tree
Hide file tree
Showing 6 changed files with 252 additions and 79 deletions.
40 changes: 40 additions & 0 deletions backend/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ func NewHandlers(
getAPIRouterNoError(apiRouter)("/testing", handlers.getTesting).Methods("GET")
getAPIRouterNoError(apiRouter)("/account-add", handlers.postAddAccount).Methods("POST")
getAPIRouterNoError(apiRouter)("/keystores", handlers.getKeystores).Methods("GET")
getAPIRouterNoError(apiRouter)("/keystore-name", handlers.getKeystoreName).Methods("GET")
getAPIRouterNoError(apiRouter)("/accounts", handlers.getAccounts).Methods("GET")
getAPIRouter(apiRouter)("/accounts/balance", handlers.getAccountsBalance).Methods("GET")
getAPIRouter(apiRouter)("/accounts/coins-balance", handlers.getCoinsTotalBalance).Methods("GET")
Expand Down Expand Up @@ -603,6 +604,30 @@ func (handlers *Handlers) getKeystores(*http.Request) interface{} {
return keystores
}

func (handlers *Handlers) getKeystoreName(r *http.Request) interface{} {
type response struct {
Success bool `json:"success"`
KeystoreName string `json:"keystoreName,omitempty"`
}

rootFingerprint := r.URL.Query().Get("rootFingerprint")

hexFingerprint, err := hex.DecodeString(rootFingerprint)
if err != nil {
return response{Success: false}
}

keystore, err := handlers.backend.Config().AccountsConfig().LookupKeystore(jsonp.HexBytes(hexFingerprint))
if err != nil {
return response{Success: false}
}

return response{
Success: true,
KeystoreName: keystore.Name,
}
}

func (handlers *Handlers) getAccounts(*http.Request) interface{} {
persistedAccounts := handlers.backend.Config().AccountsConfig()

Expand Down Expand Up @@ -810,6 +835,21 @@ func (handlers *Handlers) getCoinsTotalBalance(_ *http.Request) (interface{}, er
}
}

if handlers.backend.Config().LightningConfig().LightningEnabled() {
lightningBalance, err := handlers.backend.Lightning().Balance()
if err != nil {
return nil, err
}
availableBalance := lightningBalance.Available().BigInt()

if bitcoinBalance, exists := totalCoinsBalances[coin.CodeBTC]; exists {
bitcoinBalance.Add(bitcoinBalance, availableBalance)
} else {
totalCoinsBalances[coin.CodeBTC] = availableBalance
sortedCoins = append([]coin.Code{coin.CodeBTC}, sortedCoins...)
}
}

for _, coinCode := range sortedCoins {
currentCoin, err := handlers.backend.Coin(coinCode)
if err != nil {
Expand Down
12 changes: 12 additions & 0 deletions frontends/web/src/api/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,18 @@ export const connectKeystore = (code: AccountCode): Promise<{ success: boolean;
return apiPost(`account/${code}/connect-keystore`);
};

export type TResponseKeystoreName = {
success: true,
keystoreName: string;
} | {
success: false;
}

export const getKeystoreName = (rootFingerprint: string): Promise<TResponseKeystoreName> => {
return apiGet(`keystore-name?rootFingerprint=${rootFingerprint}`);
};


export type TSignMessage = { success: false, aborted?: boolean; errorMessage?: string; } | { success: true; signature: string; }

export type TSignWalletConnectTx = {
Expand Down
116 changes: 101 additions & 15 deletions frontends/web/src/routes/account/summary/accountssummary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { Status } from '@/components/status/status';
import { GuideWrapper, GuidedContent, Header, Main } from '@/components/layout';
import { View } from '@/components/view/view';
import { Chart } from './chart';
import { SummaryBalance } from './summarybalance';
import { LightningBalance, SummaryBalance } from './summarybalance';
import { CoinBalance } from './coinbalance';
import { AddBuyReceiveOnEmptyBalances } from '@/routes/account/info/buyReceiveCTA';
import { Entry } from '@/components/guide/entry';
Expand All @@ -36,6 +36,8 @@ import { HideAmountsButton } from '@/components/hideamountsbutton/hideamountsbut
import { AppContext } from '@/contexts/AppContext';
import { getAccountsByKeystore, isAmbiguousName } from '@/routes/account/utils';
import { RatesContext } from '@/contexts/RatesContext';
import { useLightning } from '@/hooks/lightning';
import { getLightningBalance, subscribeNodeState } from '../../../api/lightning';
import { ContentWrapper } from '@/components/contentwrapper/contentwrapper';
import { GlobalBanners } from '@/components/globalbanners/globalbanners';

Expand Down Expand Up @@ -65,9 +67,88 @@ export const AccountsSummary = ({
const [accountsTotalBalance, setAccountsTotalBalance] = useState<accountApi.TAccountsTotalBalance>();
const [coinsTotalBalance, setCoinsTotalBalance] = useState<accountApi.TCoinsTotalBalance>();
const [balances, setBalances] = useState<Balances>();
const { lightningConfig } = useLightning();
const [lightningBalance, setLightningBalance] = useState<accountApi.IBalance>();
const [lightningKeystoreName, setLightningKeystoreName] = useState('');
const lightningKeystore = { keystore: { name: lightningKeystoreName } };

const hasCard = useSDCard(devices);

const fetchLightningBalance = useCallback(async () => {
try {
const balance = await getLightningBalance();
if (mounted.current) {
setLightningBalance(balance);
}
} catch (err) {
console.error(err);
}
}, [mounted]);

const fetchLightningKeystoreName = useCallback(async () => {
if (!lightningConfig.accounts[0]) {
setLightningKeystoreName('');
return;
}
try {
const response = await accountApi.getKeystoreName(lightningConfig.accounts[0].rootFingerprint);
setLightningKeystoreName(response.success ? response.keystoreName : '');
} catch (err) {
console.error(err);
}
}, [lightningConfig.accounts]);

const getCoinsTotalBalance = useCallback(async () => {
try {
const coinBalance = await accountApi.getCoinsTotalBalance();
if (!mounted.current) {
return;
}
setCoinsTotalBalance(coinBalance);
} catch (err) {
console.error(err);
}
}, [mounted]);

// if there is an active lightning account subscribe to any node state changes.
useEffect(() => {
const lightningAccounts = lightningConfig.accounts;
if (lightningAccounts.length) {
fetchLightningBalance();
fetchLightningKeystoreName();
const subscriptions = [
subscribeNodeState(async () => {
await fetchLightningBalance();
await getCoinsTotalBalance();
})
];
return () => unsubscribe(subscriptions);
}
}, [fetchLightningBalance, getCoinsTotalBalance, fetchLightningKeystoreName, lightningConfig]);

// lightning account exists but is not from any connected or remembered keystores
const hasLightningFromOtherKeystore = (
lightningConfig.accounts.length !== 0
&& (
!accountsByKeystore.some(({ keystore }) => {
return keystore.rootFingerprint === lightningConfig.accounts[0].rootFingerprint;
})
)
);
let keystores = accountsByKeystore.length;
let keystoreDisambiguatorName;
if (hasLightningFromOtherKeystore) {
keystores += 1;
keystoreDisambiguatorName = isAmbiguousName(
lightningKeystoreName,
lightningKeystoreName
? [...accountsByKeystore, lightningKeystore]
: accountsByKeystore
)
? lightningConfig.accounts[0].rootFingerprint
: undefined;
}

const getAccountSummary = useCallback(async () => {
// replace previous timer if present
if (summaryReqTimerID.current) {
Expand Down Expand Up @@ -137,18 +218,6 @@ export const AccountsSummary = ({
[mounted]
);

const getCoinsTotalBalance = useCallback(async () => {
try {
const coinBalance = await accountApi.getCoinsTotalBalance();
if (!mounted.current) {
return;
}
setCoinsTotalBalance(coinBalance);
} catch (err) {
console.error(err);
}
}, [mounted]);

const update = useCallback(
(code: accountApi.AccountCode) => {
if (mounted.current) {
Expand Down Expand Up @@ -222,22 +291,39 @@ export const AccountsSummary = ({
<AddBuyReceiveOnEmptyBalances accounts={accounts} balances={balances} />
) : undefined
} />
{accountsByKeystore.length > 1 && (
{keystores > 1 && (
<CoinBalance
summaryData={summaryData}
coinsBalances={coinsTotalBalance}
/>
)}
{hasLightningFromOtherKeystore && (
<LightningBalance
lightningBalance={lightningBalance}
lightningAccountKeystoreName={lightningKeystoreName}
keystoreDisambiguatorName={keystoreDisambiguatorName}
/>
)}
{accountsByKeystore &&
(accountsByKeystore.map(({ keystore, accounts }) =>
<SummaryBalance
key={keystore.rootFingerprint}
keystoreDisambiguatorName={isAmbiguousName(keystore.name, accountsByKeystore) ? keystore.rootFingerprint : undefined}
keystoreDisambiguatorName={
isAmbiguousName(
keystore.name,
(lightningKeystoreName && hasLightningFromOtherKeystore)
? [...accountsByKeystore, lightningKeystore ]
: accountsByKeystore
)
? keystore.rootFingerprint
: undefined
}
accountsKeystore={keystore}
accounts={accounts}
totalBalancePerCoin={balancePerCoin ? balancePerCoin[keystore.rootFingerprint] : undefined}
totalBalance={accountsTotalBalance ? accountsTotalBalance[keystore.rootFingerprint] : undefined}
balances={balances}
lightningBalance={ (lightningConfig.accounts.length && lightningConfig.accounts[0].rootFingerprint === keystore.rootFingerprint) ? lightningBalance : undefined}
/>
))}
</View>
Expand Down
1 change: 1 addition & 0 deletions frontends/web/src/routes/account/summary/chart.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
display: flex;
flex-direction: column;
align-items: flex-start;
flex-grow: 1;
}

.filters {
Expand Down
92 changes: 50 additions & 42 deletions frontends/web/src/routes/account/summary/chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { Filters } from './filters';
import { getDarkmode } from '@/components/darkmode/darkmode';
import { DefaultCurrencyRotator } from '@/components/rates/rates';
import { AppContext } from '@/contexts/AppContext';
import { TChartFiltersProps } from './types';
import styles from './chart.module.css';

type TProps = {
Expand Down Expand Up @@ -487,9 +488,10 @@ export const Chart = ({

const hasDifference = difference && Number.isFinite(difference);
const disableFilters = !hasData || chartDataMissing;
const showFiltersChartPercentageDiff: boolean = chartDataMissing || hasData || !!noDataPlaceholder;
const disableWeeklyFilters = !hasHourlyData || chartDataMissing;
const showMobileTotalValue = toolTipVisible && !!toolTipValue && isMobile;
const chartFiltersProps = {
const chartFiltersProps: TChartFiltersProps = {
display: chartDisplay,
disableFilters,
disableWeeklyFilters,
Expand All @@ -516,50 +518,56 @@ export const Chart = ({
{chartTotal !== null && <DefaultCurrencyRotator tableRow={false} />}
</span>
</div>
{!showMobileTotalValue ? (
<PercentageDiff
hasDifference={!!hasDifference}
difference={difference}
title={diffSince}
/>
) :
<span className={styles.diffValue}>
{renderDate(toolTipTime * 1000, i18n.language, source)}
</span>
}
{showFiltersChartPercentageDiff && (
<>
{!showMobileTotalValue ? (
<PercentageDiff
hasDifference={!!hasDifference}
difference={difference}
title={diffSince}
/>
) :
<span className={styles.diffValue}>
{renderDate(toolTipTime * 1000, i18n.language, source)}
</span>
}
</>
)}
</div>
{!isMobile && <Filters {...chartFiltersProps} />}
{!isMobile && showFiltersChartPercentageDiff && <Filters {...chartFiltersProps} />}
</header>
<div className={styles.chartCanvas} style={{ minHeight: chartHeight }}>
{chartDataMissing ? (
<div className={styles.chartUpdatingMessage} style={{ height: chartHeight }}>
{t('chart.dataMissing')}
</div>
) : hasData ? !chartIsUpToDate && (
<div className={styles.chartUpdatingMessage}>
{t('chart.dataOldTimestamp', { time: new Date(lastTimestamp).toLocaleString(i18n.language), })}
</div>
) : noDataPlaceholder}
<div ref={ref} className={styles.invisible}></div>
<span
ref={refToolTip}
className={styles.tooltip}
style={{ left: toolTipLeft, top: toolTipTop }}
hidden={!toolTipVisible || isMobile}>
{toolTipValue !== undefined ? (
<span>
<h2 className={styles.toolTipValue}>
<Amount amount={toolTipValue} unit={chartFiat} />
<span className={styles.toolTipUnit}>{chartFiat}</span>
</h2>
<span className={styles.toolTipTime}>
{renderDate(toolTipTime * 1000, i18n.language, source)}
{(showFiltersChartPercentageDiff) ? (
<div className={styles.chartCanvas} style={{ minHeight: chartHeight }}>
{chartDataMissing ? (
<div className={styles.chartUpdatingMessage} style={{ height: chartHeight }}>
{t('chart.dataMissing')}
</div>
) : hasData ? !chartIsUpToDate && (
<div className={styles.chartUpdatingMessage}>
{t('chart.dataOldTimestamp', { time: new Date(lastTimestamp).toLocaleString(i18n.language), })}
</div>
) : noDataPlaceholder}
<div ref={ref} className={styles.invisible}></div>
<span
ref={refToolTip}
className={styles.tooltip}
style={{ left: toolTipLeft, top: toolTipTop }}
hidden={!toolTipVisible || isMobile}>
{toolTipValue !== undefined ? (
<span>
<h2 className={styles.toolTipValue}>
<Amount amount={toolTipValue} unit={chartFiat} />
<span className={styles.toolTipUnit}>{chartFiat}</span>
</h2>
<span className={styles.toolTipTime}>
{renderDate(toolTipTime * 1000, i18n.language, source)}
</span>
</span>
</span>
) : null}
</span>
</div>
{isMobile && <Filters {...chartFiltersProps} />}
) : null}
</span>
</div>
) : null}
{isMobile && showFiltersChartPercentageDiff && <Filters {...chartFiltersProps} />}
</section>
);
};
Loading

0 comments on commit c23771e

Please sign in to comment.