Skip to content

Commit 12e6dbe

Browse files
authored
Merge pull request #28 from perpetual-protocol/feat/fix-consider-interval-when-get-cached-TWAP
feat: consider interval when get cached TWAP
2 parents e4a64cf + 7526687 commit 12e6dbe

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

contracts/twap/CachedTwap.sol

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ abstract contract CachedTwap is CumulativeTwap {
4040
uint256 latestPrice,
4141
uint256 latestUpdatedTimestamp
4242
) internal view returns (uint256) {
43-
if (_blockTimestamp() == _lastUpdatedAt) {
43+
if (_blockTimestamp() == _lastUpdatedAt && interval == _interval) {
4444
return _cachedTwap;
4545
}
4646
return _calculateTwapPrice(interval, latestPrice, latestUpdatedTimestamp);

test/CachedTwap.spec.ts

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ describe("Cached Twap Spec", () => {
5050
let testPriceFeed: TestPriceFeed
5151
let round: number
5252

53+
async function setNextBlockTimestamp(timestamp: number) {
54+
await ethers.provider.send("evm_setNextBlockTimestamp", [timestamp])
55+
await ethers.provider.send("evm_mine", [])
56+
}
57+
5358
async function updatePrice(price: number, forward: boolean = true): Promise<void> {
5459
await bandReference.setReferenceData({
5560
rate: parseEther(price.toString()),
@@ -63,12 +68,11 @@ describe("Cached Twap Spec", () => {
6368

6469
if (forward) {
6570
currentTime += 15
66-
await ethers.provider.send("evm_setNextBlockTimestamp", [currentTime])
67-
await ethers.provider.send("evm_mine", [])
71+
await setNextBlockTimestamp(currentTime)
6872
}
6973
}
7074

71-
before(async () => {
75+
beforeEach(async () => {
7276
const _fixture = await loadFixture(priceFeedFixture)
7377
bandReference = _fixture.bandReference
7478
bandPriceFeed = _fixture.bandPriceFeed
@@ -127,5 +131,25 @@ describe("Cached Twap Spec", () => {
127131

128132
expect(price1.cachedTwap).to.not.eq(price2.cachedTwap)
129133
})
134+
135+
it("re-calculate twap if block timestamp is different from last cached twap timestamp", async () => {
136+
const price1 = await testPriceFeed.callStatic.getPrice(45)
137+
await testPriceFeed.getPrice(45)
138+
139+
// forword block timestamp 15sec
140+
currentTime += 15
141+
await setNextBlockTimestamp(currentTime)
142+
143+
const price2 = await bandPriceFeed.getPrice(45)
144+
expect(price2).to.not.eq(price1.twap)
145+
})
146+
147+
it("re-calculate twap if interval is different from interval of cached twap", async () => {
148+
await bandPriceFeed.cacheTwap(45)
149+
const price1 = await bandPriceFeed.getPrice(45)
150+
const price2 = await bandPriceFeed.getPrice(15)
151+
// shoule re-calculate twap
152+
expect(price2).to.not.eq(price1)
153+
})
130154
})
131155
})

0 commit comments

Comments
 (0)