import { ethers } from "ethers";
import { toHumanReadable } from "@injectivelabs/utils";
const provider = new ethers.JsonRpcProvider(
"https://sentry.evm-rpc.injective.network",
);
const IPythABI = [
{
inputs: [{ internalType: "bytes[]", name: "updateData", type: "bytes[]" }],
name: "getUpdateFee",
outputs: [{ internalType: "uint256", name: "feeAmount", type: "uint256" }],
stateMutability: "view",
type: "function",
},
{
inputs: [{ internalType: "bytes[]", name: "updateData", type: "bytes[]" }],
name: "updatePriceFeeds",
outputs: [],
stateMutability: "payable",
type: "function",
},
{
inputs: [
{ internalType: "bytes32", name: "id", type: "bytes32" },
{ internalType: "uint256", name: "age", type: "uint256" },
],
name: "getPriceNoOlderThan",
outputs: [
{
components: [
{ internalType: "int64", name: "price", type: "int64" },
{ internalType: "uint64", name: "conf", type: "uint64" },
{ internalType: "int32", name: "expo", type: "int32" },
{ internalType: "uint256", name: "publishTime", type: "uint256" },
],
internalType: "struct PythStructs.Price",
name: "price",
type: "tuple",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [{ internalType: "bytes32", name: "id", type: "bytes32" }],
name: "getPriceUnsafe",
outputs: [
{
components: [
{ internalType: "int64", name: "price", type: "int64" },
{ internalType: "uint64", name: "conf", type: "uint64" },
{ internalType: "int32", name: "expo", type: "int32" },
{ internalType: "uint256", name: "publishTime", type: "uint256" },
],
internalType: "struct PythStructs.Price",
name: "price",
type: "tuple",
},
],
stateMutability: "view",
type: "function",
},
] as const;
const pyth = new ethers.Contract(
"0x36825bf3Fbdf5a29E2d5148bfe7Dcf7B5639e320",
IPythABI,
provider,
);
async function main() {
try {
const priceFeedId =
"0x7a5bc1d2b56ad029048cd63964b3ad2776eadf812edc1a43a31406cb54bff592"; // INJ/USD
// const price = await pyth.getPriceUnsafe(priceFeedId);
const maxAge = 60; // 60s
const price = await pyth.getPriceNoOlderThan(priceFeedId, maxAge);
console.log(
"Human readable price:",
price.expo > 0
? toHumanReadable(price.price.toString(), price.expo.toString()).toFixed(2)
: toHumanReadable(price.price.toString(), (-price.expo).toString()).toFixed(4),
);
} catch (error) {
console.error(error);
} finally {
await provider.destroy();
}
}
main().catch(console.error);