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

Dynamic client side envs 2 #80

Merged
merged 15 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PENUMBRA_GRPC_ENDPOINT=
PENUMBRA_INDEXER_ENDPOINT=
PENUMBRA_INDEXER_CA_CERT=
PENUMBRA_CHAIN_ID=
PENUMBRA_CUILOA_URL=
5 changes: 3 additions & 2 deletions src/components/copiedTx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import React, { FC, useState } from "react";
import { CopyIcon } from "@radix-ui/react-icons";
import { HStack } from "@chakra-ui/react";
import { Constants } from "@/utils/configConstants.ts";
import { useEnvContext } from '@/utils/env/context';

interface CopyTxToClipboardProps {
txHash: string;
Expand All @@ -14,6 +14,7 @@ const CopyTxToClipboard: FC<CopyTxToClipboardProps> = ({
txHash,
clipboardPopupText,
}) => {
const envs = useEnvContext();
const [isCopied, setIsCopied] = useState(false);

const handleCopy = () => {
Expand All @@ -26,7 +27,7 @@ const CopyTxToClipboard: FC<CopyTxToClipboardProps> = ({
return (
<HStack align={"center"} spacing={".5em"}>
<a
href={`${Constants.cuiloaUrl}/transaction/${txHash}`}
href={`${envs.PENUMBRA_CUILOA_URL}/transaction/${txHash}`}
target="_blank"
rel="noreferrer"
style={{
Expand Down
3 changes: 2 additions & 1 deletion src/components/liquidityPositions/currentStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from "@penumbra-zone/protobuf/penumbra/core/component/dex/v1/dex_pb";
import { fromBaseUnit } from "../../utils/math/hiLo";
import { uint8ArrayToBase64 } from "../../utils/math/base64";
import { fetchTokenAsset } from "../../utils/token/tokenFetch";
import { useFetchTokenAsset } from "../../utils/token/tokenFetch";
import BigNumber from "bignumber.js";
import { CopyIcon } from "@radix-ui/react-icons";
import { Token } from "@/utils/types/token";
Expand All @@ -21,6 +21,7 @@ interface CurrentLPStatusProps {
const CurrentLPStatus = ({ nftId, position }: CurrentLPStatusProps) => {
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isCopied, setIsCopied] = useState<boolean>(false);
const fetchTokenAsset = useFetchTokenAsset();

const handleCopy = () => {
navigator.clipboard.writeText(nftId).then(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/components/lpAssetView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
LiquidityPositionEvent,
PositionExecutionEvent,
} from "@/utils/indexer/types/lps";
import { fetchTokenAsset } from "@/utils/token/tokenFetch";
import { useFetchTokenAsset } from "@/utils/token/tokenFetch";
import { fromBaseUnit } from "@/utils/math/hiLo";
import { base64ToUint8Array } from "@/utils/math/base64";
import { Token } from "@/utils/types/token";
Expand Down Expand Up @@ -37,6 +37,7 @@ const LPAssetView: FC<LPAssetViewProps> = ({ sectionTitle, lp_event }) => {
const [isLoading, setIsLoading] = useState<boolean>(true);
const [reserves1, setReserves1] = useState<number>(0);
const [reserves2, setReserves2] = useState<number>(0);
const fetchTokenAsset = useFetchTokenAsset();

useEffect(() => {
// Function to fetch tokens asynchronously
Expand Down
6 changes: 3 additions & 3 deletions src/components/pairSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { Box, Text, Flex } from '@chakra-ui/react';
import { fetchAllTokenAssets } from '@/utils/token/tokenFetch';
import { useTokenAssets } from '@/utils/token/tokenFetch';
import OutsideClickHandler from 'react-outside-click-handler';
import { Token } from '@/utils/types/token';

Expand All @@ -15,13 +15,13 @@
setShow: (show: boolean) => void;
onSelect: (assets: [Token, Token]) => void;
}) {
const tokenAssetsList = useTokenAssets();
const [tokenAssets, setTokenAssets] = useState<Record<string, Token>>({});
const [selectedAssets, setSelectedAssets] = useState<Token[]>([]);

useEffect(() => {
const tokenAssets = fetchAllTokenAssets();
setTokenAssets(Object.fromEntries(tokenAssets.map(asset => [asset.symbol, asset])));
setTokenAssets(Object.fromEntries(tokenAssetsList.map(asset => [asset.symbol, asset])));
}, []);

Check failure on line 24 in src/components/pairSelector.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'tokenAssetsList'. Either include it or remove the dependency array

useEffect(() => {
setSelectedAssets([]);
Expand Down
4 changes: 2 additions & 2 deletions src/components/swaps/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
SwapExecution,
SwapExecution_Trace,
} from "@penumbra-zone/protobuf/penumbra/core/component/dex/v1/dex_pb";
import { fetchAllTokenAssets } from "@/utils/token/tokenFetch";
import { useTokenAssets } from "@/utils/token/tokenFetch";
import { Token } from "@/utils/types/token";
import { LoadingSpinner } from "@/components/util/loadingSpinner";

Expand All @@ -26,6 +26,7 @@ export default function Swaps() {
Record<string, Token>
>({});
const [isLoading, setIsLoading] = useState(true);
const tokenAssets = useTokenAssets();

useEffect(() => {
const fetchData = async () => {
Expand Down Expand Up @@ -72,7 +73,6 @@ export default function Swaps() {

setSwapExecutions(swaps as SwapExecution[]);

const tokenAssets = fetchAllTokenAssets();
const metadataByAssetId: Record<string, Token> = {};
tokenAssets.forEach((asset) => {
metadataByAssetId[asset.inner] = {
Expand Down
9 changes: 6 additions & 3 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Analytics } from "@vercel/analytics/react"
import { inject } from '@vercel/analytics';
import { SpeedInsights } from "@vercel/speed-insights/next"
import { injectSpeedInsights } from '@vercel/speed-insights';
import { EnvContext } from '@/utils/env/context';

function app({ Component, pageProps }: AppProps) {
// Inject the analytics script
Expand All @@ -31,9 +32,11 @@ function app({ Component, pageProps }: AppProps) {
});
return (
<ChakraProvider theme={theme}>
<Analytics />
<SpeedInsights />
<Component {...pageProps} />
<EnvContext.Provider value={pageProps.envs}>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Meant as a placeholder until we have finalized a state manager.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We we anticipate this env context vars to be critical to a number of things in client side code, we should use react-query to fetch and sync its state with a mobx EnvContextStore.

<Analytics />
<SpeedInsights />
<Component {...pageProps} />
</EnvContext.Provider>
</ChakraProvider>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/lp/positionsByPrice/[...params].ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default async function positionsByPriceHandler(
}

// Get token 1 & 2
const tokenAssets = fetchAllTokenAssets();
const tokenAssets = fetchAllTokenAssets(process.env.PENUMBRA_CHAIN_ID);
const asset1Token = tokenAssets.find(
(x) => x.display.toLocaleLowerCase() === token1.toLocaleLowerCase()
);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/ohlc/[...params].ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default async function candleStickData(
const limit = params[3] || null;

try {
const tokenAssets = fetchAllTokenAssets();
const tokenAssets = fetchAllTokenAssets(process.env.PENUMBRA_CHAIN_ID);
if (!startHeight || !tokenIn || !tokenOut || !limit) {
res.status(400).json({ error: "Invalid query parameters" }); return;
}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/simulations/[...params].ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default async function simulationHandler(
}

// Get token 1 & 2
const tokenAssets = fetchAllTokenAssets();
const tokenAssets = fetchAllTokenAssets(process.env.PENUMBRA_CHAIN_ID);
const asset1Token = tokenAssets.find(
(x) => x.display.toLocaleLowerCase() === token1.toLocaleLowerCase()
);
Expand Down
20 changes: 16 additions & 4 deletions src/pages/block/[block_height].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { BlockDetailedSummaryData } from "@/utils/types/block";
import { BlockInfo, LiquidityPositionEvent } from "@/utils/indexer/types/lps";
import { SwapExecutionWithBlockHeight } from "@/utils/protos/types/DexQueryServiceClientInterface";
import { LoadingSpinner } from "@/components/util/loadingSpinner";
import { Constants } from "@/utils/configConstants.ts";
import { formatTimestampShort } from "@/components/blockTimestamp";
import { AddIcon, MinusIcon } from "@chakra-ui/icons";
import { innerToBech32Address } from "@/utils/math/bech32";
Expand All @@ -25,9 +24,11 @@ import {
SwapExecution_Trace,
} from "@penumbra-zone/protobuf/penumbra/core/component/dex/v1/dex_pb";
import BigNumber from "bignumber.js";
import { fetchAllTokenAssets } from "@/utils/token/tokenFetch";
import { useTokenAssets } from "@/utils/token/tokenFetch";
import { Token } from "@/utils/types/token";
import { fromBaseUnit } from "@/utils/math/hiLo";
import { getClientSideEnvs } from "@/utils/env/getClientSideEnvs";
import { useEnvContext } from "@/utils/env/context";

export const Price = ({
trace,
Expand Down Expand Up @@ -438,8 +439,9 @@ export default function Block() {
}) => {
// ! Expand default
const [isExpanded, setIsExpanded] = useState(false); // EXPAND
const tokenAssets = fetchAllTokenAssets();
const tokenAssets = useTokenAssets();
const metadataByAssetId: Record<string, Token> = {};
const envs = useEnvContext();
tokenAssets.forEach((asset) => {
metadataByAssetId[asset.inner] = {
symbol: asset.symbol,
Expand Down Expand Up @@ -653,7 +655,7 @@ export default function Block() {
</Text>
<Text>
<a
href={Constants.cuiloaUrl + "/block/" + blockHeight}
href={envs.PENUMBRA_CUILOA_URL + "/block/" + blockHeight}
target="_blank"
rel="noreferrer"
style={{
Expand Down Expand Up @@ -704,3 +706,13 @@ export default function Block() {
</Layout>
);
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two thoughts:

  • Can we put this at a kind of parent layout component so we don't have to do this for every page we create (and need to remember or else risk errors)?
  • What if we created an backend API route for returning this and we put it in react-query (client side) instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Unfortunately with this implementation it seems to be not possible
  • Perhaps that's a better approach

11 changes: 11 additions & 0 deletions src/pages/explorer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Layout from "../../components/layout";
import { LPSearchBar } from "../../components/lpSearchBar";
import Blocks from '../../components/blocks'
import Swaps from '../../components/swaps'
import { getClientSideEnvs } from "@/utils/env/getClientSideEnvs";

export default function Explorer() {
return (
Expand Down Expand Up @@ -33,4 +34,14 @@ export default function Explorer() {
</Box>
</Layout>
);
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
11 changes: 11 additions & 0 deletions src/pages/lp/[lp_nft_id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import TimelinePosition from "@/components/liquidityPositions/timelinePosition";
import ExecutionEvent from "@/components/liquidityPositions/executionEvent";
import { ChevronDownIcon } from "@chakra-ui/icons";
import { getClientSideEnvs } from "@/utils/env/getClientSideEnvs";

export default function LP() {
const [isLoading, setIsLoading] = useState(true);
Expand Down Expand Up @@ -359,3 +360,13 @@ export default function LP() {
</Layout>
);
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
11 changes: 11 additions & 0 deletions src/pages/lp/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import React, { useState } from "react";
import Layout from "../../components/layout";
import { VStack, Text, Center, HStack, Input, Button } from "@chakra-ui/react";
import { innerToBech32Address, bech32ToInner } from "../../utils/math/bech32";
import { getClientSideEnvs } from "@/utils/env/getClientSideEnvs";

export default function Utils() {
const [innerAddress, setInnerAddress] = useState("");
Expand Down Expand Up @@ -64,4 +65,14 @@ export default function Utils() {
</Center>
</Layout>
);
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
16 changes: 13 additions & 3 deletions src/pages/pair/[...params].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import DepthChart from "@/components/charts/depthChart";
import OHLCChart from "@/components/charts/ohlcChart";
import BuySellChart from "@/components/charts/buySellChart";
import { Token } from "@/utils/types/token";
import { fetchAllTokenAssets } from "@/utils/token/tokenFetch";
import { useTokenAssets } from "@/utils/token/tokenFetch";
import { getClientSideEnvs } from "@/utils/env/getClientSideEnvs";
// TODO: Better parameter check

// ! Important note: 'sell' side here refers to selling asset1 for asset2, so its really DEMAND for buying asset 1, anc vice versa for 'buy' side
Expand All @@ -41,6 +42,7 @@ export default function TradingPairs() {
const [error, setError] = useState<string | undefined>();
const searchParams = useSearchParams();
const [activeChart, setActiveChart] = useState<"Depth" | "OHLC">("Depth");
const tokenAssets = useTokenAssets();

// Pairs are in the form of baseToken:quoteToken
const router = useRouter();
Expand Down Expand Up @@ -140,7 +142,6 @@ export default function TradingPairs() {
setIsLoading(true);

// Get token 1 & 2
const tokenAssets = fetchAllTokenAssets();
const asset1Token = tokenAssets.find(
(x) => x.display.toLocaleLowerCase() === token1Symbol.toLocaleLowerCase()
);
Expand Down Expand Up @@ -248,7 +249,6 @@ export default function TradingPairs() {

try {
// Get token 1 & 2
const tokenAssets = fetchAllTokenAssets();
const asset1Token = tokenAssets.find(
(x) =>
x.display.toLocaleLowerCase() === token1Symbol.toLocaleLowerCase()
Expand Down Expand Up @@ -755,3 +755,13 @@ export default function TradingPairs() {
</Layout>
);
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
16 changes: 14 additions & 2 deletions src/pages/pair/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@
import { useState, useEffect } from 'react';
import { VStack, HStack, Box, Select, Button, Avatar } from '@chakra-ui/react';
import Layout from '@/components/layout';
import { fetchAllTokenAssets } from '@/utils/token/tokenFetch';
import { useTokenAssets } from '@/utils/token/tokenFetch';
import { LoadingSpinner } from '@/components/util/loadingSpinner';
import { Token } from '@/utils/types/token';
import { getClientSideEnvs } from '@/utils/env/getClientSideEnvs';

export default function Pairs() {
const [isLoading, setIsLoading] = useState(true);
const [tokenAssets, setTokenAssets] = useState<Token[]>([]);
const tokenAssetsList = useTokenAssets();

const [firstAsset, setFirstAsset] = useState('');
const [secondAsset, setSecondAsset] = useState('');

useEffect(() => {
setIsLoading(true)
const tokens : Token[] = fetchAllTokenAssets().sort((a, b) => a.display > b.display ? 1 : b.display > a.display ? -1 : 0);
const tokens : Token[] = tokenAssetsList.sort((a, b) => a.display > b.display ? 1 : b.display > a.display ? -1 : 0);
if (tokens.length > 0 && tokenAssets.length === 0) {
setTokenAssets(tokens)
}
Expand Down Expand Up @@ -72,3 +74,13 @@ export default function Pairs() {
</Layout>
)
}

export async function getServerSideProps() {
const envs = getClientSideEnvs();

return {
props: {
envs,
},
};
}
Loading
Loading