Skip to content

Commit

Permalink
Merge pull request #7 from darwinia-network/optimize-cache
Browse files Browse the repository at this point in the history
  • Loading branch information
hujw77 authored Sep 26, 2024
2 parents bf369f5 + d9efc64 commit 8c773a8
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 29 deletions.
16 changes: 16 additions & 0 deletions src/hooks/useAssetsToVotes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useReadContract } from 'wagmi';
import { abi, address } from '@/config/abi/hub';
import { readContract } from '@wagmi/core';
import { config } from '@/config/wagmi';

export type Operation = 'add' | 'subtract';

Expand All @@ -24,6 +26,20 @@ function useAssetsToVotes({ commission, totalAmount, inputAmount, operation }: A
return result;
}

export async function assetsToVotes(
commission: bigint,
totalAmount: bigint,
inputAmount: bigint,
operation: Operation
): Promise<bigint> {
return await readContract(config, {
abi,
address,
functionName: 'assetsToVotes',
args: [commission, calculateAssets(totalAmount, inputAmount, operation)]
});
}

function calculateAssets(totalAmount: bigint, inputAmount: bigint, operation: Operation): bigint {
if (operation === 'add') {
return (totalAmount || 0n) + (inputAmount || 0n);
Expand Down
28 changes: 27 additions & 1 deletion src/hooks/useService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,30 @@ export function useCollatorByAddress({ address, enabled = true }: CollatorByAddr
});
}

export const fetchCollatorByAddress = async ({
address,
currentChainId
}: {
address: `0x${string}`;
currentChainId: number;
}) => {
const params: CollatorSetQueryParams = {
where: {
...(address ? { address: toLowerCase(address) } : {}),
inset: 1
},
orderBy: 'key',
orderDirection: 'desc',
skip: 0,
first: 1
};
const result = await fetchCollatorSet(params, currentChainId!);
if (result === null) {
throw new Error('Failed to fetch collator set');
}
return result;
};

type CollatorSetByAccountsParams = {
accounts: `0x${string}`[];
enabled?: boolean;
Expand Down Expand Up @@ -215,7 +239,9 @@ export function useStakingAccount({ enabled = true }: StakingAccountParams) {
const params: StakingAccountQueryParams = {
where: {
account: toLowerCase(address)
}
},
orderBy: 'latestChangeTimestamp',
orderDirection: 'desc'
};
const queryKey = ['stakingAccounts', params];
const result = useQuery({
Expand Down
52 changes: 28 additions & 24 deletions src/hooks/useStakeOldAndNewPrev.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { DEFAULT_PREV } from '@/utils/getPrevNew';
import useAssetsToVotes, { Operation } from './useAssetsToVotes';
import { fetchCollatorSetNewPrev, fetchCollatorSetPrev } from './useService';
import { assetsToVotes, Operation } from './useAssetsToVotes';
import {
fetchCollatorByAddress,
fetchCollatorSetNewPrev,
fetchCollatorSetPrev
} from './useService';
import { genKey } from '@/utils';
import { CollatorSet } from '@/service/type';
import { useCallback, useState } from 'react';
Expand All @@ -22,41 +26,41 @@ export function useStakeOldAndNewPrev({
operation = 'add'
}: UseOldAndNewPrevProps) {
const { currentChainId } = useWalletStatus();
const commission = BigInt(collator?.commission || 0);
const totalAmount = BigInt(collator?.assets || 0);
const collatorAddress = collator?.address || '';
const oldKey = collator?.key || '';

const [isLoading, setIsLoading] = useState(false);
const { refetch: refetchAssetsToVotes, data } = useAssetsToVotes({
commission,
totalAmount,
inputAmount,
operation
});

console.log('data', data);

const getPrevAndNewPrev: () => Promise<PrevResult> = useCallback(async () => {
setIsLoading(true);

if (!oldKey || !collatorAddress) {
setIsLoading(true);
if (!collatorAddress) {
return {
oldPrev: DEFAULT_PREV,
newPrev: DEFAULT_PREV
};
}
setIsLoading(true);
const newCollator = await fetchCollatorByAddress({
address: collatorAddress as `0x${string}`,
currentChainId: currentChainId!
});
if (!newCollator) {
setIsLoading(false);
return { oldPrev: DEFAULT_PREV, newPrev: DEFAULT_PREV };
}

const commission = BigInt(newCollator?.[0]?.commission || 0);
const totalAmount = BigInt(newCollator?.[0]?.assets || 0);
const oldKey = newCollator?.[0]?.key || '';

const [assetsToVotesResult, collatorSetPrev] = await Promise.all([
refetchAssetsToVotes(),
fetchCollatorSetPrev({ key: oldKey, collatorAddress, currentChainId: currentChainId! })
assetsToVotes(commission, totalAmount, inputAmount, operation),
fetchCollatorSetPrev({
key: oldKey,
collatorAddress,
currentChainId: currentChainId!
})
]);
console.log('assetsToVotesResult?.data ', assetsToVotesResult?.data);

const newKey = genKey({ address: collatorAddress, votes: assetsToVotesResult?.data ?? 0n });

console.log('newKey', newKey);
const newKey = genKey({ address: collatorAddress, votes: assetsToVotesResult ?? 0n });

if (!newKey) {
setIsLoading(false);
Expand All @@ -78,7 +82,7 @@ export function useStakeOldAndNewPrev({
? (collatorSetNewPrev?.[0]?.address as `0x${string}`)
: DEFAULT_PREV
};
}, [refetchAssetsToVotes, collatorAddress, oldKey, currentChainId]);
}, [collatorAddress, currentChainId, inputAmount, operation]);

return {
getPrevAndNewPrev,
Expand Down
3 changes: 0 additions & 3 deletions src/service/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ export async function fetchStakingAccount(
params: StakingAccountQueryParams,
chainId: ChainId
): Promise<StakingAccount[] | null> {
console.log('fetchStakingAccount', chainId);

const client = getClient(chainId);
console.log('client', client);
try {
const response = await client.request<{ stakingAccounts: StakingAccount[] }>(
GET_STAKING_ACCOUNT,
Expand Down
8 changes: 7 additions & 1 deletion src/service/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,13 @@ export interface CollatorSetQueryParams {

export type CollatorSetQueryFunction = (params: CollatorSetQueryParams) => Promise<CollatorSet[]>;

export type StakingAccountOrderByField = 'id' | 'pool' | 'collator' | 'account' | 'assets';
export type StakingAccountOrderByField =
| 'id'
| 'pool'
| 'collator'
| 'account'
| 'assets'
| 'latestChangeTimestamp';
export interface StakingAccount {
account: `0x${string}`;
assets: string;
Expand Down

0 comments on commit 8c773a8

Please sign in to comment.