Use Case

Make sure that the TWAP price reported by an oracle doesn’t deviate more than X% from the pre-state TWAP price. A lot of DeFi protocols use TWAP to price their assets. This assertions makes sure that the TWAP price stays within a reasonable range defined by the protocol.

Explanation

In this example we check that the TWAP price doesn’t deviate more than 5% from the pre-state TWAP price.

Code Example

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {Assertion} from "../../lib/credible-std/src/Assertion.sol";

interface IPool {
    function price() external view returns (uint256);

    function twap() external view returns (uint256);
}

// Checks that the pool price doesn't deviate more than 5% from the twap
contract TwapDeviationAssertion is Assertion {
    IPool public pool = IPool(address(0xbeef));

    function fnSelectors() external pure override returns (bytes4[] memory assertions) {
        assertions = new bytes4[](1);
        assertions[0] = this.assertionTwapDeviation.selector;
    }

    // Make sure that the price doesn't deviate more than 5% from the twap
    // revert if the price deviation is too large
    function assertionTwapDeviation() external {
        ph.forkPostState();
        uint256 currentPrice = pool.price();
        uint256 twapPrice = pool.twap();
        uint256 maxDeviation = 5; // 5% deviation, define this according to your protocol
        uint256 deviation =
            (((currentPrice > twapPrice) ? currentPrice - twapPrice : twapPrice - currentPrice) * 100) / twapPrice;
        require(deviation <= maxDeviation, "Price deviation is too large");
    }
}