Skip to content

Commit

Permalink
refactor: replace the staking homepage and currency API. (#6289)
Browse files Browse the repository at this point in the history
  • Loading branch information
huhuanming authored Dec 3, 2024
1 parent 66e6920 commit b7e4182
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,10 @@ export class V4MigrationForSettings extends V4MigrationManagerBase {
if (v4Settings?.selectedFiatMoneySymbol) {
await this.v4dbHubs.logger.runAsyncWithCatch(
async () => {
const currencyList =
await this.backgroundApi.serviceSetting.getCurrencyList();
const existingCurrencyItem = currencyList.find(
(i) => i.id === v4Settings.selectedFiatMoneySymbol,
);
const currencyMap =
await this.backgroundApi.serviceSetting.getCurrencyMap();
const existingCurrencyItem =
currencyMap[v4Settings.selectedFiatMoneySymbol];
if (existingCurrencyItem) {
await this.backgroundApi.serviceSetting.setCurrency({
id: existingCurrencyItem.id,
Expand Down
4 changes: 2 additions & 2 deletions packages/kit-bg/src/services/ServiceAccountProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,12 +441,12 @@ class ServiceAccountProfile extends ServiceBase {
}) {
const { currency, value, updateAll } = params;

const currencyItems = (await currencyPersistAtom.get()).currencyItems;
const currencyMap = (await currencyPersistAtom.get()).currencyMap;

let usdValue: Record<string, string> = value;

if (currency !== 'usd') {
const currencyInfo = currencyItems.find((item) => item.id === currency);
const currencyInfo = currencyMap[currency];

if (!currencyInfo) {
throw new Error('Currency not found');
Expand Down
16 changes: 8 additions & 8 deletions packages/kit-bg/src/services/ServiceSetting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,17 +158,17 @@ class ServiceSetting extends ServiceBase {
}));
}

_getCurrencyList = memoizee(
_getCurrencyMap = memoizee(
async () => {
const client = await this.getClient(EServiceEndpointEnum.Utility);
const res = await client.get<{ data: ICurrencyItem[] }>(
'/utility/v1/currency/exchange-rates',
const res = await client.get<{ data: Record<string, ICurrencyItem> }>(
'/utility/v1/currency/exchange-rates/map',
);
return res.data.data;
},
{
promise: true,
maxAge: timerUtils.getTimeDurationMs({ minute: 5 }),
maxAge: timerUtils.getTimeDurationMs({ minute: 10 }),
},
);

Expand All @@ -180,15 +180,15 @@ class ServiceSetting extends ServiceBase {
}

@backgroundMethod()
public async getCurrencyList(): Promise<ICurrencyItem[]> {
return this._getCurrencyList();
public async getCurrencyMap() {
return this._getCurrencyMap();
}

@backgroundMethod()
public async fetchCurrencyList() {
const currencyItems = await this._getCurrencyList();
const currencyMap = await this._getCurrencyMap();
await currencyPersistAtom.set({
currencyItems,
currencyMap,
});
}

Expand Down
77 changes: 68 additions & 9 deletions packages/kit-bg/src/services/ServiceStaking.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import BigNumber from 'bignumber.js';

import { isTaprootAddress } from '@onekeyhq/core/src/chains/btc/sdkBtc';
import {
backgroundClass,
Expand Down Expand Up @@ -27,6 +29,7 @@ import type {
IClaimRecordParams,
IClaimableListResponse,
IEarnAccountResponse,
IEarnAccountToken,
IEarnAccountTokenResponse,
IEarnBabylonTrackingItem,
IEarnEstimateAction,
Expand Down Expand Up @@ -491,28 +494,27 @@ class ServiceStaking extends ServiceBase {
}[],
) {
const client = await this.getClient(EServiceEndpointEnum.Earn);
const response = await client.post<{
data: IEarnAccountResponse;
}>(`/earn/v1/account/list`, { accounts: params });
const resp = response.data.data;
const result: IEarnAccountTokenResponse = {
totalFiatValue: resp.totalFiatValue,
earnings24h: resp.earnings24h,
accounts: [],
};
const tokensResponse = await client.post<{
data: { tokens: IEarnAccountToken[] };
}>(`/earn/v1/recommend`, { accounts: params });

for (const account of params) {
result.accounts.push({
...account,
tokens:
resp.tokens?.filter((i) => i.networkId === account.networkId) || [],
tokensResponse.data.data.tokens?.filter(
(i) => i.networkId === account.networkId,
) || [],
});
}
return result;
}

@backgroundMethod()
async fetchAllNetworkAssets({
async getEarnAvailableAccountsParams({
accountId,
networkId,
assets,
Expand Down Expand Up @@ -550,7 +552,64 @@ class ServiceStaking extends ServiceBase {
]),
).values(),
);
return this.getAccountAsset(uniqueAccountParams);
return uniqueAccountParams;
}

@backgroundMethod()
async fetchAccountOverview(params: {
accountId: string;
networkId: string;
assets: IAvailableAsset[];
}) {
const accounts = await this.getEarnAvailableAccountsParams(params);
const client = await this.getClient(EServiceEndpointEnum.Earn);
const overviewData = await Promise.all(
accounts.map((account) =>
client.get<{
data: IEarnAccountResponse;
}>(`/earn/v1/overview`, { params: account }),
),
);

const { totalFiatValue, earnings24h } = overviewData.reduce(
(prev, item) => {
prev.totalFiatValue = prev.totalFiatValue.plus(
BigNumber(item.data.data.totalFiatValue || 0),
);
prev.earnings24h = prev.earnings24h.plus(
BigNumber(item.data.data.earnings24h || 0),
);
return prev;
},
{
totalFiatValue: BigNumber(0),
earnings24h: BigNumber(0),
},
);
// const resp = response.data.data;

return {
totalFiatValue: totalFiatValue.toFixed(),
earnings24h: earnings24h.toFixed(),
};
}

@backgroundMethod()
async fetchAllNetworkAssets({
accountId,
networkId,
assets,
}: {
accountId: string;
networkId: string;
assets: IAvailableAsset[];
}) {
const accounts = await this.getEarnAvailableAccountsParams({
accountId,
networkId,
assets,
});
return this.getAccountAsset(accounts);
}

@backgroundMethod()
Expand Down
4 changes: 2 additions & 2 deletions packages/kit-bg/src/states/jotai/atoms/currency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { EAtomNames } from '../atomNames';
import { globalAtom } from '../utils';

export type ICurrencyPersistAtom = {
currencyItems: ICurrencyItem[];
currencyMap: Record<string, ICurrencyItem>;
};
export const { target: currencyPersistAtom, use: useCurrencyPersistAtom } =
globalAtom<ICurrencyPersistAtom>({
persist: true,
name: EAtomNames.currencyPersistAtom,
initialValue: {
currencyItems: [],
currencyMap: {},
},
});
14 changes: 7 additions & 7 deletions packages/kit/src/components/Currency/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ function BasicCurrency({
children,
...props
}: ICurrencyProps) {
const [{ currencyItems }] = useCurrencyPersistAtom();
const [{ currencyMap }] = useCurrencyPersistAtom();
const [{ currencyInfo }] = useSettingsPersistAtom();
const sourceCurrencyInfo = useMemo(
() => currencyItems.find((i) => i.id === sourceCurrency),
[currencyItems, sourceCurrency],
() => currencyMap[sourceCurrency],
[currencyMap, sourceCurrency],
);
const targetCurrencyInfo = useMemo(
() => currencyMap[targetCurrency ?? currencyInfo.id],
[currencyInfo.id, currencyMap, targetCurrency],
);
const targetCurrencyInfo = useMemo(() => {
const currencyId = targetCurrency ?? currencyInfo.id;
return currencyItems.find((i) => i.id === currencyId);
}, [currencyInfo.id, currencyItems, targetCurrency]);

const value = useMemo(
() =>
Expand Down
27 changes: 25 additions & 2 deletions packages/kit/src/views/Earn/EarnHome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -634,25 +634,48 @@ function BasicEarnHome() {
.then(actions.current.updateAvailableAssets);
});
}
const earnAccountData = actions.current.getEarnAccount(totalFiatMapKey);

const fetchAndUpdateAction = async () => {
const earnAccount =
await backgroundApiProxy.serviceStaking.fetchAllNetworkAssets({
assets,
accountId: account?.id ?? '',
networkId: network?.id ?? '',
});
const earnAccountData = actions.current.getEarnAccount(totalFiatMapKey);
actions.current.updateEarnAccounts({
key: totalFiatMapKey,
earnAccount,
earnAccount: {
...earnAccountData,
...earnAccount,
},
});
};
const fetchAndUpdateOverview = async () => {
const overviewData =
await backgroundApiProxy.serviceStaking.fetchAccountOverview({
assets,
accountId: account?.id ?? '',
networkId: network?.id ?? '',
});
const earnAccountData = actions.current.getEarnAccount(totalFiatMapKey);
actions.current.updateEarnAccounts({
key: totalFiatMapKey,
earnAccount: {
accounts: earnAccountData?.accounts || [],
...overviewData,
},
});
};
const earnAccountData = actions.current.getEarnAccount(totalFiatMapKey);
if (earnAccountData) {
setTimeout(() => {
void fetchAndUpdateOverview();
void fetchAndUpdateAction();
});
} else {
await fetchAndUpdateAction();
void fetchAndUpdateOverview();
}
return { loaded: true };
},
Expand Down
5 changes: 3 additions & 2 deletions packages/kit/src/views/Setting/pages/Currency/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ export default function SettingCurrencyModal() {
currencyRef.current as ICurrencyItem,
);
const intl = useIntl();
const [{ currencyItems }] = useCurrencyPersistAtom();
const [{ currencyMap }] = useCurrencyPersistAtom();
const sections = useMemo(() => {
const currencyItems = Object.values(currencyMap);
if (currencyItems.length === 0) {
return [];
}
Expand Down Expand Up @@ -102,7 +103,7 @@ export default function SettingCurrencyModal() {
data: section.fiat,
},
].filter((item) => item.data.length > 0);
}, [currencyItems, text, intl]);
}, [currencyMap, intl, text]);

const handlePress = useCallback((item: ICurrencyItem) => {
setCurrency(item);
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/types/staking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,8 @@ export type IEarnAccount = {
};

export type IEarnAccountTokenResponse = {
totalFiatValue: string;
earnings24h: string;
totalFiatValue?: string;
earnings24h?: string;
accounts: IEarnAccount[];
};

Expand Down

0 comments on commit b7e4182

Please sign in to comment.