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

Features/fee grant #17

Merged
merged 7 commits into from
Sep 13, 2023
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 @@ -97,7 +97,7 @@ export const DeploymentDepositModal: React.FunctionComponent<Props> = ({ handleC
let spendLimitUDenom = coinToUDenom(grant.authorization.spend_limit);

if (depositAmount > spendLimitUDenom) {
setError(`Spend limit remaining: ${udenomToDenom(spendLimitUDenom)} ${depositData.label}`);
setError(`Spend limit remaining: ${udenomToDenom(spendLimitUDenom)} ${depositData?.label}`);
return false;
}

Expand All @@ -117,7 +117,7 @@ export const DeploymentDepositModal: React.FunctionComponent<Props> = ({ handleC

const onBalanceClick = () => {
clearErrors();
setValue("amount", depositData.inputMax);
setValue("amount", depositData?.inputMax);
};

const onDepositClick = event => {
Expand Down
2 changes: 1 addition & 1 deletion deploy-web/src/components/graph/Graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const useStyles = makeStyles()(theme => ({
fontWeight: "bold",
letterSpacing: "1px",
fontSize: "1rem",
color: "rgba(255,255,255,.2)"
color: theme.palette.mode === "dark" ? theme.palette.grey[800] : theme.palette.grey[400]
}
},
graphTooltip: {
Expand Down
33 changes: 33 additions & 0 deletions deploy-web/src/components/settings/AllowanceGrantedRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React, { ReactNode } from "react";
import { TableCell } from "@mui/material";
import { CustomTableRow } from "../shared/CustomTable";
import { Address } from "../shared/Address";
import { FormattedTime } from "react-intl";
import { AllowanceType } from "@src/types/grant";
import { AKTAmount } from "../shared/AKTAmount";
import { coinToUDenom } from "@src/utils/priceUtils";
import { getAllowanceTitleByType } from "@src/utils/grants";

type Props = {
allowance: AllowanceType;
children?: ReactNode;
};

export const AllowanceGrantedRow: React.FunctionComponent<Props> = ({ allowance }) => {
// const denomData = useDenomData(grant.authorization.spend_limit.denom);

return (
<CustomTableRow>
<TableCell>{getAllowanceTitleByType(allowance)}</TableCell>
<TableCell>
<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} />
</TableCell>
</CustomTableRow>
);
};
45 changes: 45 additions & 0 deletions deploy-web/src/components/settings/AllowanceIssuedRow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React, { ReactNode } from "react";
import { IconButton, TableCell } from "@mui/material";
import { CustomTableRow } from "../shared/CustomTable";
import { Address } from "../shared/Address";
import { FormattedTime } from "react-intl";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import { AllowanceType } from "@src/types/grant";
import { AKTAmount } from "../shared/AKTAmount";
import { coinToUDenom } from "@src/utils/priceUtils";
import { getAllowanceTitleByType } from "@src/utils/grants";

type Props = {
allowance: AllowanceType;
children?: ReactNode;
onEditAllowance: (allowance: AllowanceType) => void;
setDeletingAllowance: (grantallowance: AllowanceType) => void;
};

export const AllowanceIssuedRow: React.FunctionComponent<Props> = ({ allowance, onEditAllowance, setDeletingAllowance }) => {
// const denomData = useDenomData(grant.authorization.spend_limit.denom);

return (
<CustomTableRow>
<TableCell>{getAllowanceTitleByType(allowance)}</TableCell>
<TableCell>
<Address address={allowance.grantee} isCopyable />
</TableCell>
<TableCell align="right">
<AKTAmount uakt={coinToUDenom(allowance.allowance.spend_limit[0])} /> AKT
</TableCell>
<TableCell align="right">
<FormattedTime year="numeric" month={"numeric"} day={"numeric"} value={allowance.allowance.expiration} />
</TableCell>
<TableCell align="right">
<IconButton onClick={() => onEditAllowance(allowance)}>
<EditIcon />
</IconButton>
<IconButton onClick={() => setDeletingAllowance(allowance)}>
<DeleteIcon />
</IconButton>
</TableCell>
</CustomTableRow>
);
};
2 changes: 1 addition & 1 deletion deploy-web/src/components/settings/GranterRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const GranterRow: React.FunctionComponent<Props> = ({ children, grant, on
<TableCell align="right">
<FormattedTime year="numeric" month={"numeric"} day={"numeric"} value={grant.expiration} />
</TableCell>
<TableCell>
<TableCell align="right">
<IconButton onClick={() => onEditGrant(grant)}>
<EditIcon />
</IconButton>
Expand Down
222 changes: 222 additions & 0 deletions deploy-web/src/components/wallet/AllowanceModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
import { useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { FormControl, TextField, Typography, Box, Alert, InputAdornment } from "@mui/material";
import { addYears, format } from "date-fns";
import { makeStyles } from "tss-react/mui";
import { useKeplr } from "@src/context/KeplrWalletProvider";
import { aktToUakt, coinToDenom } from "@src/utils/priceUtils";
import { TransactionMessageData } from "@src/utils/TransactionMessageData";
import { LinkTo } from "../shared/LinkTo";
import { event } from "nextjs-google-analytics";
import { AnalyticsEvents } from "@src/utils/analytics";
import { AllowanceType } from "@src/types/grant";
import { Popup } from "../shared/Popup";
import { useDenomData } from "@src/hooks/useWalletBalance";
import { uAktDenom } from "@src/utils/constants";
import { FormattedDate } from "react-intl";

const useStyles = makeStyles()(theme => ({
formControl: {
marginBottom: "1rem"
}
}));

type Props = {
address: string;
editingAllowance?: AllowanceType;
onClose: () => void;
};

export const AllowanceModal: React.FunctionComponent<Props> = ({ editingAllowance, address, onClose }) => {
const formRef = useRef(null);
const [error, setError] = useState("");
const { classes } = useStyles();
const { signAndBroadcastTx } = useKeplr();
const {
handleSubmit,
control,
formState: { errors },
watch,
clearErrors,
setValue
} = useForm({
defaultValues: {
amount: editingAllowance ? coinToDenom(editingAllowance.allowance.spend_limit[0]) : 0,
expiration: format(addYears(new Date(), 1), "yyyy-MM-dd'T'HH:mm"),
useDepositor: false,
granteeAddress: editingAllowance?.grantee ?? ""
}
});
const { amount, granteeAddress, expiration } = watch();
const denomData = useDenomData(uAktDenom);

const onDepositClick = event => {
event.preventDefault();
formRef.current.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
};

const onSubmit = async ({ amount }) => {
setError("");
clearErrors();

const messages = [];
const spendLimit = aktToUakt(amount);
const expirationDate = new Date(expiration);

if (editingAllowance) {
messages.push(TransactionMessageData.getRevokeAllowanceMsg(address, granteeAddress));
}
messages.push(TransactionMessageData.getGrantBasicAllowanceMsg(address, granteeAddress, spendLimit, uAktDenom, expirationDate));
const response = await signAndBroadcastTx(messages);

if (response) {
event(AnalyticsEvents.AUTHORIZE_SPEND, {
category: "deployments",
label: "Authorize wallet to spend on deployment deposits"
});

onClose();
}
};

function handleDocClick(ev, url: string) {
ev.preventDefault();

window.open(url, "_blank");
}

const onBalanceClick = () => {
clearErrors();
setValue("amount", denomData?.inputMax);
};

return (
<Popup
fullWidth
open
variant="custom"
actions={[
{
label: "Cancel",
color: "primary",
variant: "text",
side: "left",
onClick: onClose
},
{
label: "Grant",
color: "secondary",
variant: "contained",
side: "right",
disabled: !amount,
onClick: onDepositClick
}
]}
onClose={onClose}
maxWidth="sm"
enableCloseOnBackdropClick
title="Authorize Fee Spending"
>
<form onSubmit={handleSubmit(onSubmit)} ref={formRef}>
<Alert severity="info" sx={{ marginBottom: "1rem" }}>
<Typography variant="caption">
<LinkTo onClick={ev => handleDocClick(ev, "https://docs.cosmos.network/v0.46/modules/feegrant/")}>Authorized Fee Spend</LinkTo> allows users to
authorize spend of a set number of tokens on fees from a source wallet to a destination, funded wallet.
</Typography>
</Alert>

<Box marginBottom=".5rem" marginTop=".5rem" textAlign="right">
<LinkTo onClick={() => onBalanceClick()}>
Balance: {denomData?.balance} {denomData?.label}
</LinkTo>
</Box>

<FormControl className={classes.formControl} fullWidth>
<Controller
control={control}
name="amount"
rules={{
required: true
}}
render={({ fieldState, field }) => {
const helperText = fieldState.error?.type === "validate" ? "Invalid amount." : "Amount is required.";

return (
<TextField
{...field}
type="number"
variant="outlined"
label="Spending Limit"
autoFocus
error={!!fieldState.error}
helperText={fieldState.error && helperText}
inputProps={{ min: 0, step: 0.000001, max: denomData?.inputMax }}
InputProps={{
startAdornment: <InputAdornment position="start">AKT</InputAdornment>
}}
/>
);
}}
/>
</FormControl>

<FormControl className={classes.formControl} fullWidth>
<Controller
control={control}
name="granteeAddress"
defaultValue=""
rules={{
required: true
}}
render={({ fieldState, field }) => {
return (
<TextField
{...field}
type="text"
variant="outlined"
label="Grantee Address"
disabled={!!editingAllowance}
error={!!fieldState.error}
helperText={fieldState.error && "Grantee address is required."}
/>
);
}}
/>
</FormControl>

<FormControl className={classes.formControl} fullWidth>
<Controller
control={control}
name="expiration"
rules={{
required: true
}}
render={({ fieldState, field }) => {
return (
<TextField
{...field}
type="datetime-local"
variant="outlined"
label="Expiration"
error={!!fieldState.error}
helperText={fieldState.error && "Expiration is required."}
/>
);
}}
/>
</FormControl>

{!!amount && granteeAddress && (
<Alert severity="info" variant="outlined">
<Typography variant="caption">
This address will be able to spend up to {amount} AKT on <b>transaction fees</b> on your behalf ending on{" "}
<FormattedDate value={expiration} year="numeric" month="2-digit" day="2-digit" hour="2-digit" minute="2-digit" />.
</Typography>
</Alert>
)}

{error && <Alert severity="warning">{error}</Alert>}
</form>
</Popup>
);
};
8 changes: 4 additions & 4 deletions deploy-web/src/components/wallet/GrantModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const GrantModal: React.FunctionComponent<Props> = ({ editingGrant, addre
const { amount, granteeAddress, expiration, token } = watch();
const selectedToken = supportedTokens.find(x => x.id === token);
const denom = token === "akt" ? uAktDenom : usdcDenom;
const depositData = useDenomData(denom);
const denomData = useDenomData(denom);

const onDepositClick = event => {
event.preventDefault();
Expand Down Expand Up @@ -95,7 +95,7 @@ export const GrantModal: React.FunctionComponent<Props> = ({ editingGrant, addre

const onBalanceClick = () => {
clearErrors();
setValue("amount", depositData.inputMax);
setValue("amount", denomData?.inputMax);
};

return (
Expand Down Expand Up @@ -145,7 +145,7 @@ export const GrantModal: React.FunctionComponent<Props> = ({ editingGrant, addre

<Box marginBottom=".5rem" marginTop=".5rem" textAlign="right">
<LinkTo onClick={() => onBalanceClick()}>
Balance: {depositData?.balance} {depositData?.label}
Balance: {denomData?.balance} {denomData?.label}
</LinkTo>
</Box>

Expand Down Expand Up @@ -189,7 +189,7 @@ export const GrantModal: React.FunctionComponent<Props> = ({ editingGrant, addre
autoFocus
error={!!fieldState.error}
helperText={fieldState.error && helperText}
inputProps={{ min: 0, step: 0.000001, max: depositData?.inputMax }}
inputProps={{ min: 0, step: 0.000001, max: denomData?.inputMax }}
sx={{ flexGrow: 1, marginLeft: "1rem" }}
/>
);
Expand Down
Loading