Skip to content

Commit

Permalink
feat(deployment): implement ato top up setting
Browse files Browse the repository at this point in the history
closes #412
  • Loading branch information
ygrishajev committed Nov 22, 2024
1 parent 6e31276 commit bfa085f
Show file tree
Hide file tree
Showing 16 changed files with 666 additions and 14 deletions.
12 changes: 10 additions & 2 deletions apps/deploy-web/src/components/authorizations/Authorizations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Bank } from "iconoir-react";
import { NextSeo } from "next-seo";

import { Fieldset } from "@src/components/shared/Fieldset";
import { browserEnvConfig } from "@src/config/browser-env.config";
import { useWallet } from "@src/context/WalletProvider";
import { useAllowance } from "@src/hooks/useAllowance";
import { useAllowancesIssued, useGranteeGrants, useGranterGrants } from "@src/queries/useGrantsQuery";
Expand All @@ -26,6 +27,11 @@ type RefreshingType = "granterGrants" | "granteeGrants" | "allowancesIssued" | "
const defaultRefetchInterval = 30 * 1000;
const refreshingInterval = 1000;

const MASTER_WALLETS = new Set([
browserEnvConfig.NEXT_PUBLIC_USDC_TOP_UP_MASTER_WALLET_ADDRESS,
browserEnvConfig.NEXT_PUBLIC_UAKT_TOP_UP_MASTER_WALLET_ADDRESS
]);

