Skip to content

Commit

Permalink
fix(console): refactor back to hook but with params
Browse files Browse the repository at this point in the history
  • Loading branch information
baktun14 committed Aug 26, 2024
1 parent d024669 commit 98a48af
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ import { DeploymentGrantTable } from "./DeploymentGrantTable";
import { FeeGrantTable } from "./FeeGrantTable";
import { GranteeRow } from "./GranteeRow";
import { GrantModal } from "./GrantModal";
import { useAllowance } from "@src/hooks/useAllowance";

type RefreshingType = "granterGrants" | "granteeGrants" | "allowancesIssued" | "allowancesGranted" | null;
const defaultRefetchInterval = 30 * 1000;
const refreshingInterval = 1000;

export const Authorizations: React.FunctionComponent = () => {
const { address, signAndBroadcastTx, isManaged } = useWallet();
const {
address,
signAndBroadcastTx,
fee: { all: allowancesGranted, isLoading: isLoadingAllowancesGranted, setDefault, default: defaultAllowance }
} = useWallet();
} = useAllowance(address, isManaged);
const [editingGrant, setEditingGrant] = useState<GrantType | null>(null);
const [editingAllowance, setEditingAllowance] = useState<AllowanceType | null>(null);
const [showGrantModal, setShowGrantModal] = useState(false);
Expand Down
89 changes: 7 additions & 82 deletions apps/deploy-web/src/context/WalletProvider/WalletProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"use client";
import React, { FC, useEffect, useMemo, useRef, useState } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import type { TxOutput } from "@akashnetwork/http-sdk";
import { Snackbar } from "@akashnetwork/ui/components";
import { EncodeObject } from "@cosmjs/proto-signing";
Expand All @@ -26,11 +26,7 @@ import { UrlService } from "@src/utils/urlUtils";
import { LocalWalletDataType } from "@src/utils/walletUtils";
import { useSelectedChain } from "../CustomChainProvider";
import { useSettings } from "../SettingsProvider";
import { useLocalStorage } from "usehooks-ts";
import { useAllowancesGranted } from "@src/queries/useGrantsQuery";
import { isAfter, parseISO } from "date-fns";
import difference from "lodash/difference";
import { AllowanceType } from "@src/types/grant";
import { useAllowance } from "@src/hooks/useAllowance";

const ERROR_MESSAGES = {
5: "Insufficient funds",
Expand Down Expand Up @@ -62,12 +58,6 @@ type ContextType = {
isWalletLoading: boolean;
isTrialing: boolean;
creditAmount?: number;
fee: {
all: AllowanceType[] | undefined;
default: string | undefined;
setDefault: (granter: string | undefined) => void;
isLoading: boolean;
};
};

const WalletProviderContext = React.createContext<ContextType>({} as ContextType);
Expand All @@ -79,18 +69,6 @@ const MESSAGE_STATES: Record<string, LoadingState> = {
"/akash.deployment.v1beta3.MsgUpdateDeployment": "updatingDeployment"
};

const persisted: Record<string, string[]> = typeof window !== "undefined" ? JSON.parse(localStorage.getItem("fee-granters") || "{}") : {};

const AllowanceNotificationMessage: FC = () => (
<>
You can update default fee granter in
<Link href="/settings/authorizations" className="inline-flex items-center space-x-2 !text-white">
<span>Authorizations Settings</span>
<OpenNewWindow className="text-xs" />
</Link>
</>
);

export const WalletProvider = ({ children }) => {
const [walletBalances, setWalletBalances] = useState<Balances | null>(null);
const [isWalletLoaded, setIsWalletLoaded] = useState<boolean>(true);
Expand All @@ -105,23 +83,10 @@ export const WalletProvider = ({ children }) => {
const { wallet: managedWallet, isLoading, create, refetch } = useManagedWallet();
const { address: walletAddress, username, isWalletConnected } = useMemo(() => managedWallet || userWallet, [managedWallet, userWallet]);
const { addEndpoints } = useManager();
// Wallet fee allowances
const [defaultFeeGranter, setDefaultFeeGranter] = useLocalStorage<string | undefined>(`default-fee-granters/${walletAddress}`, undefined);
const { data: allFeeGranters, isLoading: isLoadingAllowances, isFetched } = useAllowancesGranted(walletAddress);
const isManaged = !!managedWallet;
const actualAllowanceAddresses = useMemo(() => {
if (!walletAddress || !allFeeGranters) {
return null;
}

return allFeeGranters.reduce((acc, grant) => {
if (isAfter(parseISO(grant.allowance.expiration), new Date())) {
acc.push(grant.granter);
}

return acc;
}, [] as string[]);
}, [allFeeGranters, walletAddress]);
const {
fee: { default: feeGranter }
} = useAllowance(walletAddress as string, isManaged);

useWhen(managedWallet, refreshBalances);

Expand All @@ -143,40 +108,6 @@ export const WalletProvider = ({ children }) => {
})();
}, [settings?.rpcEndpoint, userWallet.isWalletConnected]);

