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

frontend: update 'My portfolio' with lightning account #2703

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
110 changes: 94 additions & 16 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,79 @@ 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 hasCard = useSDCard(devices);

const fetchLightningBalance = useCallback(async () => {
Beerosagos marked this conversation as resolved.
Show resolved Hide resolved
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);
if (mounted.current) {
setLightningKeystoreName(response.success ? response.keystoreName : '');
}
} catch (err) {
console.error(err);
}
}, [lightningConfig.accounts, mounted]);

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;
})
)
);
const allKeystores = (lightningKeystoreName && hasLightningFromOtherKeystore)
? [...accountsByKeystore, { keystore: { name: lightningKeystoreName } }]
: accountsByKeystore;

const getAccountSummary = useCallback(async () => {
// replace previous timer if present
if (summaryReqTimerID.current) {
Expand Down Expand Up @@ -137,18 +209,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 @@ -221,23 +281,41 @@ export const AccountsSummary = ({
accounts.length && accounts.length <= Object.keys(balances || {}).length ? (
<AddBuyReceiveOnEmptyBalances accounts={accounts} balances={balances} />
) : undefined
} />
{accountsByKeystore.length > 1 && (
}
hideChartDetails={hasLightningFromOtherKeystore && allKeystores.length == 1}
/>
{allKeystores.length > 1 && (
<CoinBalance
summaryData={summaryData}
coinsBalances={coinsTotalBalance}
/>
)}
{hasLightningFromOtherKeystore && (
<LightningBalance
lightningBalance={lightningBalance}
lightningAccountKeystoreName={lightningKeystoreName}
keystoreDisambiguatorName={
isAmbiguousName(lightningKeystoreName, allKeystores)
? lightningConfig.accounts[0].rootFingerprint
: undefined
}
/>
)}
thisconnect marked this conversation as resolved.
Show resolved Hide resolved
{accountsByKeystore &&
(accountsByKeystore.map(({ keystore, accounts }) =>
<SummaryBalance
key={keystore.rootFingerprint}
keystoreDisambiguatorName={isAmbiguousName(keystore.name, accountsByKeystore) ? keystore.rootFingerprint : undefined}
keystoreDisambiguatorName={
isAmbiguousName(keystore.name, allKeystores)
? 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
95 changes: 52 additions & 43 deletions frontends/web/src/routes/account/summary/chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ 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 = {
data?: TSummary;
noDataPlaceholder?: JSX.Element;
hideAmounts?: boolean;
hideChartDetails: boolean;
};

const defaultData: Readonly<TSummary> = {
Expand Down Expand Up @@ -88,7 +90,8 @@ const renderDate = (
export const Chart = ({
data = defaultData,
noDataPlaceholder,
hideAmounts = false
hideAmounts = false,
hideChartDetails = false
}: TProps) => {
const height: number = 300;
const mobileHeight: number = 150;
Expand Down Expand Up @@ -489,7 +492,7 @@ export const Chart = ({
const disableFilters = !hasData || chartDataMissing;
const disableWeeklyFilters = !hasHourlyData || chartDataMissing;
const showMobileTotalValue = toolTipVisible && !!toolTipValue && isMobile;
const chartFiltersProps = {
const chartFiltersProps: TChartFiltersProps = {
display: chartDisplay,
disableFilters,
disableWeeklyFilters,
Expand All @@ -516,50 +519,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>
}
{!hideChartDetails && (
<>
{!showMobileTotalValue ? (
<PercentageDiff
hasDifference={!!hasDifference}
difference={difference}
title={diffSince}
/>
) :
<span className={styles.diffValue}>
{renderDate(toolTipTime * 1000, i18n.language, source)}
</span>
}
</>
)}
</div>
{!isMobile && <Filters {...chartFiltersProps} />}
{!isMobile && !hideChartDetails && <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)}
{hideChartDetails || (
<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>
)}
{isMobile && !hideChartDetails && <Filters {...chartFiltersProps} />}
</section>
);
};
Loading
Loading