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

feat(wallet): add fee granter to transaction signer #238

Merged
merged 2 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { FormattedTime } from "react-intl";

import { Address } from "@src/components/shared/Address";
import { AKTAmount } from "@src/components/shared/AKTAmount";
import { Checkbox } from "@src/components/ui/checkbox";
import { TableCell, TableRow } from "@src/components/ui/table";
import { AllowanceType } from "@src/types/grant";
import { getAllowanceTitleByType } from "@src/utils/grants";
Expand All @@ -12,21 +13,24 @@ import { coinToUDenom } from "@src/utils/priceUtils";
type Props = {
allowance: AllowanceType;
children?: ReactNode;
onSelect?: () => void;
selected?: boolean;
};

export const AllowanceGrantedRow: React.FunctionComponent<Props> = ({ allowance }) => {
export const AllowanceGrantedRow: React.FunctionComponent<Props> = ({ allowance, selected, onSelect }) => {
const limit = allowance?.allowance.spend_limit[0];
return (
<TableRow className="[&>td]:px-2 [&>td]:py-1">
<TableCell>{getAllowanceTitleByType(allowance)}</TableCell>
<TableCell>
<Address address={allowance.granter} isCopyable />
<Checkbox className="ml-2" checked={selected} onCheckedChange={typeof onSelect === "function" ? checked => checked && onSelect() : undefined} />
</TableCell>
<TableCell>{getAllowanceTitleByType(allowance)}</TableCell>
<TableCell>{allowance.granter && <Address address={allowance.granter} isCopyable />}</TableCell>
<TableCell>
<AKTAmount uakt={coinToUDenom(allowance.allowance.spend_limit[0])} /> AKT
</TableCell>
<TableCell align="right">
<FormattedTime year="numeric" month={"numeric"} day={"numeric"} value={allowance.allowance.expiration} />
{limit && <AKTAmount uakt={coinToUDenom(limit)} />}
{limit && "AKT"}
</TableCell>
<TableCell align="right">{<FormattedTime year="numeric" month={"numeric"} day={"numeric"} value={allowance.allowance.expiration} />}</TableCell>
</TableRow>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FC } from "react";

import { useAllowance } from "@src/hooks/useAllowance";

export const AllowanceWatcher: FC = () => {
useAllowance();
return null;
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import Spinner from "@src/components/shared/Spinner";
import { Button } from "@akashnetwork/ui/components";
import { Table, TableBody, TableHead, TableHeader, TableRow } from "@src/components/ui/table";
import { useWallet } from "@src/context/WalletProvider";
import { useAllowancesGranted, useAllowancesIssued, useGranteeGrants, useGranterGrants } from "@src/queries/useGrantsQuery";
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";
import { TransactionMessageData } from "@src/utils/TransactionMessageData";
Expand Down Expand Up @@ -46,9 +47,9 @@ export const Authorizations: React.FunctionComponent = () => {
const { data: allowancesIssued, isLoading: isLoadingAllowancesIssued } = useAllowancesIssued(address, {
refetchInterval: isRefreshing === "allowancesIssued" ? refreshingInterval : defaultRefetchInterval
});
const { data: allowancesGranted, isLoading: isLoadingAllowancesGranted } = useAllowancesGranted(address, {
refetchInterval: isRefreshing === "allowancesGranted" ? refreshingInterval : defaultRefetchInterval
});
const {
fee: { all: allowancesGranted, isLoading: isLoadingAllowancesGranted, setDefault, default: defaultAllowance }
} = useAllowance();

useEffect(() => {
let timeout: NodeJS.Timeout;
Expand Down Expand Up @@ -261,6 +262,7 @@ export const Authorizations: React.FunctionComponent = () => {
<Table>
<TableHeader>
<TableRow>
<TableHead>Default</TableHead>
<TableHead>Type</TableHead>
<TableHead>Grantee</TableHead>
<TableHead>Spending Limit</TableHead>
Expand All @@ -269,8 +271,25 @@ export const Authorizations: React.FunctionComponent = () => {
</TableHeader>

<TableBody>
{!!allowancesGranted && (
<AllowanceGrantedRow
key={address}
allowance={{
granter: "",
grantee: "",
allowance: { "@type": "$CONNECTED_WALLET", expiration: "", spend_limit: [] }
}}
onSelect={() => setDefault(undefined)}
selected={!defaultAllowance}
/>
)}
{allowancesGranted.map(allowance => (
<AllowanceGrantedRow key={allowance.granter} allowance={allowance} />
<AllowanceGrantedRow
key={allowance.granter}
allowance={allowance}
onSelect={() => setDefault(allowance.granter)}
selected={defaultAllowance === allowance.granter}
/>
))}
</TableBody>
</Table>
Expand Down
72 changes: 70 additions & 2 deletions apps/deploy-web/src/components/shared/Popup.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as React from "react";
import { useMemo } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { DialogProps } from "@radix-ui/react-dialog";

import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@src/components/ui/select";
import { cn } from "@src/utils/styleUtils";
import { Button, ButtonProps } from "@akashnetwork/ui/components";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle as _DialogTitle } from "../ui/dialog";
Expand Down Expand Up @@ -32,6 +34,21 @@ type CustomPrompt = {
actions: ActionButton[];
};

export type SelectOption = {
text: string;
value: string;
selected?: boolean;
disabled?: boolean;
};

export type SelectProps = {
variant: "select";
options: SelectOption[];
placeholder?: string;
onValidate: (value: string | undefined) => void;
onCancel: () => void;
};

export type TOnCloseHandler = {
(event: any, reason: "backdropClick" | "escapeKeyDown" | "action"): void;
};
Expand All @@ -58,7 +75,7 @@ export type ActionButton = ButtonProps & {
isLoading?: boolean;
};

export type PopupProps = (MessageProps | ConfirmProps | PromptProps | CustomPrompt) & CommonProps;
export type PopupProps = (MessageProps | ConfirmProps | PromptProps | CustomPrompt | SelectProps) & CommonProps;

export interface DialogTitleProps {
children: React.ReactNode;
Expand All @@ -78,6 +95,8 @@ export const DialogTitle = (props: DialogTitleProps) => {

export function Popup(props: React.PropsWithChildren<PopupProps>) {
const [promptInput, setPromptInput] = React.useState("");
const initialOption = useMemo(() => (props.variant === "select" ? props.options.find(option => option.selected)?.value : undefined), [props]);
const [selectOption, setSelectOption] = React.useState<SelectOption["value"] | undefined>(initialOption);
const component = [] as JSX.Element[];

const onClose: TOnCloseHandler = (event, reason) => {
Expand All @@ -97,7 +116,30 @@ export function Popup(props: React.PropsWithChildren<PopupProps>) {
component.push(<DialogTitle key="dialog-title">{props.title}</DialogTitle>);
}

if (props.message && props.variant !== "prompt") {
if (props.variant === "select") {
component.push(
<ScrollArea className="max-h-[75vh]" key="dialog-content">
{props.message}
{props.variant === "select" ? (
<Select value={selectOption} onValueChange={setSelectOption}>
<SelectTrigger>
<SelectValue placeholder={props.placeholder} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{props.options.map((option: SelectOption) => (
<SelectItem key={option.value} value={option.value} disabled={option.disabled}>
{option.text}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
) : null}
<ScrollBar orientation="horizontal" />
</ScrollArea>
);
} else if (props.message && props.variant !== "prompt") {
component.push(
<ScrollArea className="max-h-[75vh]" key="dialog-content">
{props.message}
Expand Down Expand Up @@ -215,6 +257,32 @@ export function Popup(props: React.PropsWithChildren<PopupProps>) {
);
break;
}
case "select": {
component.push(
<DialogFooter key="DialogActions" className="justify-between">
<Button
variant="ghost"
onClick={() => {
props.onCancel();
onClose(null, "action");
}}
>
{CancelButtonLabel}
</Button>
<Button
variant="default"
color="primary"
onClick={() => {
props.onValidate(selectOption);
onClose(null, "action");
}}
>
{ConfirmButtonLabel}
</Button>
</DialogFooter>
);
break;
}
}

/**
Expand Down
43 changes: 40 additions & 3 deletions apps/deploy-web/src/context/PopupProvider/PopupProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
import React, { useCallback, useMemo, useState } from "react";
import { firstValueFrom, Subject } from "rxjs";

import { CommonProps, ConfirmProps, Popup, PopupProps } from "@src/components/shared/Popup";
import { CommonProps, ConfirmProps, Popup, PopupProps, SelectOption, SelectProps } from "@src/components/shared/Popup";
import type { FCWithChildren } from "@src/types/component";

type ConfirmPopupProps = string | (Omit<CommonProps, "onClose" | "open"> & Omit<ConfirmProps, "onValidate" | "onCancel" | "variant">);
type SelectPopupProps = Omit<CommonProps, "onClose" | "open"> & Omit<SelectProps, "onValidate" | "onCancel" | "variant">;

type PopupProviderContext = {
confirm: (messageOrProps: ConfirmPopupProps) => Promise<boolean>;
select: (props: SelectPopupProps) => Promise<string | undefined>;
};

const PopupContext = React.createContext<PopupProviderContext | undefined>(undefined);

export const PopupProvider: FCWithChildren = ({ children }) => {
const [popupProps, setPopupProps] = useState<PopupProps | undefined>();

const confirm = useCallback(
const confirm: PopupProviderContext["confirm"] = useCallback(
(messageOrProps: ConfirmPopupProps) => {
let subject: Subject<boolean> | undefined = new Subject<boolean>();

Expand Down Expand Up @@ -45,7 +47,42 @@ export const PopupProvider: FCWithChildren = ({ children }) => {
[setPopupProps]
);

const context = useMemo(() => ({ confirm }), [confirm]);
const select: PopupProviderContext["select"] = useCallback(
props => {
let subject: Subject<SelectOption["value"] | undefined> | undefined = new Subject<SelectOption["value"] | undefined>();

const reject = () => {
if (subject) {
subject.next(undefined);
subject.complete();
setPopupProps(undefined);
subject = undefined;
}
};

setPopupProps({
title: "Confirm",
...props,
open: true,
variant: "select",
onValidate: value => {
if (subject) {
subject.next(value);
subject.complete();
setPopupProps(undefined);
subject = undefined;
}
},
onCancel: reject,
onClose: reject
});

return firstValueFrom(subject);
},
[setPopupProps]
);

const context = useMemo(() => ({ confirm, select }), [confirm]);

return (
<PopupContext.Provider value={context}>
Expand Down
10 changes: 8 additions & 2 deletions apps/deploy-web/src/context/WalletProvider/WalletProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { SnackbarKey, useSnackbar } from "notistack";

import { TransactionModal } from "@src/components/layout/TransactionModal";
import { Snackbar } from "@src/components/shared/Snackbar";
import { useAllowance } from "@src/hooks/useAllowance";
import { useUsdcDenom } from "@src/hooks/useDenom";
import { getSelectedNetwork, useSelectedNetwork } from "@src/hooks/useSelectedNetwork";
import { AnalyticsEvents } from "@src/utils/analytics";
Expand Down Expand Up @@ -55,6 +56,9 @@ export const WalletProvider = ({ children }) => {
const usdcIbcDenom = useUsdcDenom();
const { disconnect, getOfflineSigner, isWalletConnected, address: walletAddress, connect, username, estimateFee, sign, broadcast } = useSelectedChain();
const { addEndpoints } = useManager();
const {
fee: { default: feeGranter }
} = useAllowance();

useEffect(() => {
if (!settings.apiEndpoint || !settings.rpcEndpoint) return;
Expand Down Expand Up @@ -160,8 +164,10 @@ export const WalletProvider = ({ children }) => {
let pendingSnackbarKey: SnackbarKey | null = null;
try {
const estimatedFees = await estimateFee(msgs);

const txRaw = await sign(msgs, estimatedFees);
const txRaw = await sign(msgs, {
...estimatedFees,
granter: feeGranter
});

setIsWaitingForApproval(false);
setIsBroadcastingTx(true);
Expand Down
Loading
Loading