/*
 * last modified---
 * 	03-18-25 new
 *
 * purpose---
 * 	class to provide chain.link aggregatorV3InterfaceABI price feeds
 */

const BigNumber = require("bignumber.js");

// implement V3 chain.link interface
class ChainLinkPriceFeed {
	constructor() {
		this.aggregatorV3InterfaceABI = [
			{
				inputs: [],
				name: "decimals",
				outputs: [{ internalType: "uint8", name: "", type: "uint8" }],
				stateMutability: "view",
				type: "function",
			},
			{
				inputs: [],
				name: "description",
				outputs: [{ internalType: "string", name: "", type: "string" }],
				stateMutability: "view",
				type: "function",
			},
			{
				inputs: [{ internalType: "uint80", name: "_roundId", type: "uint80" }],
				name: "getRoundData",
				outputs: [
				  { internalType: "uint80", name: "roundId", type: "uint80" },
				  { internalType: "int256", name: "answer", type: "int256" },
				  { internalType: "uint256", name: "startedAt", type: "uint256" },
				  { internalType: "uint256", name: "updatedAt", type: "uint256" },
				  { internalType: "uint80", name: "answeredInRound", type: "uint80" },
				],
				stateMutability: "view",
				type: "function",
			},
			{
				inputs: [],
				name: "latestRoundData",
				outputs: [
				  { internalType: "uint80", name: "roundId", type: "uint80" },
				  { internalType: "int256", name: "answer", type: "int256" },
				  { internalType: "uint256", name: "startedAt", type: "uint256" },
				  { internalType: "uint256", name: "updatedAt", type: "uint256" },
				  { internalType: "uint80", name: "answeredInRound", type: "uint80" },
				],
				stateMutability: "view",
				type: "function",
			},
			{
				inputs: [],
				name: "version",
				outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
				stateMutability: "view",
				type: "function",
			},
		];
	}

	/* method to fetch the price of a given contract
	 * @param web3 the Web3 object
	 * @param feed the address of the price feed at chain.link for this chain
	 * @return the current price (as an object), undefined if not found
	 */
	async getPrice(web3, feed) {
		var priceData = undefined;
		if (feed === '' || feed === undefined || web3 === undefined)
			return priceData;
		const prFeed
			= new web3.eth.Contract(this.aggregatorV3InterfaceABI, feed);
		await prFeed.methods.latestRoundData().call()
			.then((roundData) => {
				// the .answer field is the price, scaled by 1e8
				priceData = new BigNumber(roundData.answer).dividedBy("1e8")
							.decimalPlaces(4);
			});
		return priceData;
	}
}

export default ChainLinkPriceFeed;
