Skip to content

Commit

Permalink
feat: added apiurl in config gile
Browse files Browse the repository at this point in the history
  • Loading branch information
evandrosaturnino authored and benlongstaff committed Sep 3, 2022
1 parent 1d55a5e commit 93b17e7
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ echo_config() {
echo '{'
[ -n "$TESTNET_ONLY" ] && echo ' "testnetOnly": '$TESTNET_ONLY','
echo ' "frontendTag": "'$FRONTEND_TAG'",'
echo ' "infuraApiKey": "'$INFURA_API_KEY'"'
echo ' "infuraApiKey": "'$INFURA_API_KEY'",'
echo ' "BlocksApiUrl": "'$BLOCKS_API_URL'",'
echo ' "ThresholdUsdApiUrl": "'$THRESHOLD_USD_API_URL'"'
echo '}'
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,23 @@ import React, { useState, useEffect } from "react";
import { createClient } from "urql";
import { ChartContext } from "./ChartContext";

import { useLiquity } from "../../../../hooks/LiquityContext";

export type BlockObject = {
number?: string,
__typename?: string
}
};

export type tvlData = {
totalCollateral: number,
blockNumber: number
}
};

type FunctionalPanelProps = {
export type FunctionalPanelProps = {
loader?: React.ReactNode;
};

const BLOCKS_API_URL = "https://api.thegraph.com/subgraphs/name/blocklytics/goerli-blocks";
const THRESHOLD_USD_API_URL = "https://api.thegraph.com/subgraphs/name/evandrosaturnino/thresholdusd"

const fetchBlockByTimestamp = (timestamp: number) => {
const fetchBlockByTimestamp = (timestamp: number, BlocksApiUrl: string) => {
const query = `
query {
blocks(
Expand All @@ -34,12 +33,12 @@ const fetchBlockByTimestamp = (timestamp: number) => {
){
number
}
}
`
return fetchData(BLOCKS_API_URL, query)
}`

return fetchData(BlocksApiUrl, query);
};

const fetchTvlByBlock = (blockNumber: number) => {
const fetchTvlByBlock = (blockNumber: number, ThresholdUsdApiUrl: string) => {
const query = `
query {
systemStates(
Expand All @@ -53,16 +52,15 @@ const fetchTvlByBlock = (blockNumber: number) => {
totalCollateral
}
}`
return fetchData(THRESHOLD_USD_API_URL, query)

return fetchData(ThresholdUsdApiUrl, query);
};

export const createListOfTimestamps = (): Array<number> => {
const currentDate = Math.floor((Date.now() / 1000) - 120) // Get a date object for the current time;

const deltaPerPeriod = 86400; // Every 24 hours (in secs)
const numberOfPeriods = 30; // For 30 days
const startingTimestamp = currentDate - (deltaPerPeriod * numberOfPeriods); // Set it 30 days ago (in secs)

const timestamps: Array<number> = [];

for (let i = 0; i < numberOfPeriods + 1; i++) {
Expand All @@ -72,24 +70,23 @@ export const createListOfTimestamps = (): Array<number> => {
return timestamps;
};

export const queryBlocksByTimestamps = async (timestamps: Array<number>): Promise<Array<BlockObject>> => {
export const queryBlocksByTimestamps = async (timestamps: Array<number>, BlocksApiUrl: string): Promise<Array<BlockObject>> => {
const blocks: Array<BlockObject> = [];

for (const timestamp of timestamps) {
const blocksData = await fetchBlockByTimestamp(timestamp);
const blocksData = await fetchBlockByTimestamp(timestamp, BlocksApiUrl);
const block: BlockObject = blocksData.data.blocks[0];
blocks.push(block);
}; // iterating the timestamps array to query one block for each day

return blocks;
};

export const queryTvlByBlocks = async (blocks: Array<BlockObject>): Promise<Array<tvlData>> => {

export const queryTvlByBlocks = async (blocks: Array<BlockObject>, ThresholdUsdApiUrl: string): Promise<Array<tvlData>> => {
const tvlData = blocks.map(async (block) => {
const blockNumber: number = Number(block.number);

return fetchTvlByBlock(blockNumber).then((result) => {
return fetchTvlByBlock(blockNumber, ThresholdUsdApiUrl).then((result) => {
const tvlValue: tvlData = result.data ? {
totalCollateral: Number(result.data.systemStates[0].totalCollateral),
blockNumber: blockNumber
Expand All @@ -104,40 +101,49 @@ export const queryTvlByBlocks = async (blocks: Array<BlockObject>): Promise<Arra
return Promise.all(tvlData)
};

export const queryTVL = async (): Promise<Array<tvlData>> => {
export const queryTVL = async (BlocksApiUrl: string, ThresholdUsdApiUrl: string): Promise<Array<tvlData>> => {
const timestamps: Array<number> = createListOfTimestamps();
return await queryBlocksByTimestamps(timestamps).then(
return await queryBlocksByTimestamps(timestamps, BlocksApiUrl).then(
async (blocks) => {
const tvl = await queryTvlByBlocks(blocks);
return tvl
const tvl = await queryTvlByBlocks(blocks, ThresholdUsdApiUrl);
return tvl;
}
);
}
};

async function fetchData(API_URL: string, query: string) {
const client = createClient({
url: API_URL
});

const response = await client.query(query).toPromise();
return response;
}
};

export const ChartProvider: React.FC<FunctionalPanelProps> = ({ children, loader }) => {
const timestamps: Array<number> = createListOfTimestamps();
const [tvl, setTvl] = useState<Array<tvlData>>();
const [isMounted, setIsMounted] = useState<boolean>(true);

const { config, provider } = useLiquity();
const { BlocksApiUrl, ThresholdUsdApiUrl } = config;

useEffect(() => {
if (isMounted) {
queryTVL().then(
(result) => {
if (!isMounted) return null
provider.getNetwork().then((network) => {
const networkName = network.name === 'homestead' ? 'ethereum' : network.name;
const BlocksUrlByNetwork = `https://${BlocksApiUrl}/${networkName}-blocks`;
const ThresholdUrlByNetwork = `https://${ThresholdUsdApiUrl}/${networkName}-thresholdusd`;

console.log('ThresholdUrlByNetwork: ', ThresholdUrlByNetwork)
console.log('BlocksUrlByNetwork: ', BlocksUrlByNetwork)

queryTVL(BlocksUrlByNetwork, ThresholdUrlByNetwork).then(
(result) => {
if (!isMounted) return null;
setTvl(result);
return tvl
return tvl;
}
);
)});
}
return () => {
setIsMounted(false);
Expand All @@ -147,11 +153,12 @@ export const ChartProvider: React.FC<FunctionalPanelProps> = ({ children, loader

if (!timestamps || !tvl) {
return <>{loader}</>
}
};

const provider = {
const chartProvider = {
tvl,
timestamps
};
return <ChartContext.Provider value={provider}>{children}</ChartContext.Provider>;

return <ChartContext.Provider value={chartProvider}>{children}</ChartContext.Provider>;
};
34 changes: 29 additions & 5 deletions packages/dev-frontend/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
export type LiquityFrontendConfig = {
export type ThresholdConfig = {
infuraApiKey?: string;
testnetOnly?: boolean;
BlocksApiUrl?: string;
ThresholdUsdApiUrl?: string;
};

const defaultConfig: LiquityFrontendConfig = {
const defaultConfig: ThresholdConfig = {
};

function hasKey<K extends string>(o: object, k: K): o is Record<K, unknown> {
return k in o;
}

const parseConfig = (json: unknown): LiquityFrontendConfig => {
const parseConfig = (json: unknown): ThresholdConfig => {
const config = { ...defaultConfig };

if (typeof json === "object" && json !== null) {
Expand All @@ -35,6 +37,28 @@ const parseConfig = (json: unknown): LiquityFrontendConfig => {
console.log(testnetOnly);
}
}

if (hasKey(json, "BlocksApiUrl") && json.BlocksApiUrl !== "") {
const { BlocksApiUrl } = json;

if (typeof BlocksApiUrl === "string") {
config.BlocksApiUrl = BlocksApiUrl;
} else {
console.error("Malformed BlocksApiUrl:");
console.log(BlocksApiUrl);
}
}

if (hasKey(json, "ThresholdUsdApiUrl") && json.ThresholdUsdApiUrl !== "") {
const { ThresholdUsdApiUrl } = json;

if (typeof ThresholdUsdApiUrl === "string") {
config.ThresholdUsdApiUrl = ThresholdUsdApiUrl;
} else {
console.error("Malformed ThresholdUsdApiUrl:");
console.log(ThresholdUsdApiUrl);
}
}
} else {
console.error("Malformed config:");
console.log(json);
Expand All @@ -43,7 +67,7 @@ const parseConfig = (json: unknown): LiquityFrontendConfig => {
return config;
};

let configPromise: Promise<LiquityFrontendConfig> | undefined = undefined;
let configPromise: Promise<ThresholdConfig> | undefined = undefined;

const fetchConfig = async () => {
try {
Expand All @@ -60,7 +84,7 @@ const fetchConfig = async () => {
}
};

export const getConfig = (): Promise<LiquityFrontendConfig> => {
export const getConfig = (): Promise<ThresholdConfig> => {
if (!configPromise) {
configPromise = fetchConfig();
}
Expand Down
6 changes: 3 additions & 3 deletions packages/dev-frontend/src/hooks/LiquityContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import {
_connectByChainId
} from "@liquity/lib-ethers";

import { LiquityFrontendConfig, getConfig } from "../config";
import { ThresholdConfig, getConfig } from "../config";

type LiquityContextValue = {
config: LiquityFrontendConfig;
config: ThresholdConfig;
account: string;
provider: Provider;
liquity: EthersLiquityWithStore<BlockPolledLiquityStore>;
Expand Down Expand Up @@ -43,7 +43,7 @@ export const LiquityProvider: React.FC<LiquityProviderProps> = ({
unsupportedMainnetFallback
}) => {
const { library: provider, account, chainId } = useWeb3React<Web3Provider>();
const [config, setConfig] = useState<LiquityFrontendConfig>();
const [config, setConfig] = useState<ThresholdConfig>();

const connection = useMemo(() => {
if (config && provider && account && chainId) {
Expand Down

0 comments on commit 93b17e7

Please sign in to comment.