Files
js/pages/api/gas.ts
T
Nacho Iacovino 556b4f4a50 Gas estimator (#30)
* Add mapping

* Basic modal with gas price

* Fetch gas price from etherscan

* Only 4 decimals

* Make /gas a page

* Create gas endpoint

* Show USD value

* Built switch

* Linting

* Make ETH the default

* Prettier pls

* Fix styles

* Fix corner

* Border color change

* Add useGas query

* Add defaults

* Fetch data only once

* Use try/catch and promise.all

* Consistent naming

* Move default inside parenthesis

* Use parenthesis

* Prettier pls

* Add undefined to possible type

* Fix error status

* Add key directly to query

* Add links to portal

* Add tooltips

* Add disclaimer

* Add ethereum badge

* Add external link icon

* Make Switch smaller

* Use semantic borderColor
2022-03-30 16:43:33 +02:00

36 lines
1.2 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from "next";
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method !== "GET") {
return res.status(400).json({ error: "invalid method" });
}
const gasPriceEndpoint = `https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=${process.env.ETHERSCAN_KEY}`;
const ethPriceEndpoint = `https://api.etherscan.io/api?module=stats&action=ethprice&apikey=${process.env.ETHERSCAN_KEY}`;
const gasPrice = fetch(gasPriceEndpoint);
const ethPrice = fetch(ethPriceEndpoint);
try {
const [gasPriceRes, ethPriceRes] = await Promise.all([gasPrice, ethPrice]);
const gasData = await gasPriceRes.json();
const ethPriceData = await ethPriceRes.json();
if (!gasData?.result) {
return res.status(400).json({ error: "Failed to fetch gas price" });
}
if (!ethPriceData?.result) {
return res.status(400).json({ error: "Failed to fetch ETH price" });
}
return res.status(200).json({
gasPrice: gasData.result.ProposeGasPrice,
ethPrice: ethPriceData.result.ethusd,
});
} catch (err) {
console.error(err);
return res.status(502).json({ error: "Invalid response" });
}
};