Skip to content

Commit

Permalink
clean up success callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
alecananian committed Jan 2, 2025
1 parent 82f0c82 commit 24ebd12
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 60 deletions.
3 changes: 3 additions & 0 deletions app/api/user.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ export const fetchUserIncentives = async (
const reward = (rewardPerLiquidityDelta * usersLiquidity) / UINT112_MAX;
return {
...userIncentive,
isActive:
Number(userIncentive.incentive.endTime) >
Math.floor(Date.now() / 1000),
incentive: {
...userIncentive.incentive,
rewardToken: rewardToken,
Expand Down
8 changes: 4 additions & 4 deletions app/hooks/useClaimRewards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ type Props = {
onSuccess?: () => void;
};

export const useClaimRewards = ({ enabled = true, onSuccess }: Props) => {
export const useClaimRewards = (props?: Props) => {
const { isConnected } = useAccount();
const stakingContractAddress = useContractAddress("stakingContract");
const claimAllRewards = useWriteStakingContractClaimAllRewards();
const claimAllRewardsReceipt = useWaitForTransactionReceipt({
hash: claimAllRewards.data,
});

const isEnabled = enabled && isConnected;
const isEnabled = isConnected && props?.enabled !== false;
const isSuccess = claimAllRewardsReceipt.isSuccess;

useToast({
Expand All @@ -33,9 +33,9 @@ export const useClaimRewards = ({ enabled = true, onSuccess }: Props) => {

useEffect(() => {
if (isSuccess) {
onSuccess?.();
props?.onSuccess?.();
}
}, [isSuccess, onSuccess]);
}, [isSuccess, props?.onSuccess]);

return {
claimRewards: (incentiveIds: bigint[]) => {
Expand Down
21 changes: 7 additions & 14 deletions app/hooks/useSubscribeToIncentives.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,29 @@
import { useEffect, useState } from "react";
import { useWaitForTransactionReceipt } from "wagmi";

import type { UserIncentive } from "~/api/user.server";
import { useEffect } from "react";
import { useAccount } from "~/contexts/account";
import { useWriteStakingContractSubscribeToIncentives } from "~/generated";
import { useContractAddress } from "./useContractAddress";
import { useToast } from "./useToast";

type Props = {
enabled?: boolean;
onSuccess?: (incentiveIds: bigint[]) => void;
onSuccess?: () => void;
};

export const useSubscribeToIncentives = ({
enabled = true,
onSuccess,
}: Props) => {
const [lastIncentiveIds, setLastIncentiveIds] = useState<bigint[]>([]);
export const useSubscribeToIncentives = (props?: Props) => {
const { isConnected } = useAccount();
const stakingContractAddress = useContractAddress("stakingContract");
const subscribeToIncentives = useWriteStakingContractSubscribeToIncentives();
const subscribeToIncentivesReceipt = useWaitForTransactionReceipt({
hash: subscribeToIncentives.data,
});

const isEnabled = enabled && isConnected;
const isEnabled = isConnected && props?.enabled !== false;
const isSuccess = subscribeToIncentivesReceipt.isSuccess;

useToast({
title: "Subscribing to rewards",
title: "Subscribe to rewards",
isLoading:
subscribeToIncentives.isPending || subscribeToIncentivesReceipt.isLoading,
isSuccess,
Expand All @@ -41,18 +36,16 @@ export const useSubscribeToIncentives = ({

useEffect(() => {
if (isSuccess) {
onSuccess?.(lastIncentiveIds);
props?.onSuccess?.();
}
}, [isSuccess, onSuccess, lastIncentiveIds]);
}, [isSuccess, props?.onSuccess]);

return {
subscribeToIncentives: (incentiveIds: bigint[]) => {
if (!isEnabled) {
return;
}

setLastIncentiveIds(incentiveIds);

return subscribeToIncentives.writeContractAsync({
address: stakingContractAddress,
args: [incentiveIds],
Expand Down
2 changes: 1 addition & 1 deletion app/hooks/useWithdrawBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const useWithdrawBatch = ({
nftVaultApproveReceipt.isLoading;

useToast({
title: "Withdrawing Rewards",
title: "Withdraw rewards",
isLoading,
isSuccess,
isError:
Expand Down
74 changes: 33 additions & 41 deletions app/routes/pools_.$id.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ import { formatTokenReserve } from "~/lib/tokens";
import { cn } from "~/lib/utils";
import type { RootLoader } from "~/root";
import { getSession } from "~/sessions";
import type { Optional, PoolToken } from "~/types";
import type { Optional, PoolToken, TroveTokenWithQuantity } from "~/types";
import type { TransactionType } from ".graphclient";

type PoolManagementTab = "deposit" | "withdraw" | "stake" | "unstake";
Expand Down Expand Up @@ -197,8 +197,7 @@ export default function PoolDetailsPage() {

const nftIncentive = userIncentives.find(
(userIncentive) =>
userIncentive.incentive.rewardToken?.isNFT &&
BigInt(userIncentive.reward) > 0,
userIncentive.isActive && userIncentive.incentive.rewardToken?.isNFT,
);

const nftIncentiveDecimals =
Expand Down Expand Up @@ -226,24 +225,8 @@ export default function PoolDetailsPage() {
refetchNftIncentiveTokenBalance();
}, [revalidator, refetchNftIncentiveTokenBalance]);

const { subscribeToIncentives } = useSubscribeToIncentives({
onSuccess: useCallback(
(incentiveIds: bigint[]) => {
// API can be slow to update, so optimistically update the subscribed list
setOptimisticSubscribedIncentiveIds((curr) =>
curr.concat(incentiveIds),
);
refetch();
},
[refetch],
),
});

const { claimRewards } = useClaimRewards({
// Doesn't need optimistic update because data is pulled directly from contract
onSuccess: refetch,
});

const { subscribeToIncentives } = useSubscribeToIncentives();
const { claimRewards } = useClaimRewards();
const { withdrawBatch, isLoading: isLoadingWithdrawBatch } = useWithdrawBatch(
{
vaultAddress: nftIncentive?.incentive.rewardTokenAddress as
Expand Down Expand Up @@ -286,6 +269,32 @@ export default function PoolDetailsPage() {
const quoteToken =
baseToken.id === pool.token1.id ? pool.token0 : pool.token1;

const handleSubscribeToAll = async () => {
const incentiveIds = [...unsubscribedIncentiveIds];
await subscribeToIncentives(incentiveIds);
// API can be slow to update, so optimistically update the subscribed list
setOptimisticSubscribedIncentiveIds((curr) => curr.concat(incentiveIds));
refetch();
};

const handleClaimRewards = async () => {
await claimRewards(subscribedIncentiveIds);
// Doesn't need optimistic update because data is pulled directly from contract
refetch();
};

const handleWithdrawRewards = async (tokens: TroveTokenWithQuantity[]) => {
await withdrawBatch(
tokens.map((token) => ({
id: BigInt(token.tokenId),
amount: BigInt(token.quantity),
collectionId: token.collectionAddr as Address,
})),
);
setIsWithdrawingFromVault(false);
refetch();
};

return (
<main className="container py-5 md:py-7">
<Link
Expand Down Expand Up @@ -502,12 +511,7 @@ export default function PoolDetailsPage() {
)}
</div>
{lpStaked > 0 && unsubscribedIncentiveIds.length > 0 ? (
<Button
className="w-full"
onClick={() =>
subscribeToIncentives(unsubscribedIncentiveIds)
}
>
<Button className="w-full" onClick={handleSubscribeToAll}>
Start earning all rewards
</Button>
) : null}
Expand Down Expand Up @@ -544,10 +548,7 @@ export default function PoolDetailsPage() {
</ul>
</div>
{hasStakingRewards ? (
<Button
className="w-full"
onClick={() => claimRewards(subscribedIncentiveIds)}
>
<Button className="w-full" onClick={handleClaimRewards}>
Claim all rewards
</Button>
) : null}
Expand Down Expand Up @@ -771,16 +772,7 @@ export default function PoolDetailsPage() {
floorBigInt(nftIncentiveTokenBalance, nftIncentiveDecimals),
nftIncentiveDecimals,
)}
onSubmit={async (tokens) => {
await withdrawBatch(
tokens.map((token) => ({
id: BigInt(token.tokenId),
amount: BigInt(token.quantity),
collectionId: token.collectionAddr as Address,
})),
);
setIsWithdrawingFromVault(false);
}}
onSubmit={handleWithdrawRewards}
isSubmitDisabled={isLoadingWithdrawBatch}
keepOpenOnSubmit
/>
Expand Down

0 comments on commit 24ebd12

Please sign in to comment.