Skip to content

Commit

Permalink
Refactor/cleanup deprecated code (#2)
Browse files Browse the repository at this point in the history
* Remove deprecated code

* Remove more deprecated code

* Improve typings

* Add env var for Rest Api url in api

* Fix bug created in earlier commit

* Add typing and show 404 if deployment is not found

* Fixes
  • Loading branch information
Redm4x authored Aug 31, 2023
1 parent d445527 commit aaf0781
Show file tree
Hide file tree
Showing 73 changed files with 319 additions and 1,164 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The database schemas is defined using [sequelize-typescript](https://github.com/

- **base** - Tables which are cosmos generic and are used for every chains
- **akash** - Tables which are akash specific (they are not created when initializing a database for another chain)
- **user** - Tables which are user specific. Contains tables for user settings, templates and alerts (BlockSpy specific)
- **user** - Tables which are user specific. Contains tables for user settings and templates

## Block
|Column|Type|Note|
Expand Down Expand Up @@ -394,4 +394,3 @@ Created when a user "favorite" a template
|youtubeUsername|varchar
|twitterUsername|varchar
|githubUsername|varchar
|accountType|varchar|`CLOUDMOS` or `BLOCKSPY`
5 changes: 4 additions & 1 deletion api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,16 @@ When running the api locally the following environment variables can be set in a

|Name|Value|Note|
|-|-|-
Network|`mainnet` or `testnet`|Specify if the api should be in mainnet or testnet mode. Default: `mainnet`.
RestApiNodeUrl|ex: `"https://api.akashnet.net"`|Rest api to use. Will default to `"https://rest.cosmos.directory/akash"` for mainnet and `"https://api.testnet-02.aksh.pw:443"` for testnet.
HealthchecksEnabled|`true` or `false`|Specify if the [Scheduler](./src/index.ts#L42) should send health check pings.
SentryDSN|ex: `"https://[email protected]/1234"`|[Sentry DSN](https://docs.sentry.io/product/sentry-basics/dsn-explainer/) used when [initializing](./src/index.ts#L29) Sentry
AkashDatabaseCS|ex: `postgres://user:password@localhost:5432/cloudmos-akash`|Akash Database Connection String
AkashTestnetDatabaseCS|ex: `postgres://user:password@localhost:5432/cloudmos-akash-testnet`|Akash Testnet Database Connection String
UserDatabaseCS|ex: `postgres://user:password@localhost:5432/cloudmos-users`|User Database Connection String
Auth0JWKSUri|ex: `'https://1a2b3c.us.auth0.com/.well-known/jwks.json'`|
Auth0Audience|ex: `'https://api.cloudmos.io'`
Auth0Issuer|ex: `'https://dev-5aprb0lr.us.auth0.com/'`
Auth0Issuer|ex: `'https://auth.cloudmos.io/'`
StripeSecretKey|ex: `sk_test_12aw315wdawd3...293d12d32df8jf`
WebsiteUrl|`http://localhost:3001`
WebsiteUrl|`http://localhost:3001`
6 changes: 4 additions & 2 deletions api/src/providers/apiNodeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import { Validator } from "@shared/dbSchemas/base";
import { Op } from "sequelize";
import { Provider, ProviderAttribute } from "@shared/dbSchemas/akash";
import { cacheKeys, cacheResponse } from "@src/caching/helpers";
import { env } from "@src/shared/utils/env";

const apiNodeUrl = process.env.Network === "testnet" ? "https://api.testnet-02.aksh.pw:443" : "https://rest.cosmos.directory/akash";
const betaTypeVersion = process.env.Network === "testnet" ? "v1beta3" : "v1beta2";
const defaultNodeUrl = env.Network === "testnet" ? "https://api.testnet-02.aksh.pw:443" : "https://rest.cosmos.directory/akash";
const apiNodeUrl = env.RestApiNodeUrl ?? defaultNodeUrl;
const betaTypeVersion = env.Network === "testnet" ? "v1beta3" : "v1beta2";

export async function getChainStats() {
const result: { communityPool: number; inflation: number; communityTax: number; bondedTokens: number; totalSupply: number } = await cacheResponse(
Expand Down
15 changes: 3 additions & 12 deletions api/src/providers/userDataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function randomIntFromInterval(min: number, max: number) {
}

export async function checkUsernameAvailable(username: string, dbTransaction?: Transaction): Promise<boolean> {
const existingUser = await UserSetting.findOne({ where: { username: username, accountType: "cloudmos" }, transaction: dbTransaction });
const existingUser = await UserSetting.findOne({ where: { username: username }, transaction: dbTransaction });
return !existingUser;
}

Expand Down Expand Up @@ -60,14 +60,7 @@ export async function updateSettings(
await settings.save();
}

export async function getSettingsOrInit(
userId: string,
wantedUsername: string,
email: string,
emailVerified: boolean,
subscribedToNewsletter: boolean,
accountType: string = "cloudmos"
) {
export async function getSettingsOrInit(userId: string, wantedUsername: string, email: string, emailVerified: boolean, subscribedToNewsletter: boolean) {
let [userSettings, created] = await UserSetting.findCreateFind({
where: { userId: userId },
defaults: {
Expand All @@ -76,8 +69,7 @@ export async function getSettingsOrInit(
email: email,
emailVerified: emailVerified,
stripeCustomerId: null,
subscribedToNewsletter: subscribedToNewsletter,
accountType: accountType
subscribedToNewsletter: subscribedToNewsletter
}
});

Expand All @@ -86,7 +78,6 @@ export async function getSettingsOrInit(
} else if (userSettings.email !== email || userSettings.emailVerified !== emailVerified) {
userSettings.email = email;
userSettings.emailVerified = emailVerified;
userSettings.accountType = accountType;
await userSettings.save();
}

Expand Down
2 changes: 1 addition & 1 deletion api/src/routers/dashboardRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ dashboardRouter.use(privateMiddleware);
dashboardRouter.get(
"/stats",
asyncHandler(async (req, res) => {
const userCountRequest = UserSetting.count({ where: { accountType: "cloudmos" } });
const userCountRequest = UserSetting.count();
const publicTemplateCountRequest = Template.count({
where: { isPublic: true }
});
Expand Down
4 changes: 2 additions & 2 deletions api/src/routers/userRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,9 @@ userRouter.post(
express.json(),
asyncHandler(async (req: JWTRequest, res) => {
const userId = req.auth?.sub;
const { wantedUsername, email, emailVerified, subscribedToNewsletter, accountType } = req.body;
const { wantedUsername, email, emailVerified, subscribedToNewsletter } = req.body;

const settings = await getSettingsOrInit(userId, wantedUsername, email, !!emailVerified, subscribedToNewsletter, accountType);
const settings = await getSettingsOrInit(userId, wantedUsername, email, !!emailVerified, subscribedToNewsletter);

res.send(settings);
})
Expand Down
1 change: 1 addition & 0 deletions api/src/shared/utils/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const env = {
AkashTestnetDatabaseCS: process.env.AkashTestnetDatabaseCS,
UserDatabaseCS: process.env.UserDatabaseCS,
Network: process.env.Network ?? "mainnet",
RestApiNodeUrl: process.env.RestApiNodeUrl,
AkashlyticsGithubPAT: process.env.AkashlyticsGithubPAT,
Auth0JWKSUri: process.env.Auth0JWKSUri,
Auth0Audience: process.env.Auth0Audience,
Expand Down
13 changes: 13 additions & 0 deletions deploy-web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deploy-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
"@types/file-saver": "^2.0.5",
"@types/js-yaml": "^4.0.5",
"@types/json2csv": "^5.0.3",
"@types/lodash": "^4.14.197",
"@types/node": "^12.12.21",
"@types/nprogress": "^0.2.0",
"@types/react": "^17.0.2",
Expand Down
21 changes: 3 additions & 18 deletions deploy-web/src/components/deployment/DeploymentListRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { useAllLeases } from "@src/queries/useLeaseQuery";
import { makeStyles } from "tss-react/mui";
import { useRouter } from "next/router";
import { getAvgCostPerMonth, getTimeLeft, useRealTimeLeft } from "@src/utils/priceUtils";
import { Box, Checkbox, CircularProgress, darken, IconButton, Menu, TableCell, Tooltip, Typography, useMediaQuery, useTheme } from "@mui/material";
import { Box, Checkbox, CircularProgress, darken, IconButton, Menu, TableCell, Tooltip, Typography } from "@mui/material";
import { UrlService } from "@src/utils/urlUtils";
import { cx } from "@emotion/css";
import { CustomMenuItem } from "../shared/CustomMenuItem";
Expand Down Expand Up @@ -112,7 +112,7 @@ export const DeploymentListRow: React.FunctionComponent<Props> = ({ deployment,
const hasActiveLeases = hasLeases && filteredLeases.some(l => l.state === "active");
const deploymentCost = hasLeases ? filteredLeases.reduce((prev, current) => prev + parseFloat(current.price.amount), 0) : 0;
const timeLeft = getTimeLeft(deploymentCost, deployment.escrowBalance);
const realTimeLeft = useRealTimeLeft(deploymentCost, deployment.escrowBalance, deployment.escrowAccount.settled_at, deployment.createdAt);
const realTimeLeft = useRealTimeLeft(deploymentCost, deployment.escrowBalance, parseFloat(deployment.escrowAccount.settled_at), deployment.createdAt);
const deploymentName = deployment.name ? (
<>
<Typography variant="body2" className="text-truncate" title={deployment.name}>
Expand All @@ -125,9 +125,8 @@ export const DeploymentListRow: React.FunctionComponent<Props> = ({ deployment,
);
const showWarning = differenceInCalendarDays(timeLeft, new Date()) < 7;
const escrowBalance = isActive && hasActiveLeases ? realTimeLeft?.escrow : deployment.escrowBalance;
const amountSpent = isActive && hasActiveLeases ? realTimeLeft?.amountSpent : deployment.transferred.amount;
const amountSpent = isActive && hasActiveLeases ? realTimeLeft?.amountSpent : parseFloat(deployment.transferred.amount);
const isValidTimeLeft = isActive && hasActiveLeases && isValid(realTimeLeft?.timeLeft);
const theme = useTheme();
const avgCost = udenomToDenom(getAvgCostPerMonth(deploymentCost));
const storageDeploymentData = getDeploymentData(deployment?.dseq);
const denomData = useDenomData(deployment.escrowAccount.balance.denom);
Expand Down Expand Up @@ -197,19 +196,6 @@ export const DeploymentListRow: React.FunctionComponent<Props> = ({ deployment,
router.push(url);
};

// TODO Alerts
// const onSetAlert = () => {
// window.open(
// UrlService.alertsCreate(null, "akash", "deployment-balance-monitor", {
// owner: { operator: "eq", value: address },
// dseq: { operator: "eq", value: deployment.dseq }
// }),
// "_ blank"
// );

// handleMenuClose();
// };

return (
<>
<CustomTableRow className={classes.root} onClick={() => viewDeployment()}>
Expand Down Expand Up @@ -348,7 +334,6 @@ export const DeploymentListRow: React.FunctionComponent<Props> = ({ deployment,
{isActive && <CustomMenuItem onClick={() => setIsDepositingDeployment(true)} icon={<AddIcon fontSize="small" />} text="Add funds" />}
<CustomMenuItem onClick={() => changeDeploymentName(deployment.dseq)} icon={<EditIcon fontSize="small" />} text="Edit name" />
{storageDeploymentData?.manifest && <CustomMenuItem onClick={() => redeploy()} icon={<PublishIcon fontSize="small" />} text="Redeploy" />}
{/* {isActive && <CustomMenuItem onClick={() => onSetAlert()} icon={<AddAlertIcon fontSize="small" />} text="Balance Alert" />} */}
{isActive && <CustomMenuItem onClick={() => onCloseDeployment()} icon={<CancelPresentationIcon fontSize="small" />} text="Close" />}
</Menu>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,19 +126,6 @@ export const DeploymentDetailTopBar: React.FunctionComponent<Props> = ({ address
}
};

// TODO Alerts
// const onSetAlert = () => {
// window.open(
// UrlService.alertsCreate(null, "akash", "deployment-balance-monitor", {
// owner: { operator: "eq", value: address },
// dseq: { operator: "eq", value: deployment.dseq }
// }),
// "_blank"
// );

// handleMenuClose();
// };

return (
<>
<Box
Expand Down Expand Up @@ -188,7 +175,6 @@ export const DeploymentDetailTopBar: React.FunctionComponent<Props> = ({ address
>
<CustomMenuItem onClick={() => onChangeName()} icon={<EditIcon fontSize="small" />} text="Edit Name" />
{storageDeploymentData?.manifest && <CustomMenuItem onClick={() => redeploy()} icon={<PublishIcon fontSize="small" />} text="Redeploy" />}
{/* {isActive && <CustomMenuItem onClick={() => onSetAlert()} icon={<AddAlertIcon fontSize="small" />} text="Balance Alert" />} */}
<CustomMenuItem onClick={() => onCloseDeployment()} icon={<CancelPresentationIcon fontSize="small" />} text="Close" />
</Menu>
</Box>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useCertificate } from "../../context/CertificateProvider";
// import { ShellDownloadModal } from "./ShellDownloadModal";
import { LeaseSelect } from "./LeaseSelect";
import { useLeaseStatus } from "@src/queries/useLeaseQuery";
import { Alert, Box, Button, CircularProgress } from "@mui/material";
import ViewPanel from "../shared/ViewPanel";
import { ServiceSelect } from "./ServiceSelect";
import { ShellDownloadModal } from "./ShellDownloadModal";
import useWebSocket from "react-use-websocket";
import { PROVIDER_PROXY_URL_WS } from "@src/utils/constants";
import { XTermRefType } from "@src/lib/XTerm/XTerm";
import { XTerm } from "@src/lib/XTerm";
import { LeaseShellCode } from "@src/types/shell";
import { useAkashProviders } from "@src/context/AkashProvider";
import { useCustomWebSocket } from "@src/hooks/useCustomWebSocket";
import { LeaseDto } from "@src/types/deployment";

type Props = {
leases: Array<any>; // Type
leases: LeaseDto[];
};

export const DeploymentLeaseShell: React.FunctionComponent<Props> = ({ leases }) => {
Expand All @@ -26,7 +25,7 @@ export const DeploymentLeaseShell: React.FunctionComponent<Props> = ({ leases })
const [isConnectionClosed, setIsConnectionClosed] = useState(false);
const [services, setServices] = useState([]);
const [selectedService, setSelectedService] = useState(null);
const [selectedLease, setSelectedLease] = useState(null);
const [selectedLease, setSelectedLease] = useState<LeaseDto>(null);
const [isShowingDownloadModal, setIsShowingDownloadModal] = useState(false);
const [isChangingSocket, setIsChangingSocket] = useState(false);
const { providers } = useAkashProviders();
Expand All @@ -36,7 +35,7 @@ export const DeploymentLeaseShell: React.FunctionComponent<Props> = ({ leases })
data: leaseStatus,
refetch: getLeaseStatus,
isFetching: isLoadingStatus
} = useLeaseStatus(providerInfo?.host_uri, selectedLease || {}, {
} = useLeaseStatus(providerInfo?.host_uri, selectedLease, {
enabled: false
});
const currentUrl = useRef(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const DeploymentSubHeader: React.FunctionComponent<Props> = ({ deployment
const { classes } = useStyles();
const hasLeases = leases && leases.length > 0;
const deploymentCost = hasLeases ? leases.reduce((prev, current) => prev + parseFloat(current.price.amount), 0) : 0;
const realTimeLeft = useRealTimeLeft(deploymentCost, deployment.escrowBalance, deployment.escrowAccount.settled_at, deployment.createdAt);
const realTimeLeft = useRealTimeLeft(deploymentCost, deployment.escrowBalance, parseFloat(deployment.escrowAccount.settled_at), deployment.createdAt);
const avgCost = uaktToAKT(getAvgCostPerMonth(deploymentCost));
const isActive = deployment.state === "active";
const hasActiveLeases = hasLeases && leases.some(l => l.state === "active");
Expand Down Expand Up @@ -99,12 +99,12 @@ export const DeploymentSubHeader: React.FunctionComponent<Props> = ({ deployment
<Box sx={{ display: "flex", alignItems: "center" }}>
<PriceValue
denom={deployment.escrowAccount.balance.denom}
value={uaktToAKT(isActive && hasActiveLeases ? realTimeLeft?.amountSpent : deployment.transferred.amount, 6)}
value={uaktToAKT(isActive && hasActiveLeases ? realTimeLeft?.amountSpent : parseFloat(deployment.transferred.amount), 6)}
/>

<CustomTooltip
arrow
title={<span>{uaktToAKT(isActive && hasActiveLeases ? realTimeLeft?.amountSpent : deployment.transferred.amount, 6)} AKT</span>}
title={<span>{uaktToAKT(isActive && hasActiveLeases ? realTimeLeft?.amountSpent : parseFloat(deployment.transferred.amount), 6)} AKT</span>}
>
<InfoIcon fontSize="small" color="disabled" sx={{ marginLeft: ".5rem" }} />
</CustomTooltip>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ import { event } from "nextjs-google-analytics";
import { AnalyticsEvents } from "@src/utils/analytics";
import { useAkashProviders } from "@src/context/AkashProvider";
import { CustomTooltip } from "../shared/CustomTooltip";

const yaml = require("js-yaml");
import yaml from "js-yaml";

export const useStyles = makeStyles()(theme => ({
title: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,12 @@ export const ManifestEdit: React.FunctionComponent<Props> = ({ editedManifest, s
setIsDepositingDeployment(true);
};

const onDeploymentDeposit = async (deposit, depositorAddress) => {
const onDeploymentDeposit = async (deposit: number, depositorAddress: string) => {
setIsDepositingDeployment(false);
await handleCreateClick(deposit, depositorAddress);
};

async function handleCreateClick(deposit, depositorAddress) {
async function handleCreateClick(deposit: number, depositorAddress: string) {
setIsCreatingDeployment(true);
const dd = await createAndValidateDeploymentData(editedManifest, null, deposit, depositorAddress);

Expand All @@ -170,7 +170,8 @@ export const ManifestEdit: React.FunctionComponent<Props> = ({ editedManifest, s
try {
const messages = [];
const hasValidCert = isCertificateValidated && isLocalCertificateValidated;
let _crtpem, _encryptedKey;
let _crtpem: string;
let _encryptedKey: string;

// Create a cert if the user doesn't have one
if (!hasValidCert) {
Expand Down
2 changes: 1 addition & 1 deletion deploy-web/src/components/providers/LeaseRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const MemoLeaseRow: React.FunctionComponent<Props> = ({ lease }) => {
</TableCell>
<TableCell>
<div className={classes.flexCenter}>
<PricePerMonth denom={lease.price.denom} perBlockValue={uaktToAKT(lease.price.amount, 6)} />
<PricePerMonth denom={lease.price.denom} perBlockValue={uaktToAKT(parseFloat(lease.price.amount), 6)} />
<PriceEstimateTooltip denom={lease.price.denom} value={lease.price.amount} />
</div>
</TableCell>
Expand Down
4 changes: 2 additions & 2 deletions deploy-web/src/components/shared/CodeSnippet.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { lighten, Box, IconButton, darken } from "@mui/material";
import { lighten, Box, IconButton } from "@mui/material";
import FileCopyIcon from "@mui/icons-material/FileCopy";
import { useSnackbar } from "notistack";
import { useRef } from "react";
Expand Down Expand Up @@ -30,7 +30,7 @@ const useStyles = makeStyles()(theme => ({
export const CodeSnippet = ({ code }) => {
const { classes } = useStyles();
const { enqueueSnackbar } = useSnackbar();
const codeRef = useRef();
const codeRef = useRef<HTMLElement>();

const onCopyClick = () => {
copyTextToClipboard(code);
Expand Down
Loading

0 comments on commit aaf0781

Please sign in to comment.