useWhen(
isFetched && walletAddress && !isManaged && !!actualAllowanceAddresses,
() => {
const _actualAllowanceAddresses = actualAllowanceAddresses as string[];
const persistedAddresses = persisted[walletAddress as string] || [];
const added = difference(_actualAllowanceAddresses, persistedAddresses);
const removed = difference(persistedAddresses, _actualAllowanceAddresses);

if (added.length || removed.length) {
persisted[walletAddress as string] = _actualAllowanceAddresses;
localStorage.setItem(`fee-granters`, JSON.stringify(persisted));
}

if (added.length) {
enqueueSnackbar(<Snackbar iconVariant="info" title="New fee allowance granted" subTitle={<AllowanceNotificationMessage />} />, {
variant: "info"
});
}

if (removed.length) {
enqueueSnackbar(<Snackbar iconVariant="warning" title="Some fee allowance is revoked or expired" subTitle={<AllowanceNotificationMessage />} />, {
variant: "warning"
});
}

if (defaultFeeGranter && removed.includes(defaultFeeGranter)) {
setDefaultFeeGranter(undefined);
} else if (!defaultFeeGranter && _actualAllowanceAddresses.length) {
setDefaultFeeGranter(_actualAllowanceAddresses[0]);
}
},
[actualAllowanceAddresses, persisted]
);

async function createStargateClient() {
const selectedNetwork = networkStore.getSelectedNetwork();

Expand Down Expand Up @@ -274,7 +205,7 @@ export const WalletProvider = ({ children }) => {
const estimatedFees = await userWallet.estimateFee(msgs);
const txRaw = await userWallet.sign(msgs, {
...estimatedFees,
granter: defaultFeeGranter
granter: feeGranter
});

setLoadingState("broadcasting");
Expand Down Expand Up @@ -421,13 +352,7 @@ export const WalletProvider = ({ children }) => {
isManaged: isManaged,
isWalletLoading: isLoading,
isTrialing: !!managedWallet?.isTrialing,
creditAmount: managedWallet?.creditAmount,
fee: {
all: allFeeGranters,
default: defaultFeeGranter,
setDefault: setDefaultFeeGranter,
isLoading: isLoadingAllowances
}
creditAmount: managedWallet?.creditAmount
}}
>
{children}
Expand Down
90 changes: 90 additions & 0 deletions apps/deploy-web/src/hooks/useAllowance.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import React, { FC, useMemo } from "react";
import { Snackbar } from "@akashnetwork/ui/components";
import isAfter from "date-fns/isAfter";
import parseISO from "date-fns/parseISO";
import { OpenNewWindow } from "iconoir-react";
import difference from "lodash/difference";
import Link from "next/link";
import { useSnackbar } from "notistack";
import { useLocalStorage } from "usehooks-ts";

import { useWhen } from "@src/hooks/useWhen";
import { useAllowancesGranted } from "@src/queries/useGrantsQuery";

const persisted: Record<string, string[]> = typeof window !== "undefined" ? JSON.parse(localStorage.getItem("fee-granters") || "{}") : {};

const AllowanceNotificationMessage: FC = () => (
<>
You can update default fee granter in
<Link href="/settings/authorizations" className="inline-flex items-center space-x-2 !text-white">
<span>Authorizations Settings</span>
<OpenNewWindow className="text-xs" />
</Link>
</>
);

export const useAllowance = (address: string, isManaged: boolean) => {
const [defaultFeeGranter, setDefaultFeeGranter] = useLocalStorage<string | undefined>(`default-fee-granters/${address}`, undefined);
const { data: allFeeGranters, isLoading, isFetched } = useAllowancesGranted(address);
const { enqueueSnackbar } = useSnackbar();

const actualAllowanceAddresses = useMemo(() => {
if (!address || !allFeeGranters) {
return null;
}

return allFeeGranters.reduce((acc, grant) => {
if (isAfter(parseISO(grant.allowance.expiration), new Date())) {
acc.push(grant.granter);
}

return acc;
}, [] as string[]);
}, [allFeeGranters, address]);

useWhen(
isFetched && address && !isManaged && !!actualAllowanceAddresses,
() => {
const _actualAllowanceAddresses = actualAllowanceAddresses as string[];
const persistedAddresses = persisted[address] || [];
const added = difference(_actualAllowanceAddresses, persistedAddresses);
const removed = difference(persistedAddresses, _actualAllowanceAddresses);

if (added.length || removed.length) {
persisted[address] = _actualAllowanceAddresses;
localStorage.setItem(`fee-granters`, JSON.stringify(persisted));
}

if (added.length) {
enqueueSnackbar(<Snackbar iconVariant="info" title="New fee allowance granted" subTitle={<AllowanceNotificationMessage />} />, {
variant: "info"
});
}

if (removed.length) {
enqueueSnackbar(<Snackbar iconVariant="warning" title="Some fee allowance is revoked or expired" subTitle={<AllowanceNotificationMessage />} />, {
variant: "warning"
});
}

if (defaultFeeGranter && removed.includes(defaultFeeGranter)) {
setDefaultFeeGranter(undefined);
} else if (!defaultFeeGranter && _actualAllowanceAddresses.length) {
setDefaultFeeGranter(_actualAllowanceAddresses[0]);
}
},
[actualAllowanceAddresses, persisted]
);

return useMemo(
() => ({
fee: {
all: allFeeGranters,
default: defaultFeeGranter,
setDefault: setDefaultFeeGranter,
isLoading
}
}),
[defaultFeeGranter, setDefaultFeeGranter, allFeeGranters, isLoading]
);
};

0 comments on commit 98a48af

Please sign in to comment.