{
    "Function": "_calcTwap",
    "File": "contracts/AMM.sol",
    "Parent Contracts": [
        "contracts/legos/Governable.sol",
        "node_modules/@openzeppelin/contracts/proxy/utils/Initializable.sol",
        "contracts/legos/Governable.sol",
        "contracts/Interfaces.sol"
    ],
    "High-Level Calls": [],
    "Internal Calls": [
        "_blockTimestamp",
        "_blockTimestamp"
    ],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "function _calcTwap(uint256 _intervalInSeconds)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 snapshotIndex = reserveSnapshots.length - 1;\n        uint256 currentPrice = reserveSnapshots[snapshotIndex].lastPrice;\n        if (_intervalInSeconds == 0) {\n            return currentPrice;\n        }\n\n        uint256 baseTimestamp = _blockTimestamp() - _intervalInSeconds;\n        ReserveSnapshot memory currentSnapshot = reserveSnapshots[snapshotIndex];\n        // return the latest snapshot price directly\n        // if only one snapshot or the timestamp of latest snapshot is earlier than asking for\n        if (reserveSnapshots.length == 1 || currentSnapshot.timestamp <= baseTimestamp) {\n            return currentPrice;\n        }\n\n        uint256 previousTimestamp = currentSnapshot.timestamp;\n        uint256 period = _blockTimestamp() - previousTimestamp;\n        uint256 weightedPrice = currentPrice * period;\n        while (true) {\n            // if snapshot history is too short\n            if (snapshotIndex == 0) {\n                return weightedPrice / period;\n            }\n\n            snapshotIndex = snapshotIndex - 1;\n            currentSnapshot = reserveSnapshots[snapshotIndex];\n            currentPrice = reserveSnapshots[snapshotIndex].lastPrice;\n\n            // check if current round timestamp is earlier than target timestamp\n            if (currentSnapshot.timestamp <= baseTimestamp) {\n                // weighted time period will be (target timestamp - previous timestamp). For example,\n                // now is 1000, _interval is 100, then target timestamp is 900. If timestamp of current round is 970,\n                // and timestamp of NEXT round is 880, then the weighted time period will be (970 - 900) = 70,\n                // instead of (970 - 880)\n                weightedPrice = weightedPrice + (currentPrice * (previousTimestamp - baseTimestamp));\n                break;\n            }\n\n            uint256 timeFraction = previousTimestamp - currentSnapshot.timestamp;\n            weightedPrice = weightedPrice + (currentPrice * timeFraction);\n            period = period + timeFraction;\n            previousTimestamp = currentSnapshot.timestamp;\n        }\n        return weightedPrice / _intervalInSeconds;\n    }"
}