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

fix(console): refactor useAllowance hook #336

Merged
merged 2 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { NextSeo } from "next-seo";

import { Fieldset } from "@src/components/shared/Fieldset";
import { useWallet } from "@src/context/WalletProvider";
import { useAllowance } from "@src/hooks/useAllowance";
import { useAllowancesIssued, useGranteeGrants, useGranterGrants } from "@src/queries/useGrantsQuery";
import { AllowanceType, GrantType } from "@src/types/grant";
import { averageBlockTime } from "@src/utils/priceUtils";
Expand All @@ -27,7 +26,11 @@ const defaultRefetchInterval = 30 * 1000;
const refreshingInterval = 1000;

export const Authorizations: React.FunctionComponent = () => {
const { address, signAndBroadcastTx } = useWallet();
const {
address,
signAndBroadcastTx,
fee: { all: allowancesGranted, isLoading: isLoadingAllowancesGranted, setDefault, default: defaultAllowance }
} = useWallet();
const [editingGrant, setEditingGrant] = useState<GrantType | null>(null);
const [editingAllowance, setEditingAllowance] = useState<AllowanceType | null>(null);
const [showGrantModal, setShowGrantModal] = useState(false);
Expand All @@ -46,9 +49,6 @@ export const Authorizations: React.FunctionComponent = () => {
const { data: allowancesIssued, isLoading: isLoadingAllowancesIssued } = useAllowancesIssued(address, {
refetchInterval: isRefreshing === "allowancesIssued" ? refreshingInterval : defaultRefetchInterval
});
const {
fee: { all: allowancesGranted, isLoading: isLoadingAllowancesGranted, setDefault, default: defaultAllowance }
} = useAllowance();

useEffect(() => {
let timeout: NodeJS.Timeout;
Expand Down
93 changes: 84 additions & 9 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, { useEffect, useMemo, useRef, useState } from "react";
import React, { FC, 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 @@ -13,7 +13,6 @@ import { event } from "nextjs-google-analytics";
import { SnackbarKey, useSnackbar } from "notistack";

import { LoadingState, TransactionModal } from "@src/components/layout/TransactionModal";
import { useAllowance } from "@src/hooks/useAllowance";
import { useUsdcDenom } from "@src/hooks/useDenom";
import { useManagedWallet } from "@src/hooks/useManagedWallet";
import { useUser } from "@src/hooks/useUser";
Expand All @@ -27,6 +26,11 @@ 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";

const ERROR_MESSAGES = {
5: "Insufficient funds",
Expand Down Expand Up @@ -58,6 +62,12 @@ 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 @@ -69,6 +79,18 @@ 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 @@ -79,14 +101,27 @@ export const WalletProvider = ({ children }) => {
const { settings } = useSettings();
const usdcIbcDenom = useUsdcDenom();
const user = useUser();

const userWallet = useSelectedChain();
const { wallet: managedWallet, isLoading, create, refetch } = useManagedWallet();
const { address: walletAddress, username, isWalletConnected } = useMemo(() => managedWallet || userWallet, [managedWallet, userWallet]);
const { addEndpoints } = useManager();
const {
fee: { default: feeGranter }
} = useAllowance();
// 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]);

useWhen(managedWallet, refreshBalances);

Expand All @@ -108,6 +143,40 @@ 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 @@ -205,7 +274,7 @@ export const WalletProvider = ({ children }) => {
const estimatedFees = await userWallet.estimateFee(msgs);
const txRaw = await userWallet.sign(msgs, {
...estimatedFees,
granter: feeGranter
granter: defaultFeeGranter
});

setLoadingState("broadcasting");
Expand Down Expand Up @@ -349,10 +418,16 @@ export const WalletProvider = ({ children }) => {
logout,
signAndBroadcastTx,
refreshBalances,
isManaged: !!managedWallet,
isManaged: isManaged,
isWalletLoading: isLoading,
isTrialing: !!managedWallet?.isTrialing,
creditAmount: managedWallet?.creditAmount
creditAmount: managedWallet?.creditAmount,
fee: {
all: allFeeGranters,
default: defaultFeeGranter,
setDefault: setDefaultFeeGranter,
isLoading: isLoadingAllowances
}
}}
>
{children}
Expand Down
89 changes: 0 additions & 89 deletions apps/deploy-web/src/hooks/useAllowance.tsx

This file was deleted.

2 changes: 0 additions & 2 deletions apps/deploy-web/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import Router from "next/router";
import { ThemeProvider } from "next-themes";
import NProgress from "nprogress";

import { AllowanceWatcher } from "@src/components/authorizations/AllowanceWatcher";
import GoogleAnalytics from "@src/components/layout/CustomGoogleAnalytics";
import { CustomIntlProvider } from "@src/components/layout/CustomIntlProvider";
import { PageHead } from "@src/components/layout/PageHead";
Expand Down Expand Up @@ -71,7 +70,6 @@ const App: React.FunctionComponent<Props> = props => {
<BackgroundTaskProvider>
<TemplatesProvider>
<LocalNoteProvider>
<AllowanceWatcher />
<GoogleAnalytics />
<Component {...pageProps} />
</LocalNoteProvider>
Expand Down
8 changes: 4 additions & 4 deletions apps/deploy-web/src/queries/useGrantsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ApiUrlService } from "@src/utils/apiUtils";
import { QueryKeys } from "./queryKeys";

async function getGranterGrants(apiEndpoint: string, address: string) {
if (!address || !apiEndpoint) return [];
if (!address || !apiEndpoint) return undefined;

const response = await axios.get(ApiUrlService.granterGrants(apiEndpoint, address));
const filteredGrants = response.data.grants.filter(
Expand All @@ -26,7 +26,7 @@ export function useGranterGrants(address: string, options = {}) {
}

async function getGranteeGrants(apiEndpoint: string, address: string) {
if (!address || !apiEndpoint) return [];
if (!address || !apiEndpoint) return undefined;

const response = await axios.get(ApiUrlService.granteeGrants(apiEndpoint, address));
const filteredGrants = response.data.grants.filter(
Expand All @@ -47,7 +47,7 @@ export function useGranteeGrants(address: string, options = {}) {
}

async function getAllowancesIssued(apiEndpoint: string, address: string) {
if (!address || !apiEndpoint) return [];
if (!address || !apiEndpoint) return undefined;

const response = await axios.get(ApiUrlService.allowancesIssued(apiEndpoint, address));

Expand All @@ -61,7 +61,7 @@ export function useAllowancesIssued(address: string, options = {}) {
}

async function getAllowancesGranted(apiEndpoint: string, address: string) {
if (!address || !apiEndpoint) return [];
if (!address || !apiEndpoint) return undefined;

const response = await axios.get(ApiUrlService.allowancesGranted(apiEndpoint, address));

Expand Down
Loading