export const Authorizations: React.FunctionComponent = () => {
const { address, signAndBroadcastTx, isManaged } = useWallet();
const {
Expand All @@ -41,13 +47,15 @@ export const Authorizations: React.FunctionComponent = () => {
const [selectedGrants, setSelectedGrants] = useState<GrantType[]>([]);
const [selectedAllowances, setSelectedAllowances] = useState<AllowanceType[]>([]);
const { data: granterGrants, isLoading: isLoadingGranterGrants } = useGranterGrants(address, {
refetchInterval: isRefreshing === "granterGrants" ? refreshingInterval : defaultRefetchInterval
refetchInterval: isRefreshing === "granterGrants" ? refreshingInterval : defaultRefetchInterval,
select: (data: GrantType[]) => data.filter(grant => !MASTER_WALLETS.has(grant.grantee))
});
const { data: granteeGrants, isLoading: isLoadingGranteeGrants } = useGranteeGrants(address, {
refetchInterval: isRefreshing === "granteeGrants" ? refreshingInterval : defaultRefetchInterval
});
const { data: allowancesIssued, isLoading: isLoadingAllowancesIssued } = useAllowancesIssued(address, {
refetchInterval: isRefreshing === "allowancesIssued" ? refreshingInterval : defaultRefetchInterval
refetchInterval: isRefreshing === "allowancesIssued" ? refreshingInterval : defaultRefetchInterval,
select: (data: AllowanceType[]) => data.filter(allowance => !MASTER_WALLETS.has(allowance.grantee))
});

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import React, { FC, useCallback, useEffect, useMemo } from "react";
import { Controller, SubmitHandler, useForm } from "react-hook-form";
import { Button, Form, FormField, FormInput } from "@akashnetwork/ui/components";
import { zodResolver } from "@hookform/resolvers/zod";
import addYears from "date-fns/addYears";
import format from "date-fns/format";
import { z } from "zod";

import { aktToUakt, uaktToAKT } from "@src/utils/priceUtils";

const positiveNumberSchema = z.coerce.number().min(0, {
message: "Amount must be greater or equal to 0."
});

const formSchema = z
.object({
uaktFeeLimit: positiveNumberSchema,
usdcFeeLimit: positiveNumberSchema,
uaktDeploymentLimit: positiveNumberSchema,
usdcDeploymentLimit: positiveNumberSchema,
expiration: z.string().min(1, "Expiration is required.")
})
.refine(
data => {
if (data.usdcDeploymentLimit > 0) {
return data.usdcFeeLimit > 0;
}
return true;
},
{
message: "Must be greater than 0 if `USDC Deployments Limit` is greater than 0",
path: ["usdcFeeLimit"]
}
)
.refine(
data => {
if (data.usdcFeeLimit > 0) {
return data.usdcDeploymentLimit > 0;
}
return true;
},
{
message: "Must be greater than 0 if `USDC Fees Limit` is greater than 0",
path: ["usdcDeploymentLimit"]
}
)
.refine(
data => {
if (data.uaktDeploymentLimit > 0) {
return data.uaktFeeLimit > 0;
}
return true;
},
{
message: "Must be greater than 0 if `AKT Deployments Limit` is greater than 0",
path: ["uaktFeeLimit"]
}
)
.refine(
data => {
if (data.uaktFeeLimit > 0) {
return data.uaktDeploymentLimit > 0;
}
return true;
},
{
message: "Must be greater than 0 if `AKT Fees Limit` is greater than 0",
path: ["uaktDeploymentLimit"]
}
);

type FormValues = z.infer<typeof formSchema>;

type LimitFields = keyof Omit<FormValues, "expiration">;

type AutoTopUpSubmitHandler = (action: "revoke-all" | "update", next: FormValues) => Promise<void>;

export interface AutoTopUpSettingProps extends Partial<Record<LimitFields, number>> {
onSubmit: AutoTopUpSubmitHandler;
expiration?: Date;
}

const fields: LimitFields[] = ["uaktFeeLimit", "usdcFeeLimit", "uaktDeploymentLimit", "usdcDeploymentLimit"];

export const AutoTopUpSetting: FC<AutoTopUpSettingProps> = ({ onSubmit, expiration, ...props }) => {
const hasAny = useMemo(() => fields.some(field => props[field]), [props]);

const defaultLimitValues = useMemo(() => {
return fields.reduce(
(acc, field) => {
acc[field] = uaktToAKT(props[field] || 0);
return acc;
},
{} as Record<LimitFields, number>
);
}, [props]);

const form = useForm<z.infer<typeof formSchema>>({
defaultValues: {
...defaultLimitValues,
expiration: format(expiration || addYears(new Date(), 1), "yyyy-MM-dd'T'HH:mm")
},
resolver: zodResolver(formSchema)
});
const { handleSubmit, control, setValue, reset } = form;

useEffect(() => {
setValue("uaktFeeLimit", uaktToAKT(props.uaktFeeLimit || 0));
}, [props.uaktFeeLimit]);

useEffect(() => {
setValue("usdcFeeLimit", uaktToAKT(props.usdcFeeLimit || 0));
}, [props.usdcFeeLimit]);

useEffect(() => {
setValue("uaktDeploymentLimit", uaktToAKT(props.uaktDeploymentLimit || 0));
}, [props.uaktDeploymentLimit]);

useEffect(() => {
setValue("usdcDeploymentLimit", uaktToAKT(props.usdcDeploymentLimit || 0));
}, [props.usdcDeploymentLimit]);

useEffect(() => {
if (expiration) {
setValue("expiration", format(expiration || addYears(new Date(), 1), "yyyy-MM-dd'T'HH:mm"));
}
}, [expiration]);

const execSubmitterRoleAction: SubmitHandler<FormValues> = useCallback(
async (next: FormValues, event: React.BaseSyntheticEvent<SubmitEvent>) => {
const role = event.nativeEvent.submitter?.getAttribute("data-role");
await onSubmit(role as "revoke-all" | "update", convertToUakt(next));
reset(next);
},
[onSubmit, reset]
);

return (
<div>
<Form {...form}>
<form onSubmit={handleSubmit(execSubmitterRoleAction)} noValidate>
<div className="flex">
<div className="flex-1">
<FormField
control={control}
name="uaktDeploymentLimit"
render={({ field, fieldState }) => {
return <FormInput {...field} dirty={fieldState.isDirty} type="number" label="AKT Deployments Limit, AKT" min={0} step={0.000001} />;
}}
/>
</div>

<div className="ml-3 flex-1">
<FormField
control={control}
name="uaktFeeLimit"
render={({ field, fieldState }) => {
return <FormInput {...field} dirty={fieldState.isDirty} type="number" label="AKT Fees Limit, AKT" min={0} step={0.000001} />;
}}
/>
</div>
</div>

<div className="flex">
<div className="flex-1">
<FormField
control={control}
name="usdcDeploymentLimit"
render={({ field, fieldState }) => {
return <FormInput {...field} dirty={fieldState.isDirty} type="number" label="USDC Deployments Limit, AKT" min={0} step={0.000001} />;
}}
/>
</div>

<div className="ml-3 flex-1">
<FormField
control={control}
name="usdcFeeLimit"
render={({ field, fieldState }) => {
return <FormInput {...field} dirty={fieldState.isDirty} type="number" label="USDC Fees Limit, AKT" min={0} step={0.000001} />;
}}
/>
</div>
</div>

<div className="mb-4 w-full">
<Controller
control={control}
name="expiration"
render={({ field, fieldState }) => {
return <FormInput {...field} dirty={fieldState.isDirty} type="datetime-local" label="Expiration" />;
}}
/>
</div>

<Button variant="default" size="sm" className="mr-2" data-role="update" disabled={!form.formState.isDirty}>
{hasAny ? "Update" : "Enable"}
</Button>

{hasAny && (
<Button variant="default" size="sm" data-role="revoke-all">
Disable
</Button>
)}
</form>
</Form>
</div>
);
};

function convertToUakt({ ...values }: FormValues) {
return fields.reduce((acc, field) => {
acc[field] = aktToUakt(values[field]);
return acc;
}, values);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import React, { FC, useCallback, useEffect } from "react";

import { AutoTopUpSetting, AutoTopUpSettingProps } from "@src/components/settings/AutoTopUpSetting/AutoTopUpSetting";
import { useWallet } from "@src/context/WalletProvider";
import { useAutoTopUpLimits } from "@src/hooks/useAutoTopUpLimits";
import { useAutoTopUpService } from "@src/hooks/useAutoTopUpService";
import { useDoubleTransactionAlert } from "@src/hooks/useDoubleTransactionAlert";

export const AutoTopUpSettingContainer: FC = () => {
const { address, signAndBroadcastTx } = useWallet();
const { fetch, uaktFeeLimit, usdcFeeLimit, uaktDeploymentLimit, usdcDeploymentLimit, expiration } = useAutoTopUpLimits();
const autoTopUpMessageService = useAutoTopUpService();
const doubleTransactionAlert = useDoubleTransactionAlert();

useEffect(() => {
fetch();
}, []);

const updateAllowancesAndGrants: AutoTopUpSettingProps["onSubmit"] = useCallback(
async (action, next) => {
const prev = {
uaktFeeLimit,
usdcFeeLimit,
uaktDeploymentLimit,
usdcDeploymentLimit,
expiration
};

const { revoke, grant } = autoTopUpMessageService.collectMessages({
granter: address,
prev,
next: action === "revoke-all" ? undefined : { ...next, expiration: new Date(next.expiration) }
});

const closeAlert = revoke.length && grant.length && doubleTransactionAlert.show();

if (revoke.length) {
await signAndBroadcastTx(revoke);
}

if (grant.length) {
await signAndBroadcastTx(grant);
}

if (closeAlert) {
closeAlert();
}

await fetch();
},
[
address,
autoTopUpMessageService,
doubleTransactionAlert,
expiration,
fetch,
signAndBroadcastTx,
uaktDeploymentLimit,
uaktFeeLimit,
usdcDeploymentLimit,
usdcFeeLimit
]
);

return (
<AutoTopUpSetting
onSubmit={updateAllowancesAndGrants}
uaktFeeLimit={uaktFeeLimit}
usdcFeeLimit={usdcFeeLimit}
uaktDeploymentLimit={uaktDeploymentLimit}
usdcDeploymentLimit={usdcDeploymentLimit}
expiration={expiration}
/>
);
};
6 changes: 6 additions & 0 deletions apps/deploy-web/src/components/settings/SettingsContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { Edit } from "iconoir-react";
import { useRouter } from "next/navigation";
import { NextSeo } from "next-seo";

import { AutoTopUpSetting } from "@src/components/settings/AutoTopUpSetting/AutoTopUpSetting";
import { AutoTopUpSettingContainer } from "@src/components/settings/AutoTopUpSetting/AutoTopUpSettingContainer";
import { LocalDataManager } from "@src/components/settings/LocalDataManager";
import { Fieldset } from "@src/components/shared/Fieldset";
import { LabelValue } from "@src/components/shared/LabelValue";
Expand Down Expand Up @@ -58,6 +60,10 @@ export const SettingsContainer: React.FunctionComponent = () => {
<ColorModeSelect />
<LocalDataManager />
</Fieldset>

<Fieldset label="Auto Top Up">
<AutoTopUpSettingContainer />
</Fieldset>
</div>

<Fieldset label="Certificates" className="mb-4">
Expand Down
1 change: 1 addition & 0 deletions apps/deploy-web/src/components/settings/SettingsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export const SettingsForm: React.FunctionComponent = () => {
name="apiEndpoint"
defaultValue={settings.apiEndpoint}
render={({ field }) => {
console.log("DEBUG field", field);
return <FormInput {...field} type="text" className="flex-1" />;
}}
/>
Expand Down
9 changes: 9 additions & 0 deletions apps/deploy-web/src/hooks/useAllowanceService.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useMemo } from "react";
import { AllowanceHttpService } from "@akashnetwork/http-sdk";

import { useSettings } from "@src/context/SettingsProvider";

export const useAllowanceService = () => {
const { settings } = useSettings();
return useMemo(() => new AllowanceHttpService({ baseURL: settings.apiEndpoint }), [settings.apiEndpoint]);
};
Loading

0 comments on commit bfa085f

Please sign in to comment.