Skip to content

Commit

Permalink
refactor(network): retrieves api versions and urls based on network s…
Browse files Browse the repository at this point in the history
…tore
  • Loading branch information
ygrishajev committed Sep 12, 2024
1 parent d71d815 commit 793a3ac
Show file tree
Hide file tree
Showing 27 changed files with 209 additions and 248 deletions.
5 changes: 5 additions & 0 deletions apps/deploy-web/env/.env.production
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
AUTH0_BASE_URL=https://console.akash.network
AUTH0_ISSUER_BASE_URL=https://auth.cloudmos.io

NEXT_PUBLIC_DEFAULT_NETWORK_ID=mainnet
NEXT_PUBLIC_BILLING_ENABLED=false
NEXT_PUBLIC_MANAGED_WALLET_NETWORK_ID=mainnet
NEXT_PUBLIC_MANAGED_WALLET_DENOM=usdc
Expand All @@ -15,3 +16,7 @@ NEXT_PUBLIC_BASE_API_MAINNET_URL=https://api.cloudmos.io
NEXT_PUBLIC_BASE_API_SANDBOX_URL=https://api-sandbox.cloudmos.io
NEXT_PUBLIC_BASE_API_TESTNET_URL=https://api-testnet.cloudmos.io
NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL

BASE_API_MAINNET_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL
BASE_API_TESTNET_URL=$NEXT_PUBLIC_BASE_API_TESTNET_URL
BASE_API_SANDBOX_URL=$NEXT_PUBLIC_BASE_API_SANDBOX_URL
7 changes: 6 additions & 1 deletion apps/deploy-web/env/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ AUTH0_SECRET
AUTH0_CLIENT_ID
AUTH0_CLIENT_SECRET

NEXT_PUBLIC_DEFAULT_NETWORK_ID=
NEXT_PUBLIC_BILLING_ENABLED=
NEXT_PUBLIC_MANAGED_WALLET_NETWORK_ID=
NEXT_PUBLIC_MANAGED_WALLET_DENOM=
Expand All @@ -20,4 +21,8 @@ NEXT_PUBLIC_BASE_API_TESTNET_URL=
NEXT_PUBLIC_API_BASE_URL=
NEXT_PUBLIC_SENTRY_DSN=
NEXT_PUBLIC_SENTRY_SERVER_NAME=
NEXT_PUBLIC_GA_MEASUREMENT_ID=
NEXT_PUBLIC_GA_MEASUREMENT_ID=

BASE_API_MAINNET_URL=
BASE_API_TESTNET_URL=
BASE_API_SANDBOX_URL=
7 changes: 6 additions & 1 deletion apps/deploy-web/env/.env.staging
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
AUTH0_BASE_URL=https://console-beta.akash.network
AUTH0_ISSUER_BASE_URL=https://dev-5aprb0lr.us.auth0.com

NEXT_PUBLIC_DEFAULT_NETWORK_ID=mainnet
NEXT_PUBLIC_BILLING_ENABLED=true
NEXT_PUBLIC_MANAGED_WALLET_NETWORK_ID=mainnet
NEXT_PUBLIC_MANAGED_WALLET_DENOM=usdc
Expand All @@ -13,4 +14,8 @@ NEXT_PUBLIC_NODE_ENV=$NODE_ENV
NEXT_PUBLIC_BASE_API_MAINNET_URL=https://api-mainnet-staging.cloudmos.io
NEXT_PUBLIC_BASE_API_SANDBOX_URL=https://api-sandbox-staging.cloudmos.io
NEXT_PUBLIC_BASE_API_TESTNET_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL
NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL
NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL

BASE_API_MAINNET_URL=$NEXT_PUBLIC_BASE_API_MAINNET_URL
BASE_API_TESTNET_URL=$NEXT_PUBLIC_BASE_API_TESTNET_URL
BASE_API_SANDBOX_URL=$NEXT_PUBLIC_BASE_API_SANDBOX_URL
4 changes: 2 additions & 2 deletions apps/deploy-web/src/components/new-deployment/BidGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Alert, Table, TableBody, TableCell, TableHeader, TableRow } from "@akas
import { Check } from "iconoir-react";

import { MAINNET_ID } from "@src/config/network.config";
import { useSettings } from "@src/context/SettingsProvider";
import networkStore from "@src/store/networkStore";
import { BidDto, DeploymentDto } from "@src/types/deployment";
import { ApiProviderList } from "@src/types/provider";
import { deploymentGroupResourceSum, getStorageAmount } from "@src/utils/deploymentDetailUtils";
Expand Down Expand Up @@ -46,7 +46,7 @@ export const BidGroup: React.FunctionComponent<Props> = ({
}) => {
const [resources, setResources] = useState<{ cpuAmount: number; gpuAmount: number; memoryAmount: number; storageAmount: number } | null>(null);
const fBids = bids.filter(bid => filteredBids.includes(bid.id));
const { selectedNetworkId } = useSettings();
const { id: selectedNetworkId } = networkStore.useSelectedNetwork();

useEffect(() => {
const currentGroup = deploymentDetail?.groups.find(g => g.group_id.gseq === gseq);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const CreateLease: React.FunctionComponent<Props> = ({ dseq }) => {
a[b.gseq] = [...(a[b.gseq] || []), b];
return a as { [key: number]: BidDto };
}, {} as any) || {};
const dseqList = Object.keys(groupedBids).map(g => parseInt(g));
const dseqList = Object.keys(groupedBids).map(group => parseInt(group));
const allClosed = (bids?.length || 0) > 0 && bids?.every(bid => bid.state === "closed");
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const wallet = useWallet();
Expand Down
5 changes: 4 additions & 1 deletion apps/deploy-web/src/config/env-config.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export const serverEnvSchema = browserEnvSchema.extend({
AUTH0_CLIENT_ID: z.string(),
AUTH0_CLIENT_SECRET: z.string(),
AUTH0_AUDIENCE: z.string(),
AUTH0_SCOPE: z.string()
AUTH0_SCOPE: z.string(),
BASE_API_MAINNET_URL: z.string().url(),
BASE_API_TESTNET_URL: z.string().url(),
BASE_API_SANDBOX_URL: z.string().url()
});

export type BrowserEnvConfig = z.infer<typeof browserEnvSchema>;
Expand Down
48 changes: 48 additions & 0 deletions apps/deploy-web/src/config/network.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,53 @@
import type { MainnetNetworkId, SandboxNetworkId, TestnetNetworkId } from "@akashnetwork/akashjs/build/types/network";

import { browserEnvConfig } from "@src/config/browser-env.config";
import type { Network } from "@src/types/network";

export const MAINNET_ID: MainnetNetworkId = "mainnet";
export const SANDBOX_ID: SandboxNetworkId = "sandbox";
export const TESTNET_ID: TestnetNetworkId = "testnet";

export const INITIAL_NETWORKS_CONFIG: Network[] = [
{
id: MAINNET_ID,
title: "Mainnet",
description: "Akash Network mainnet network.",
nodesUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/nodes/mainnet`,
chainId: "akashnet-2",
chainRegistryName: "akash",
versionUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/version/mainnet`,
rpcEndpoint: "https://rpc.cosmos.directory/akash",
enabled: true,
apiVersion: "v1beta3",
marketApiVersion: "v1beta4",
version: null
},
{
id: TESTNET_ID,
title: "GPU Testnet",
description: "Testnet of the new GPU features.",
nodesUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/nodes/testnet`,
chainId: "testnet-02",
chainRegistryName: "akash-testnet",
versionUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/version/testnet`,
rpcEndpoint: "https://rpc.testnet-02.aksh.pw:443",
enabled: false,
apiVersion: "v1beta3",
marketApiVersion: "v1beta3",
version: null
},
{
id: SANDBOX_ID,
title: "Sandbox",
description: "Sandbox of the mainnet version.",
nodesUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/nodes/sandbox`,
chainId: "sandbox-01",
chainRegistryName: "akash-sandbox",
versionUrl: `${browserEnvConfig.NEXT_PUBLIC_API_BASE_URL}/v1/version/sandbox`,
rpcEndpoint: "https://rpc.sandbox-01.aksh.pw:443",
version: null,
enabled: true,
apiVersion: "v1beta3",
marketApiVersion: "v1beta4"
}
];
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import axios from "axios";
import { event } from "nextjs-google-analytics";
import { useSnackbar } from "notistack";

import { networkService } from "@src/services/network/network.service";
import networkStore from "@src/store/networkStore";
import { RestApiCertificatesResponseType } from "@src/types/certificate";
import { AnalyticsEvents } from "@src/utils/analytics";
import { TransactionMessageData } from "@src/utils/TransactionMessageData";
Expand Down Expand Up @@ -73,14 +73,15 @@ export const CertificateProvider = ({ children }) => {
const { enqueueSnackbar } = useSnackbar();
const { address, signAndBroadcastTx } = useWallet();
const { apiEndpoint } = settings;
const selectedNetwork = networkStore.useSelectedNetwork();

const loadValidCertificates = useCallback(
async (showSnackbar?: boolean) => {
setIsLoadingCertificates(true);

try {
const response = await axios.get<RestApiCertificatesResponseType>(
`${apiEndpoint}/akash/cert/${networkService.networkVersion}/certificates/list?filter.state=valid&filter.owner=${address}`
`${apiEndpoint}/akash/cert/${selectedNetwork.apiVersion}/certificates/list?filter.state=valid&filter.owner=${address}`
);
const certs = (response.data.certificates || []).map(cert => {
const parsed = atob(cert.certificate.cert);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
"use client";
import React, { FC, ReactNode, useCallback, useEffect, useState } from "react";
import type { NetworkId } from "@akashnetwork/akashjs/build/types/network";
import React, { useCallback, useEffect, useState } from "react";
import axios from "axios";

import { browserEnvConfig } from "@src/config/browser-env.config";
import { useLocalStorage } from "@src/hooks/useLocalStorage";
import { usePreviousRoute } from "@src/hooks/usePreviousRoute";
import { queryClient } from "@src/queries";
import { initiateNetworkData, networks } from "@src/store/networkStore";
import networkStore, { initiateNetworkVersions } from "@src/store/networkStore";
import type { FCWithChildren } from "@src/types/component";
import { NodeStatus } from "@src/types/node";
import { mainnetNodes } from "@src/utils/apiUtils";
import { initAppTypes } from "@src/utils/init";
import { migrateLocalStorage } from "@src/utils/localStorage";

Expand Down Expand Up @@ -38,8 +36,6 @@ type ContextType = {
isSettingsInit: boolean;
refreshNodeStatuses: (settingsOverride?: Settings) => Promise<void>;
isRefreshingNodeStatus: boolean;
selectedNetworkId: string;
setSelectedNetworkId: (value: React.SetStateAction<string>) => void;
};

const SettingsProviderContext = React.createContext<ContextType>({} as ContextType);
Expand All @@ -53,14 +49,14 @@ const defaultSettings: Settings = {
customNode: null
};

export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
export const SettingsProvider: FCWithChildren = ({ children }) => {
const [settings, setSettings] = useState<Settings>(defaultSettings);
const [isLoadingSettings, setIsLoadingSettings] = useState(true);
const [isSettingsInit, setIsSettingsInit] = useState(false);
const [isRefreshingNodeStatus, setIsRefreshingNodeStatus] = useState(false);
const { getLocalStorageItem, setLocalStorageItem } = useLocalStorage();
const [selectedNetworkId, setSelectedNetworkId] = useState<NetworkId>(browserEnvConfig.NEXT_PUBLIC_DEFAULT_NETWORK_ID);
const { isCustomNode, customNode, nodes, apiEndpoint, rpcEndpoint } = settings;
const selectedNetwork = networkStore.useSelectedNetwork();

usePreviousRoute();

Expand All @@ -69,27 +65,19 @@ export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
const initiateSettings = async () => {
setIsLoadingSettings(true);

// Set the versions and metadata of available networks
await initiateNetworkData();
await initiateNetworkVersions();

// Apply local storage migrations
migrateLocalStorage();

// Init app types based on the selected network id
initAppTypes();

const _selectedNetworkId = (localStorage.getItem("selectedNetworkId") as NetworkId | null) || browserEnvConfig.NEXT_PUBLIC_DEFAULT_NETWORK_ID;

setSelectedNetworkId(_selectedNetworkId);

const settingsStr = getLocalStorageItem("settings");
const settings = { ...defaultSettings, ...JSON.parse(settingsStr || "{}") } as Settings;

// Set the available nodes list and default endpoints
const currentNetwork = networks.find(x => x.id === _selectedNetworkId);
const response = await axios.get(currentNetwork?.nodesUrl || mainnetNodes);
const nodes = response.data as Array<{ id: string; api: string; rpc: string }>;
const mappedNodes: Array<BlockchainNode> = await Promise.all(
const { data: nodes } = await axios.get<Array<{ id: string; api: string; rpc: string }>>(selectedNetwork.nodesUrl);
const nodesWithStatuses: Array<BlockchainNode> = await Promise.all(
nodes.map(async node => {
const nodeStatus = await loadNodeStatus(node.rpc);

Expand All @@ -98,7 +86,7 @@ export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
status: nodeStatus.status,
latency: nodeStatus.latency,
nodeInfo: nodeStatus.nodeInfo
} as BlockchainNode;
};
})
);

Expand All @@ -120,12 +108,12 @@ export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
id: customNodeUrl.hostname
};

updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, customNode, nodes: mappedNodes });
updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, customNode, nodes: nodesWithStatuses });
}

// If the user has no settings or the selected node is inactive, use the fastest available active node
if (!hasSettings || (hasSettings && settings.selectedNode?.status === "inactive")) {
const randomNode = getFastestNode(mappedNodes);
const randomNode = getFastestNode(nodesWithStatuses);
// Use cosmos.directory as a backup if there's no active nodes in the list
defaultApiNode = randomNode?.api || "https://rest.cosmos.directory/akash";
defaultRpcNode = randomNode?.rpc || "https://rpc.cosmos.directory/akash";
Expand All @@ -137,12 +125,12 @@ export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
nodeInfo: null,
id: "https://rest.cosmos.directory/akash"
};
updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, nodes: mappedNodes });
updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, nodes: nodesWithStatuses });
} else {
defaultApiNode = settings.apiEndpoint;
defaultRpcNode = settings.rpcEndpoint;
selectedNode = settings.selectedNode;
updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, nodes: mappedNodes });
updateSettings({ ...settings, apiEndpoint: defaultApiNode, rpcEndpoint: defaultRpcNode, selectedNode, nodes: nodesWithStatuses });
}

setIsLoadingSettings(false);
Expand Down Expand Up @@ -297,8 +285,6 @@ export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
isLoadingSettings,
refreshNodeStatuses,
isRefreshingNodeStatus,
selectedNetworkId,
setSelectedNetworkId,
isSettingsInit
}}
>
Expand Down
13 changes: 5 additions & 8 deletions apps/deploy-web/src/hooks/useLocalStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,22 @@ import { useEffect, useState } from "react";
import { useEventListener } from "usehooks-ts";

import { useWallet } from "@src/context/WalletProvider";
import networkStore from "@src/store/networkStore";

export const useLocalStorage = () => {
const { address } = useWallet();
const selectedNetwork = networkStore.useSelectedNetwork();

const getLocalStorageItem = (key: string) => {
const selectedNetworkId = localStorage.getItem("selectedNetworkId");

return localStorage.getItem(`${selectedNetworkId}${address ? "/" + address : ""}/${key}`);
return localStorage.getItem(`${selectedNetwork.id}${address ? "/" + address : ""}/${key}`);
};

const setLocalStorageItem = (key: string, value: string) => {
const selectedNetworkId = localStorage.getItem("selectedNetworkId");

localStorage.setItem(`${selectedNetworkId}${address ? "/" + address : ""}/${key}`, value);
localStorage.setItem(`${selectedNetwork.id}${address ? "/" + address : ""}/${key}`, value);
};

const removeLocalStorageItem = (key: string) => {
const selectedNetworkId = localStorage.getItem("selectedNetworkId");
localStorage.removeItem(`${selectedNetworkId}${address ? "/" + address : ""}/${key}`);
localStorage.removeItem(`${selectedNetwork.id}${address ? "/" + address : ""}/${key}`);
};

return {
Expand Down
2 changes: 1 addition & 1 deletion apps/deploy-web/src/pages/api/auth/[...auth0].ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default handleAuth({
}

const userSettings = await axios.post(
`${serverEnvConfig.NEXT_PUBLIC_BASE_API_MAINNET_URL}/user/tokenInfo`,
`${serverEnvConfig.BASE_API_MAINNET_URL}/user/tokenInfo`,
{
wantedUsername: session.user.nickname,
email: session.user.email,
Expand Down
2 changes: 1 addition & 1 deletion apps/deploy-web/src/pages/api/proxy/[...path].ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default async (req, res) => {

const proxy = httpProxy.createProxyServer({
changeOrigin: true,
target: serverEnvConfig.NEXT_PUBLIC_BASE_API_MAINNET_URL,
target: serverEnvConfig.BASE_API_MAINNET_URL,
secure: false,
autoRewrite: false
});
Expand Down
3 changes: 2 additions & 1 deletion apps/deploy-web/src/pages/providers/[owner]/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { NetworkId } from "@akashnetwork/akashjs/build/types/network";
import axios from "axios";

import { ProviderDetail } from "@src/components/providers/ProviderDetail";
Expand All @@ -16,7 +17,7 @@ const ProviderDetailPage: React.FunctionComponent<Props> = ({ owner, _provider }
export default ProviderDetailPage;

export async function getServerSideProps({ params, query }) {
const apiUrl = serverApiUrlService.getBaseApiUrlFor(query.network as string);
const apiUrl = serverApiUrlService.getBaseApiUrlFor(query.network as NetworkId);
const response = await axios.get(`${apiUrl}/v1/providers/${params?.owner}`);

return {
Expand Down
2 changes: 1 addition & 1 deletion apps/deploy-web/src/pages/template/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const getServerSideProps = async function getServerSideProps({ params, re
};
}

const response = await axios.get(`${serverEnvConfig.NEXT_PUBLIC_BASE_API_MAINNET_URL}/user/template/${params?.id}`, config);
const response = await axios.get(`${serverEnvConfig.BASE_API_MAINNET_URL}/user/template/${params?.id}`, config);

return {
props: {
Expand Down
2 changes: 1 addition & 1 deletion apps/deploy-web/src/pages/templates/[templateId]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const TemplateDetailPage: React.FunctionComponent<Props> = ({ templateId, templa
export default TemplateDetailPage;

export async function getServerSideProps({ params }) {
const response = await axios.get(`${serverEnvConfig.NEXT_PUBLIC_BASE_API_MAINNET_URL}/templates`);
const response = await axios.get(`${serverEnvConfig.BASE_API_MAINNET_URL}/templates`);
const categories = response.data.filter(x => (x.templates || []).length > 0);
categories.forEach(c => {
c.templates.forEach(t => (t.category = c.title));
Expand Down
Loading

0 comments on commit 793a3ac

Please sign in to comment.